baixingwenzheng-pc/dist/assets/live_info.5b582beb.js
2024-08-05 18:00:52 +08:00

8 lines
475 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import{_ as _sfc_main$1,F as Footer}from"./Footer.f740febe.js";import{o as broadcastInfo}from"./index.e55b68a5.js";import{d as defineComponent,q as useRouter,l as useMessage,m as ref,s as onMounted,o as openBlock,t as createElementBlock,b as createVNode,g as createBaseVNode,A as toDisplayString,F as Fragment$1}from"./vendor.cf21d8e3.js";/* empty css */var muiPlayer_min={exports:{}};
/*!
* Mui Player Javascript Library v1.8.1 @Professional edition
* Date2023-01-28
* Released under GPL-3.0 license
* https://muiplayer.js.org/
*/(function(module,exports){function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray(e)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}function _createForOfIteratorHelper(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var i=0;return{s:t=function(){},n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:t}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,n=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return n=e.done,e},e:function(e){a=!0,s=e},f:function(){try{n||null==r.return||r.return()}finally{if(a)throw s}}}}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Map"===(r="Object"===r&&e.constructor?e.constructor.name:r)||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=new Array(t);r<t;r++)i[r]=e[r];return i}function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var e,t;e=window,t=function(){var MuiPlayer=function MuiPlayer(config){var _this=this;_this._global_={};var webpagePlugin="",mobilePlugin="",hls=null,flv=null,option=config||{},plugins=option.plugins||[];this._event_={};var con="string"==typeof option.container?document.querySelector(option.container):option.container,$CONSTANT,$habit,$node,$global,element,$el,variable,$data,$method;con&&($CONSTANT={unitLengthReg:/^(auto|inherit|initial|\d+(\.\d+)?(\%|px|cm|mm|em|rem|vw|vh|)?)$/i,encodeKey:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"},$habit={themeColor:"#1e98d4"},$node={video:'\x3c!-- HTML5 Video --\x3e<div class="video-wrapper"><video width="100%" height="100%"></video></div>',mplayerPoster:'<div class="mplayer-poster" id="mplayer-poster"></div>',mplayerCover:'\x3c!-- 媒体播放遮罩层 --\x3e<div class="mplayer-cover" id="mplayer-cover"></div>',mplayerLoading:'\x3c!-- Mplayer加载Loading --\x3e<div class="mplayer-loading"id="mplayer-loading"control><svg viewBox="25 25 50 50"class="mplayer-loading__circular"><circle cx="50"cy="50"r="20"fill="none"></circle></svg></div>',mplayerError:'\x3c!-- 视频加载错误显示 --\x3e<div class="mplayer-error"id="mplayer-error"control><div class="errop-tip">视频加载失败,点击刷新</div><svg t="1575125481608"class="icon"viewBox="0 0 1024 1024"version="1.1"xmlns="http://www.w3.org/2000/svg"p-id="5893"width="28"height="28"><path d="M513.34 831.74C337.03 831.74 193.6 688.31 193.6 512c0-71.09 23.31-138.85 65.53-194.03v51.61c0 17.67 14.33 32 32 32s32-14.33 32-32V239.45c0-5.87-1.59-11.36-4.34-16.09-0.06-0.1-0.11-0.2-0.17-0.3-0.16-0.28-0.34-0.55-0.51-0.82-0.13-0.2-0.26-0.41-0.39-0.61-0.08-0.13-0.17-0.25-0.26-0.37a35.5 35.5 0 0 0-1.58-2.13c-6.81-8.35-16.96-12.35-26.95-11.69h-130c-17.67 0-32 14.33-32 32s14.33 32 32 32h55.35C159.8 339 129.6 423.35 129.6 512c0 51.79 10.15 102.05 30.17 149.38 19.33 45.7 46.99 86.74 82.23 121.97 35.23 35.23 76.27 62.9 121.97 82.23 47.33 20.02 97.59 30.17 149.38 30.17 17.67 0 32-14.33 32-32s-14.34-32.01-32.01-32.01zM855.38 762.3h-51.23c19.81-23 36.93-48.3 50.75-75.22 27.6-53.74 42.18-114.28 42.18-175.08 0-51.79-10.15-102.05-30.17-149.38-19.33-45.7-46.99-86.73-82.23-121.97-35.23-35.23-76.27-62.9-121.97-82.23-47.33-20.02-97.59-30.17-149.38-30.17-17.67 0-32 14.33-32 32s14.33 32 32 32c176.31 0 319.74 143.44 319.74 319.74 0 78.31-27.68 151.61-77.6 209.05l0.24-56.04c0.08-17.67-14.19-32.06-31.86-32.14h-0.14c-17.61 0-31.92 14.24-32 31.86l-0.55 129.43a31.988 31.988 0 0 0 9.32 22.71 31.68 31.68 0 0 0 5.33 4.3c0.02 0.01 0.04 0.02 0.06 0.04 0.48 0.31 0.97 0.61 1.47 0.89l0.15 0.09c0.5 0.28 1 0.54 1.51 0.8 0.03 0.01 0.05 0.03 0.08 0.04 1.64 0.8 3.34 1.46 5.1 1.98 0.01 0 0.02 0.01 0.03 0.01 0.55 0.16 1.1 0.3 1.66 0.43 0.07 0.02 0.15 0.03 0.22 0.05 0.5 0.11 1 0.21 1.5 0.3 0.1 0.02 0.2 0.04 0.3 0.05 0.48 0.08 0.96 0.15 1.44 0.21 0.11 0.01 0.23 0.03 0.34 0.04 0.48 0.05 0.95 0.09 1.43 0.12l0.34 0.03c0.53 0.03 1.07 0.04 1.61 0.05h132.31c17.67 0 32-14.33 32-32s-14.31-31.99-31.98-31.99z"p-id="5894"fill="#ffffff"></path></svg></div>',mplayerHeader:'\x3c!-- Mplayer 顶部导航 --\x3e<div class="mplayer-header"id="mplayer-header"><div class="title-groupt"id="title-groupt"><button class="player-btn header-control back-button keyboard-input"id="back-button"control><svg id="back-icon-svg"t="1573891955387"viewBox="0 0 1024 1024"version="1.1"xmlns="http://www.w3.org/2000/svg"p-id="4550"width="18"height="18"><path d="M305.519192 557.640404c-11.636364 0-23.40202-4.39596-32.323232-13.317172-17.842424-17.842424-17.842424-46.674747 0-64.517171L683.830303 69.30101c17.842424-17.842424 46.674747-17.842424 64.517172 0 17.842424 17.842424 17.842424 46.674747 0 64.517172L337.713131 544.323232c-8.921212 8.921212-20.557576 13.317172-32.193939 13.317172z m0 0"fill="#ffffff"p-id="4551"></path><path d="M715.894949 968.145455c-11.636364 0-23.40202-4.39596-32.323232-13.317172L273.19596 544.323232c-17.842424-17.842424-17.842424-46.674747 0-64.517171 17.842424-17.842424 46.674747-17.842424 64.517171 0l410.505051 410.50505c17.842424 17.842424 17.842424 46.674747 0 64.517172-8.921212 8.921212-20.557576 13.317172-32.323233 13.317172z m0 0"fill="#ffffff"p-id="4552"></path></svg><div class="title-name"id="title-name"></div></button></div><div class="buttom-group"id="buttom-group"></div></div>',mplayerFooter:'\x3c!-- Mplayer 底部操作控件 --\x3e<div class="mplayer-footer"id="mplayer-footer"><div class="progress"id="progress"><div class="left-part"id="left-part"><button class="player-btn keyboard-input play-switch footer-control"id="play-switch"control>\x3c!--play button--\x3e<div class="_play"><svg t="1574051894346"viewBox="0 0 1024 1024"version="1.1"xmlns="http://www.w3.org/2000/svg"p-id="1212"><path d="M324.085 95.787l500.422 300.664c82.373 50.453 79.284 136.946-1.030 186.37v0l-506.6 304.784c-41.187 23.683-87.522 37.068-131.798 9.267-36.037-22.653-46.335-58.691-46.335-97.819v-616.774c0-39.127 13.386-75.166 48.395-97.819 45.305-27.801 94.731-14.416 136.946 11.327v0z"p-id="1213"fill="#ffffff"></path></svg></div>\x3c!--pause button--\x3e<div class="_pause"style="display: none;"><svg t="1574051952939"viewBox="0 0 1024 1024"version="1.1"xmlns="http://www.w3.org/2000/svg"p-id="1434"><path d="M248.26311111 515.072c0-110.592-0.22755555-221.184 0.11377778-331.776 0.11377778-35.84 18.20444445-60.87111111 49.26577778-70.99733333 27.53422222-8.87466667 56.88888889 0.34133333 75.32088888 23.77955555 10.58133333 13.42577778 15.13244445 28.89955555 15.01866667 45.96622223-0.11377778 223.11822222 0.11377778 446.23644445-0.22755555 669.35466666-0.11377778 42.55288889-31.06133333 73.27288889-70.54222222 72.81777778-39.25333333-0.45511111-68.72177778-31.51644445-68.94933334-74.52444444-0.34133333-111.50222222 0-223.11822222 0-334.62044445zM638.52088889 516.66488889V193.64977778c0-52.45155555 27.42044445-85.21955555 70.54222222-84.65066667 42.43911111 0.56888889 69.17688889 32.42666667 69.17688889 83.05777778 0.11377778 218.22577778 0.11377778 436.56533333 0 654.79111111 0 38.34311111-17.29422222 63.60177778-49.152 73.95555555-27.648 8.98844445-56.54755555 0-75.43466667-23.552-12.17422222-15.13244445-15.36-32.768-15.24622222-51.76888888 0.22755555-109.568 0.11377778-219.136 0.11377778-328.81777778z"p-id="1435"fill="#ffffff"></path></svg></div></button>\x3c!--直播模式--\x3e<button class="player-btn live-mode footer-control"id="live-mode"control><div class="spot"></div><div class="mode-text">直播</div></button></div>\x3c!--底部进度容器--\x3e<div class="progress-container"id="progress-container">\x3c!--安全进度时长--\x3e<div class="progress-begin"id="progress-begin">开始</div>\x3c!--拖动有效的作用域--\x3e<div class="touch-effective"id="touch-effective">\x3c!--加载进度条总长--\x3e<div class="progress-total"id="progress-total"></div>\x3c!--资源缓存进度--\x3e<div class="progress-buffered"id="progress-buffered"></div>\x3c!--播放进度--\x3e<div class="progress-play"id="progress-play"></div>\x3c!--拖动进度球--\x3e<div class="ball-container"><div class="progress-drag"id="progress-ball"><div class="progress-ball"></div></div></div></div>\x3c!--总时长--\x3e<div class="progress-long"id="progress-long">结束</div></div><div class="right-part"id="right-part">\x3c!--全屏开关--\x3e<button class="player-btn keyboard-input full-switch footer-control"id="full-switch"tooltip="全屏"control><div class="_full"><svg t="1607611836872"class="icon"viewBox="0 0 1024 1024"version="1.1"xmlns="http://www.w3.org/2000/svg"p-id="2384"><path d="M842 797.08l-226.07999999-226.08a30 30 0 0 0-42.42000001 42.42000001L799.58 839.5 692 839.5a30 30 0 0 0 0 60L872 899.5a29.91 29.91 0 0 0 30-29.99999999l0-180a30 30 0 0 0-60 0l0 107.57999999zM130.79 128.29A29.91 29.91 0 0 1 152 119.5l180 0a30 30 0 0 1 0 60l-107.58 0 226.08 226.08a30 30 0 0 1-42.42000001 42.42L182 221.92 182 329.50000001a30 30 0 0 1-60 0L122 149.50000001a29.91 29.91 0 0 1 8.79-21.21000001z"fill="#ffffff"p-id="2385"></path></svg></div><div class="_unfull"style="display: none;"><svg t="1607611848290"class="icon"viewBox="0 0 1024 1024"version="1.1"xmlns="http://www.w3.org/2000/svg"p-id="2546"><path d="M416.00000001 370.752L174.848 129.59999999a32 32 0 0 0-45.24800001 45.24800001L370.752 416.00000001 256 416a32 32 0 0 0 0 64l192 0a31.904 31.904 0 0 0 32-32L480 256a32 32 0 0 0-64 0l1e-8 114.752z m137.37599999 182.624A31.904 31.904 0 0 1 576 544L768 544a32 32 0 0 1 0 64l-114.752-1e-8 241.15200001 241.15200001a32 32 0 1 1-45.24800001 45.24800001L607.99999999 653.248 608 768a32 32 0 0 1-64 0l0-192a31.904 31.904 0 0 1 9.376-22.624z"fill="#ffffff"p-id="2547"></path></svg></div></button></div></div></div>',miniProgress:'\x3c!-- Mplayer 底部播放迷你进度条 --\x3e<div class="mini-progress"id="mini-progress">\x3c!--加载进度条总长--\x3e<div class="mini-total"id="mini-total"></div>\x3c!--资源缓存进度--\x3e<div class="mini-buffered"id="mini-buffered"></div>\x3c!--播放进度--\x3e<div class="mini-play"id="mini-play"></div></div>'},$global=function(){return{first_authplay:!1,isReady:!1,webpagePlugin:{},mobilePlugin:{},cssAutoprefixer:["webkit","ms","moz","o"]}},element=function(){return{mPlayer:con,videoObject:con.querySelector("video"),mplayerCover:con.querySelector("#mplayer-cover"),mplayerPoster:con.querySelector("#mplayer-poster"),mplayerHeader:con.querySelector("#mplayer-header"),headerMenu:con.querySelector("#buttom-group"),backButton:con.querySelector("#back-button"),mplayerFooter:con.querySelector("#mplayer-footer"),progressContainer:con.querySelector("#progress-container"),playSwitch:con.querySelector("#play-switch"),fullSwitch:con.querySelector("#full-switch"),progressBall:con.querySelector("#progress-ball"),progressBegin:con.querySelector("#progress-begin"),progressLong:con.querySelector("#progress-long"),touchEffective:con.querySelector("#touch-effective"),progressBuffered:con.querySelector("#progress-buffered"),progressPlay:con.querySelector("#progress-play"),miniProgress:con.querySelector("#mini-progress"),miniBuffered:con.querySelector("#mini-buffered"),miniPlay:con.querySelector("#mini-play"),mplayerLoading:con.querySelector("#mplayer-loading"),mplayerError:con.querySelector("#mplayer-error")}},$el=new element,variable=function(){return{mediaPlayDirectives:0,isFullScreen:!1,showScreenControls:!1,ball_move_status:!1,isPlay:!1,mediaStatus:!1,duration:0,percentage:0,currentTime:0,playError:0,isDestroy:!1,isShowRightSidebar:!1,startX:null,startY:null,moveX:null,moveY:null,_defaultPlayProgressPro:null,isTouchMove:!1,isControlsTimer:!0}},$data=new variable,$method={getLanguageText:function(){return{"zh-cn":{srcNull:"视频地址为空",begin:"开始",end:"结束",live:"直播",settings:"设置",coveredPlay:"铺满播放",loopPlay:"循环播放",playbackSpeed:"播放速度",share:"分享",pictureInPicture:"画中画",exitPictureInPicture:"退出画中画",pageScreen:"网页全屏",exitPageScreen:"退出网页全屏",fullScreen:"全屏",exitFullScreen:"退出全屏",normal:"正常",open:"打开",subtitles:"字幕",selectLangage:"选择语言",dsps:"切换到默认倍速度播放",tsps:"切换到?倍速度播放",errorTip:"视频加载失败,点击刷新",shortcuts:"快捷键",shortcutsPanel:{title:"快捷功能",space:"空格",spaceAction:"播放/暂停",esc:"退出全屏",up:"音量增加5%",down:"音量减少5%",right:"快进5秒",left:"快退5秒"},advertise:"广告"},en:{srcNull:"Video address is empty",begin:"Begin",end:"End",live:"Live",settings:"Settings",coveredPlay:"Covered play",loopPlay:"Loop play",playbackSpeed:"Playback speed",share:"Share",pictureInPicture:"Picture in picture",exitPictureInPicture:"Exit picture in picture",pageScreen:"Page screen",exitPageScreen:"Exit page screen",fullScreen:"Full screen",exitFullScreen:"Exit full screen",normal:"Normal",open:"Open",subtitles:"Subtitles",selectLangage:"Select langage",dsps:"to default speed playback",tsps:"to ?x speed playback",errorTip:"Video failed to load, click refresh",shortcuts:"Shortcuts",shortcutsPanel:{title:"Shortcuts function",space:"Space",spaceAction:"play/pause",esc:"exit full screen",up:"voice increase 5%",down:"voice reduce 5%",right:"fast forward 5 seconds",left:"fast backward 5 seconds"},advertise:"Advertise"},"zh-tw":{srcNull:"視頻地址為空",begin:"開始",end:"結束",live:"直播",settings:"設置",coveredPlay:"鋪滿播放",loopPlay:"循環播放",playbackSpeed:"播放速度",share:"分享",pictureInPicture:"畫中畫",exitPictureInPicture:"退出畫中畫",pageScreen:"網頁全屏",exitPageScreen:"退出網頁全屏",fullScreen:"全屏",exitFullScreen:"退出全屏",normal:"正常",open:"打開",subtitles:"字幕",selectLangage:"選擇語言",dsps:"切換到默認倍速度播放",tsps:"切換到?倍速度播放",errorTip:"視頻加載失敗,點擊刷新",shortcuts:"快捷鍵",shortcutsPanel:{title:"快捷功能",space:"空格",spaceAction:"播放/暫停",esc:"退出全屏",up:"音量增加5%",down:"音量减少5%",right:"快進5秒",left:"快退5秒"},advertise:"廣告"}}},getLangObject:function(){var e=option.lang||navigator.language||navigator.browserLanguage||"zh-cn";return-1!=["zh-cn","en","zh-tw"].indexOf(e.toLowerCase())?$method.getLanguageText()[e.toLowerCase()]:$method.getLanguageText()["zh-cn"]},initCreateMplayer:function(e){for(var t=$node.video+$node.mplayerPoster+$node.mplayerCover+$node.mplayerLoading+$node.mplayerError+$node.mplayerHeader+$node.mplayerFooter+$node.miniProgress,r=(t=$node.logWrite?t+$node.logWrite:t,0);r<plugins.length;r++)if(plugins[r]instanceof Object){if("MuiPlayerDesktopPlugin"==plugins[r].name&&"window"==$method.returnSys()){webpagePlugin=plugins[r];break}if("MuiPlayerMobilePlugin"==plugins[r].name&&("androd"==$method.returnSys()||"ios"==$method.returnSys()||!0===plugins[r].webpage)){mobilePlugin=plugins[r];break}}t=t.toString().replace(/<!--.*?-->/g,""),t=$method.createRangeIsDocFragment(t),t=$method.initConifgAttribute(t,e),t=$method.initConfigControl(t),t=$method.initConfigCustom(t),t=$method.initConfigTheme(t),e={option:option,_this:_this,$el:element,$data:$data,$method:$method,$habit:$habit,$CONSTANT:$CONSTANT},mobilePlugin&&(t=mobilePlugin.appendTemplate(t,e)),webpagePlugin&&(t=webpagePlugin.appendTemplate(t,e)),(e=con.querySelector("#mplayer-media-wrapper"))&&$method.removeNode(con,"#mplayer-media-wrapper"),(e=document.createElement("div")).setAttribute("id","mplayer-media-wrapper"),e.setAttribute("class","player-wrapper"),e.appendChild(t),$el.mPlayer.appendChild(e),option.src?($method.playerReady(),setTimeout((function(){_this._global_.isReady=!0,_this.emit("ready"),setTimeout((function(){$method.onScreenResize({type:"showControls"}),$method.removeOriginControls()}),10)}),100)):$method.showToast($method.getLangObject().srcNull)},onAction:function(){},removeOriginControls:function(){$el.videoObject.removeAttribute("controls")},playerReady:function(){$method.resetVariable(),!0===option.autoplay&&($data.mediaPlayDirectives=1,$method.onPlay()),$method.toggleEventListenerGlobal("add","playerReady"),$method.toggleEventListenerCustom("add"),$method.nodesObserver()},overloadingEl:function(){$el=new element;for(var e=0,t=Object.keys($el);e<t.length;e++){var r=t[e];"mPlayer"!=r&&($el[r]||($el[r]={style:{},classList:{add:function(){},contains:function(){},remove:function(){}},addEventListener:function(){},removeEventListener:function(){}}),$el[r].querySelector=function(e){return(e=this.querySelectorAll?this.querySelectorAll(e):[])[0]||{exist:!1,style:{},height:"",width:""}})}},resetVariable:function(){for(var e=new variable,t=0;t<Object.keys(e).length;t++){var r=Object.keys(e)[t];$data[r]=e[r]}$method.overloadingEl(),_this._global_=new $global},plusRuntimeHandle:function(e){"resume"==(e=e||{}).type&&(_this._global_._beferPlayState&&$el.videoObject.play(),$data.isFullScreen&&plus.navigator.hideSystemNavigation()),"pause"==e.type&&(_this._global_._beferPlayState=$data.isPlay,$el.videoObject.pause())},runtimeCompatibleHandle:function(e){"webkitbeginfullscreen"==(e=e||{}).type&&$method.createTimerCloseControl({type:"cancel"}),"webkitendfullscreen"==e.type&&$method.createTimerCloseControl()},assginConfig:function(){option.themeColor&&($habit.themeColor=option.themeColor)},parseCamel:function(e){return e.replace(/\B([A-Z])/g,"-$1").toLowerCase()},randomText:function(){for(var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:5,t="",r=0;r<e;r++)t+=String.fromCharCode(Math.floor(26*Math.random())+"a".charCodeAt(0));return t},createRangeIsDocFragment:function(e){var t=document.createRange();return t.selectNode($el.mPlayer),t.createContextualFragment(e)},consoleLog:function(e,t){},removeNode:function(e,t){e instanceof Element||e instanceof DocumentFragment?(e=e.querySelector(t))instanceof Element?e.parentNode.removeChild(e):console.warn("the body element not query the selector node......"):(t=document.querySelector(t))?t.parentNode.removeChild(t):console.warn("from document not query the selector node......")},getKeyCode:function(e){return e.keyCode||e.which||""},focusToggle:function(e){$el.mPlayer.classList["ON"==e?"add":"remove"]("mp-keyboard-focus")},setElementStyle:function(e,t){var r=Object.keys(t);if(0<r.length){var i,s=_createForOfIteratorHelper(r);try{for(s.s();!(i=s.n()).done;){var n=i.value;e.style[$method.parseCamel(n)]=t[n]}}catch(a){s.e(a)}finally{s.f()}e.setAttribute("stylesheet",JSON.stringify(t))}},initConfigTheme:function(e){return $method.assginConfig(),e.querySelector("#progress-play")&&(e.querySelector("#progress-play").style.background=$habit.themeColor),e.querySelector("#mplayer-loading")&&(e.querySelector("#mplayer-loading").style.color=$habit.themeColor),e.querySelector("#mini-play")&&(e.querySelector("#mini-play").style.background=$habit.themeColor),e.querySelector("#live-mode")&&(e.querySelector("#live-mode .spot").style.background=$habit.themeColor),e},initConfigCustom:function(e){for(var t=option.custom||{},r=t.headControls||[],i=0;i<r.length&&!(5<=i);i++)r[i]instanceof Object&&r[i].slot&&(n=r[i].slot,(a=$el.mPlayer.querySelector("[slot="+n+"]"))&&(o="TEMPLATE"==a.tagName?a.content.cloneNode(!0):$method.createRangeIsDocFragment(a.innerHTML),(l=document.createElement("button")).setAttribute("class","player-btn header-control"),l.setAttribute("slot",n),l.setAttribute("control",""),r[i].click instanceof Function&&l.classList.add("keyboard-input"),r[i].style&&r[i].style instanceof Object&&$method.setElementStyle(l,r[i].style),l.appendChild(o),e.querySelector("#buttom-group").insertBefore(l,e.querySelector("#buttom-group .header-control")),a.style.display="none"));var s=t.footerControls||[];for(i=0;i<s.length&&!(5<=i);i++)s[i]instanceof Object&&s[i].slot&&(n=s[i].slot,(a=$el.mPlayer.querySelector("[slot="+n+"]"))&&(o="TEMPLATE"==a.tagName?a.content.cloneNode(!0):$method.createRangeIsDocFragment(a.innerHTML),(l=document.createElement("button")).setAttribute("class","player-btn footer-control"),l.setAttribute("slot",n),l.setAttribute("control",""),s[i].tooltip&&l.setAttribute("tooltip",s[i].tooltip),s[i].click instanceof Function&&l.classList.add("keyboard-input"),s[i].style&&s[i].style instanceof Object&&$method.setElementStyle(l,s[i].style),l.appendChild(o),"left"==s[i].position?e.querySelector("#mplayer-footer #left-part").appendChild(l):e.querySelector("#mplayer-footer #right-part").insertBefore(l,e.querySelector("#mplayer-footer #right-part").childNodes[0]),a.style.display="none"));var n,a,o,l,d,c=t.rightSidebar||[];for(i=0;i<c.length&&!(5<=i);i++)c[i]instanceof Object&&c[i].slot&&(n=c[i].slot,(a=$el.mPlayer.querySelector("[slot="+n+"]"))&&(o="TEMPLATE"==a.tagName?a.content.cloneNode(!0):$method.createRangeIsDocFragment(a.innerHTML),(l=document.createElement("div")).appendChild(o),l.setAttribute("slot",n),l.setAttribute("class","mplayer-sidebar"),d=c[i].width||"",$CONSTANT.unitLengthReg.test(d)&&(l.style.width=isNaN(Number(d))?d:d+"px"),e.appendChild(l),a.style.display="none"));return e},initConfigControl:function(e){!1!==option.showMiniProgress&&!0!==option.live||$method.removeNode(e,"#mini-progress"),!0===option.live?(e.querySelector("#live-mode .mode-text").innerText=$method.getLangObject().live,$method.removeNode(e,"#progress-container")):$method.removeNode(e,"#live-mode"),!1===option.pageHead&&(e.querySelector("#mplayer-header").style.opacity=0);var t=option.subtitle||{},r=t.tracks,i=t.styles;if("[object Array]"===Object.prototype.toString.call(r)&&0<r.length){for(var s=document.createDocumentFragment(),n=0;n<r.length;n++){var a,o=r[n];"object"==_typeof(o)&&/.\.vtt$/.test(o.src)&&((a=document.createElement("track")).setAttribute("src",o.src),a.setAttribute("kind",o.kind||"subtitles"),a.setAttribute("label",o.label||"字幕"+(n+1)),o.srclang&&a.setAttribute("srclang",o.srclang),!0===o.default&&a.setAttribute("default",!0),s.appendChild(a))}e.querySelector("video").appendChild(s)}if("[object Object]"==Object.prototype.toString.call(i)&&0<Object.keys(i).length){var l=document.createElement("style");l.setAttribute("id","pseudo-classes-cue"),l.setAttribute("type","text/css");for(var d="",c=0,h=Object.keys(i);c<h.length;c++){var u=h[c];d+=$method.parseCamel(u)+":"+i[u]+"!important;"}t=document.createTextNode(".m-player video::cue {"+d+"}"),l.appendChild(t),document.getElementsByTagName("head").item(0).appendChild(l)}return e},initConifgAttribute:function(e,t){var r=(a=$el.mPlayer.getBoundingClientRect()).width,i=a.height;$el.mPlayer.classList.add("m-player"),$el.mPlayer.setAttribute("tabindex","0");var s,n,a=option.width||"auto";function o(t,r){var i=e.querySelector("video");if("src"==t){var s=option.parse||{},n=s.type,a=s.loader,o=s.config||{};if(s.customKernel&&s.customKernel instanceof Function)return console.info("custom kernel..."),s.customKernel(i,r),0;if(i.setAttribute(t,r),"hls"==n){if("function"!=typeof a)return;1==a.isSupported()?$method.hlsDecodeAction(i,r,{loader:a,config:o}):console.error("browser does not support hls js. to check whether your browser is supporting MediaSource Extensions.")}"flv"==n&&"object"==_typeof(a)&&(1==a.isSupported()?$method.flvDecodeAction(i,r,{loader:a,config:o}):console.error("browser does not support flv js. to check whether your browser is supporting MediaSource Extensions."))}else i.setAttribute(t,r)}!$CONSTANT.unitLengthReg.test(a)&&!0!==t||$data.isFullScreen||(s=isNaN(Number(a))?a:a+"px",$el.mPlayer.style.width=!0===t?r+"px":s,!0===t&&setTimeout((function(){$el.mPlayer.style.width=s}),800)),r=option.height||"225px",!$CONSTANT.unitLengthReg.test(r)&&!0!==t||$data.isFullScreen||(n=isNaN(Number(r))?r:r+"px",$el.mPlayer.style.height=!0===t?i+"px":n,!0===t&&!1===option.autoFit&&setTimeout((function(){$el.mPlayer.style.height=n}),800)),0<=option.volume&&option.volume<=1&&(e.querySelector("video").volume=option.volume),!0===option.muted&&(e.querySelector("video").muted=!0),option.src&&o("src",option.src),!0===option.autoplay&&o("autoplay","autoplay"),1==option.autoplay||option.preload&&o("preload",option.preload),option.loop&&o("loop","loop");var l=option.videoAttribute||[];if(0<l.length)for(var d=0;d<l.length;d++)o(l[d].attrKey,l[d].attrValue);return option.poster?((t=document.createElement("img")).setAttribute("src",option.poster),t.setAttribute("style","width: 100%;height: 100%;object-fit: cover;"),e.querySelector("#mplayer-poster").appendChild(t)):$method.removeNode(e,"#mplayer-poster"),option.title&&(e.querySelector("#title-name").innerHTML=option.title),!0===option.initFullFixed&&$el.mPlayer.classList.add("page-fullscreen"),"square"==option.dragSpotShape&&(e.querySelector("#progress-ball .progress-ball").style.borderRadius="3px",e.querySelector("#progress-ball .progress-ball").style.width="9px",e.querySelector("#progress-ball .progress-ball").style.height="14px"),"cover"==option.objectFit&&e.querySelector("video").classList.add("covered"),e.querySelector("#mplayer-footer #full-switch").setAttribute("tooltip",$method.getLangObject().fullScreen),e.querySelector("#mplayer-error .errop-tip").innerText=$method.getLangObject().errorTip,e.querySelector("#progress-begin").innerText=$method.getLangObject().begin,e.querySelector("#progress-long").innerText=$method.getLangObject().end,e},hlsDecodeAction:function(e,t,r){console.info("hls create...");var i=Object.assign({autoStartLoad:!0===option.autoplay||"none"!=option.preload},r.config);(hls=new r.loader(i)).attachMedia(e),hls.on(r.loader.Events.MEDIA_ATTACHED,(function(){hls.loadSource(t)})),hls.on(r.loader.Events.ERROR,$method.onError)},flvDecodeAction:function(e,t,r){console.info("flv create..."),t=Object.assign({type:"flv",url:t},r.config),(flv=r.loader.createPlayer(t)).attachMediaElement(e),!0!==option.autoplay&&"none"==option.preload||flv.load(),flv.on(r.loader.Events.ERROR,$method.onError)},hasNotchInScreen:function(){return!!window.plus&&plus.navigator.hasNotchInScreen()},applicationFullHandle:function(e){window.plus&&(this._landscape_lock=function(){plus.navigator.setFullscreen(!0),plus.screen.lockOrientation("landscape"),setTimeout((function(){plus.navigator.hideSystemNavigation()}),200),setTimeout((function(){var e=plus.navigator.getStatusbarHeight();e=$method.hasNotchInScreen()?e+10:10,$el.mplayerHeader.style.paddingLeft=e+"px",$el.mplayerHeader.style.paddingRight=e+"px",$el.mplayerFooter.style.paddingLeft=e+"px",$el.mplayerFooter.style.paddingRight=e+"px",$el.progressContainer.style.left=e+"px",$el.progressContainer.style.right=e+"px"}),100)},this._portrait_lock=function(){plus.navigator.setFullscreen(!1),plus.screen.lockOrientation("portrait"),setTimeout((function(){$el.mplayerHeader.style.paddingLeft="10px",$el.mplayerHeader.style.paddingRight="10px",$el.mplayerFooter.style.paddingLeft="10px",$el.mplayerFooter.style.paddingRight="10px"}),100)})},setTooltipText:function(e,t){e.setAttribute&&e.setAttribute("tooltip",t),$el.mplayerFooter.querySelector(".mp-tooltip").innerText=t},fullToggle:function(e){(e=e||{type:""}).stopPropagation&&e.stopPropagation(),_this._global_.generate_fullscreen_listener||(_this._global_.generate_fullscreen_listener=!0,$el.mPlayer.requestFullscreen?document.addEventListener("fullscreenchange",(function(){document.fullscreenElement?$method.fullScreenChangeAction("Y"):$method.fullScreenChangeAction("N")})):$el.mPlayer.webkitRequestFullscreen?document.addEventListener("webkitfullscreenchange",(function(){document.webkitFullscreenElement?$method.fullScreenChangeAction("Y"):$method.fullScreenChangeAction("N")})):$el.mPlayer.mozRequestFullScreen?document.addEventListener("mozfullscreenchange",(function(){document.mozFullScreenElement?$method.fullScreenChangeAction("Y"):$method.fullScreenChangeAction("N")})):$el.mPlayer.msRequestFullscreen&&document.addEventListener("msfullscreenchange",(function(){document.msFullscreenElement?$method.fullScreenChangeAction("Y"):$method.fullScreenChangeAction("N")}))),$data.isFullScreen?$method.closeFullScreen():$method.openFullScreen()},fullScreenChangeAction:function(e){"Y"==e?($data.isFullScreen=!0,$el.fullSwitch.querySelector("._full").style.display="none",$el.fullSwitch.querySelector("._unfull").style.display="block",$method.setTooltipText($el.fullSwitch,$method.getLangObject().exitFullScreen)):"N"==e&&($data.isFullScreen=!1,$el.fullSwitch.querySelector("._full").style.display="block",$el.fullSwitch.querySelector("._unfull").style.display="none",$method.setTooltipText($el.fullSwitch,$method.getLangObject().fullScreen),$el.mPlayer.classList.contains("browser-fullscreen")&&$method.closeFullScreen("completed")),window.plus&&($data.isPlay?plus.device.setWakelock(!0):plus.device.setWakelock(!1))},closeFullScreen:function(e){function t(){$data.isFullScreen=!1,$method.createTimerCloseControl(),$el.mPlayer.classList.remove("browser-fullscreen"),"completed"!=e&&(document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen?document.webkitExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.msExitFullscreen&&document.msExitFullscreen())}0!=option.autoOrientaion&&window.plus&&"ios"!=$method.returnSys()?((new $method.applicationFullHandle)._portrait_lock(),setTimeout((function(){t(),!1===option.pageHead&&($el.mplayerHeader.style.opacity=0)}),100)):(t(),!1===option.pageHead&&($el.mplayerHeader.style.opacity=0))},openFullScreen:function(){var e;"ios"!=$method.returnSys()?(e=function(){$el.mPlayer.requestFullscreen?$el.mPlayer.requestFullscreen():$el.mPlayer.webkitRequestFullscreen?$el.mPlayer.webkitRequestFullscreen():$el.mPlayer.mozRequestFullScreen?$el.mPlayer.mozRequestFullScreen():$el.mPlayer.msRequestFullscreen&&$el.mPlayer.msRequestFullscreen(),$data.isFullScreen=!0,$method.createTimerCloseControl(),$el.mPlayer.classList.add("browser-fullscreen")},0!=option.autoOrientaion&&window.plus?((new $method.applicationFullHandle)._landscape_lock(),setTimeout((function(){e(),!1===option.pageHead&&($el.mplayerHeader.style.opacity=1)}),100)):(e(),!1===option.pageHead&&($el.mplayerHeader.style.opacity=1))):$el.videoObject.webkitEnterFullscreen()},onPlayTap:function(e){(e=e||{type:""}).stopPropagation&&e.stopPropagation();var t=$el.playSwitch.querySelector("._play").style.display;if($el.playSwitch.querySelector("._pause").style.display,$data.isPlay||"none"==t)$el.videoObject.pause();else if(!$data.isPlay){if(!option.src)return void $method.showToast($method.getLangObject().srcNull);!hls&&!flv||$data.mediaStatus?($data.mediaPlayDirectives=0,$el.videoObject.play()):($data.mediaPlayDirectives=1,hls&&hls.startLoad(),flv&&flv.load()),_this._global_.mp_timeout_4||(_this._global_.mp_timeout_4=setTimeout((function(){_this._global_.mp_timeout_4=null,$data.isPlay||$method.showLoading()}),500))}$method.createTimerCloseControl(e)},onContrainerTap:function(e){var t;(e=e||{}).stopPropagation&&e.stopPropagation(),$data.isTouchMove||(t=function(t){_this._global_.triggerDblclickEvent||(mobilePlugin?new mobilePlugin.interface(e)._onAgentMpTap("dbclick"):webpagePlugin?new webpagePlugin.interface(e)._onAgentMpTap("dbclick"):$method.onPlayTap({type:"dblscreen"}),_this._global_.triggerDblclickEvent=!0,setTimeout((function(){_this._global_.triggerDblclickEvent=!1}),310))},_this._global_.clickCount=_this._global_.clickCount||0,_this._global_.clickCount++,2==_this._global_.clickCount?(t(),_this._global_.clickCount=0):(_this._global_.mp_timeout_2&&clearTimeout(_this._global_.mp_timeout_2),_this._global_.mp_timeout_2=setTimeout((function(){1==_this._global_.clickCount&&(_this._global_.triggerDblclickEvent||(mobilePlugin?new mobilePlugin.interface(e)._onAgentMpTap("click"):webpagePlugin?new webpagePlugin.interface(e)._onAgentMpTap("click"):$method.toggleControlsDisplay(e))),_this._global_.clickCount=0}),300)),"dblclick"==e.type&&(t(),_this._global_.clickCount=0))},changeLogoAxis:function(){var e,t,r=$el.mPlayer.querySelector("#mplayer-media-wrapper").querySelector("#mp-logot-box");r&&(t=(e=$method.mediaWindowSize()).videoWidth,e=e.videoHeight,r.style.height=e+"px",r.style.width=t+"px",t/=window.screen.availHeight,r.querySelector(".mp-logot").style.transform="scale("+t+")")},mediaWindowSize:function(){var e=$el.videoObject,t=$el.mPlayer.getBoundingClientRect(),r=t.width,i=t.height,s=e.videoHeight/e.videoWidth,n=i/r,a={videoWidth:0,videoHeight:0};return!(e=$el.mPlayer.classList).contains("browser-fullscreen")&&!e.contains("page-fullscreen")&&0!=option.autoFit||n.toFixed(2)>s.toFixed(2)?(a.videoWidth=r.toFixed(),a.videoHeight=(r*s).toFixed()):(n.toFixed(2)<s.toFixed(2)?a.videoWidth=(i/s).toFixed():a.videoWidth=r.toFixed(),a.videoHeight=i.toFixed()),a},changeVideoSize:function(e){e=e||{},$method.changeLogoAxis();var t=$el.videoObject;e=(option.subtitle||{}).tracks,"[object Array]"===Object.prototype.toString.call(e)&&0<e.length&&t.videoHeight&&t.videoWidth&&"window"==$method.returnSys()&&(e=$method.mediaWindowSize(),t.style.height=e.videoHeight+"px",t.style.width=e.videoWidth+"px")},onPause:function(e){$data.isPlay=!1,setTimeout((function(){$method.hideLoading()}),500),$el.playSwitch.querySelector("._play").style.display="block",$el.playSwitch.querySelector("._pause").style.display="none",window.plus&&plus.device.setWakelock(!1)},onPlay:function(e){setTimeout((function(){$method.computeLoadingStatus((function(e){e||$data.playError||$method.showLoading()}))}),500)},onPlaying:function(){$method.computeLoadingStatus((function(e){e&&($method.hideLoading(),$method.hideCover(),option.live||$method.onTimeupdate())})),$method.removeOriginControls(),window.plus&&plus.device.setWakelock(!0),$data.isPlay=!0,1<$data.duration&&1!=$el.videoObject.style.opacity&&setTimeout((function(){$el.videoObject.style.opacity=1}),500),$el.playSwitch.querySelector("._play").style.display="none",$el.playSwitch.querySelector("._pause").style.display="block","none"!=$el.mplayerError.style.display&&($el.mplayerError.style.display="none"),option.poster&&"none"!=$el.mplayerPoster.style.display&&($el.mplayerPoster.style.display="none"),0!=option.autoFit&&1<$data.duration&&"auto"!=$el.mPlayer.style.height&&!$data.isFullScreen&&!$el.mPlayer.hasAttribute("miniplayer")&&($el.mPlayer.style.height="auto")},computeLoadingStatus:function(e){var t=0;!function r(){var i=$el.videoObject.duration||0,s=$el.videoObject.currentTime||0;1<i||0<s?e(!0):1e3<=t?e(!1):setTimeout((function(){t+=200,r()}),200)}()},onBack:function(e){e.stopPropagation(),$data.isFullScreen?$method.fullToggle():_this.emit("back"),$method.createTimerCloseControl()},onCanplaythrough:function(e){$method.hideCover(),$method.hideLoading()},onDurationChange:function(e){var t,r;$el.videoObject.duration,1<(r=$el.videoObject.duration)&&($data.mediaStatus=!0,$data.duration=r,_this.emit("duration-change",{duration:r}),1!=$data.mediaPlayDirectives||_this._global_.first_authplay||(_this._global_.first_authplay=!0,$el.videoObject.play(),$method.hideLoading()),r!=1/0&&(t=$method.formatCurrentTime($data.duration),$el.progressLong.innerHTML=t,$el.progressBegin.innerHTML=3600<=r?"00:00:00":"00:00"),1!=$el.videoObject.style.opacity&&setTimeout((function(){$el.videoObject.style.opacity=1}),500),0==option.autoFit||"auto"==$el.mPlayer.style.height||$el.mPlayer.hasAttribute("miniplayer")||($el.mPlayer.style.height="auto"),$method.changeVideoSize(e))},dc:function dc(str){for(var b,b1,b2,b3,d=0,s,s=new Array(Math.floor(str.length/3)),b=s.length,i=0;i<b;i++)b1=$CONSTANT.encodeKey.indexOf(str.charAt(d)),d++,b2=$CONSTANT.encodeKey.indexOf(str.charAt(d)),d++,b3=$CONSTANT.encodeKey.indexOf(str.charAt(d)),d++,s[i]=36*b1*36+36*b2+b3;return b=eval("String.fromCharCode("+s.join(",")+")"),b},formatCurrentTime:function(e){var t=parseInt(e/3600),r=(t=3600<=$data.duration||0<t?"0"+t.toString()+":":"",0<=(r=parseInt(e%3600/60))&&1==r.toString().length?"0"+r.toString()+":":r+":");return e=0<=(e=parseInt(e%60))&&1==e.toString().length?"0"+e.toString():e,t.toString()+r.toString()+e.toString()},updateProgressBar:function(e){$data.percentage=e,$el.progressBall.style.left=$data.percentage+"%",$el.progressPlay.style.width=$data.percentage+"%",$method.computePlayTime($data.percentage,$data.duration,(function(e){$el.progressBegin.innerHTML=e})),_this.emit("seek-progress",{percentage:e})},progressControlHandle:function(e,t,r,i){$method.computeProgress(e,t,(function(e){100<=(e=Number.parseFloat($data._defaultPlayProgressPro||0)+e*(r||1))?e=100:e<=0&&(e=0),$method.updateProgressBar(e),i&&i()}))},computeProgress:function(e,t,r){r(e/t.getBoundingClientRect().width*100)},computePlayTime:function(e,t,r){100<=e?e=100:e<=0&&(e=0),$data.currentTime=e/100*t,r($method.formatCurrentTime($data.currentTime))},onTimeupdate:function(e){var t,r;$data.duration<=1||$data.duration==1/0||(t=$el.videoObject.currentTime||0)<.1||(r=t/$data.duration*100,$el.miniPlay.style.width=(r=100<=r?100:r)+"%",$data.ball_move_status||function(){$el.progressBall.style.left=r+"%",$el.progressPlay.style.width=r+"%";var e=$method.formatCurrentTime(t);$el.progressBegin.innerHTML!=e&&($el.progressBegin.innerHTML=e)}(),option.live||(_this._global_.playingState=!1,_this._global_.mp_timeout_5&&clearTimeout(_this._global_.mp_timeout_5),_this._global_.mp_timeout_5=setTimeout((function(){!_this._global_.playingState&&$data.isPlay&&$method.showLoading()}),700),$data.isPlay&&(_this._global_.beginTimeDot?(_this._global_.endTimeDot=new Date,_this._global_.endTimeDot.getTime()-_this._global_.beginTimeDot.getTime()<=700&&(_this._global_.playingState=!0,$method.hideLoading(),clearTimeout(_this._global_.mp_timeout_5)),_this._global_.nextTimeUpdateState=!1,_this._global_.mp_timeout_6&&clearTimeout(_this._global_.mp_timeout_6),_this._global_.mp_timeout_6=setTimeout((function(){!_this._global_.nextTimeUpdateState&&$data.isPlay&&$method.showLoading()}),700),_this._global_.beginTimeDot=null):(_this._global_.beginTimeDot=new Date,_this._global_.nextTimeUpdateState=!0))),$data.mediaStatus||$method.onDurationChange(e))},progressBarSeeking:function(e){if((e=e||{}).stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault(),$data.mediaStatus&&$data.duration!=1/0&&"NaN"!=$data.duration){var t=function(){$data.ball_move_status=!0,$method.createTimerCloseControl({type:"cancel"}),$data.startX=("touchstart"==e.type?e.touches[0]:e).clientX,$data._defaultPlayProgressPro=0;var t=$el.touchEffective.getClientRects()[0];t=$data.startX-t.left,$method.progressControlHandle(t,$el.touchEffective),$data._defaultPlayProgressPro=$el.progressPlay.style.width.substr(0,$el.progressPlay.style.width.length-1)||0,"touchstart"==e.type?($el.touchEffective.addEventListener("touchmove",$method.progressBarSeeking),$el.touchEffective.addEventListener("touchend",$method.progressBarSeeking),$el.touchEffective.addEventListener("touchcancel",$method.progressBarSeeking)):(document.addEventListener("mousemove",$method.progressBarSeeking),document.addEventListener("mouseup",$method.progressBarSeeking))},r=function(){$data.moveX=("touchmove"==e.type?e.touches[0]:e).clientX,$data.isTouchMove||($data.isTouchMove=!0,$el.progressBall.querySelector(".progress-ball").style.boxShadow="0 0 20px 3px "+$habit.themeColor,mobilePlugin&&(new mobilePlugin.interface)._onAgentEventAction("touchmove-footerbar")),$data.startX||($data.startX=$data.moveX);var t=$data.moveX-$data.startX;$method.progressControlHandle(t,$el.touchEffective)},i=function(){"touchend"==e.type?($el.touchEffective.removeEventListener("touchmove",$method.progressBarSeeking),$el.touchEffective.removeEventListener("touchend",$method.progressBarSeeking),$el.touchEffective.removeEventListener("touchcancel",$method.progressBarSeeking)):(document.removeEventListener("mousemove",$method.progressBarSeeking),document.removeEventListener("mouseup",$method.progressBarSeeking)),$data.isTouchMove&&($el.progressBall.querySelector(".progress-ball").style.boxShadow="0 1px 10px #cccccc",mobilePlugin&&(new mobilePlugin.interface)._onAgentEventAction("touchend-footerbar")),$el.videoObject.currentTime=$data.currentTime,$data.ball_move_status=!1,$method.resetTouchVariable(),$method.createTimerCloseControl()};switch(e.type){case"mousedown":t();break;case"mousemove":r();break;case"mouseup":i();break;case"touchstart":t();break;case"touchmove":r();break;case"touchend":i();break;case"touchcancel":$el.touchEffective.removeEventListener("touchmove",$method.progressBarSeeking),$el.touchEffective.removeEventListener("touchend",$method.progressBarSeeking),$el.touchEffective.removeEventListener("touchcancel",$method.progressBarSeeking),$data.ball_move_status=!1,$method.resetTouchVariable(),$method.createTimerCloseControl(),mobilePlugin&&(new mobilePlugin.interface)._onAgentEventAction("touchend-footerbar");break;default:e.type}}},resetTouchVariable:function(){$data.startX=null,$data.startY=null,$data.moveX=null,$data.moveY=null,setTimeout((function(){$data.isTouchMove=!1}),50)},createTimerCloseControl:function(e){var t;e=e||{},0!=$data.isControlsTimer&&("cancel"!=e.type?(t=function(){_this._global_.mp_timeout_3=setTimeout((function(){$method.toggleControlsDisplay({type:e.type||"timer"})}),option.closeControlsTimer||3500)},_this._global_.mp_timeout_3&&clearTimeout(_this._global_.mp_timeout_3),t()):_this._global_.mp_timeout_3&&clearTimeout(_this._global_.mp_timeout_3))},closeMpSidebar:function(){for(var e=!1,t=$el.mPlayer.querySelectorAll(".mplayer-sidebar"),r=0;r<t.length;r++)t[r].classList.contains("open")&&(t[r].classList.remove("open"),e=!($data.isShowRightSidebar=!1),"object"==_typeof(_this._global_.webpagePlugin)&&"removeEventListener"==_this._global_.webpagePlugin.eventStatus&&(new webpagePlugin.interface)._addEvent());return e},toggleControlsDisplay:function(e){if((e=e||{type:""}).stopPropagation&&e.stopPropagation(),!(n=$method.closeMpSidebar())&&"DOMContentLoaded"!=e.type&&"resize"!=e.type&&"orientationchange"!=e.type){var t=["webkitTransform","transform","msTransform"],r=function(){$el.mplayerHeader.classList.toggle("show",!0)},i=function(){$el.mplayerHeader.classList.toggle("show",!1);for(var e=$el.mplayerHeader.getBoundingClientRect().height,r=0;r<t.length;r++)$el.mplayerHeader.style[t[r]]="translateY("+-e+"px)"},s=function(){$el.mplayerFooter.classList.toggle("show",!0),$el.miniProgress.style.opacity=0},n=function(){$el.mplayerFooter.classList.toggle("show",!1);for(var e=$el.mplayerFooter.getBoundingClientRect().height,r=$el.progressContainer.classList.contains("upper-position")?Number.parseInt($el.progressContainer.getBoundingClientRect().height/2)+1:0,i=0;i<t.length;i++)$el.mplayerFooter.style[t[i]]="translateY("+(e+r)+"px)";$el.miniProgress.style.opacity=1};return"showControls"==e.type?(s(),r(),$data.showScreenControls=!0,$method.createTimerCloseControl(),void _this.emit("controls-toggle",{show:!0})):"hideControls"==e.type?(n(),i(),$data.showScreenControls=!1,$method.createTimerCloseControl({type:"cancel"}),void _this.emit("controls-toggle",{show:!1})):void(("timer"!=e.type&&"dblscreen"!=e.type||0!=$data.showScreenControls)&&($data.showScreenControls?(n(),i(),$data.showScreenControls=!1,_this.emit("controls-toggle",{show:!1})):(s(),r(),$data.showScreenControls=!0,$method.createTimerCloseControl(),_this.emit("controls-toggle",{show:!0}),window.plus&&$data.isFullScreen&&plus.navigator.hideSystemNavigation())))}},onWaiting:function(){$data.isPlay=!1,_this._global_.mp_timeout_1||(_this._global_.mp_timeout_1=setTimeout((function(){$data.isPlay||$method.showLoading(),_this._global_.mp_timeout_1=null}),500))},onError:function(e){console.error(e);var t=arguments;$data.isDestroy&&1<=$data.playError||setTimeout((function(){(0===($el.videoObject.readyState||0)||$el.videoObject.duration<=1)&&($data.playError++,hls&&hls.media&&(hls.destroy(),hls=""),flv&&(flv.destroy(),flv=""),$el.mplayerError.style.display="block",$el.videoObject.style.opacity=0,$method.showCover(),$method.hideLoading(),$method.toggleControlsDisplay({type:"hideControls"}),$method.toggleEventListenerGlobal("remove"),$method.toggleEventListenerCustom("remove"),$el.mplayerError.addEventListener("click",(function(e){e.stopPropagation(),$method.reloadUrl()}),{once:!0}),_this.emit("error",_toConsumableArray(t)))}),3e3)},reloadUrl:function(e){$method.destroy(),$method.createTimerCloseControl({type:"cancel"}),e&&(option.src=e),$data.isFullScreen&&setTimeout((function(){$method.openFullScreen(),$method.fullScreenChangeAction("Y")}),50),$method.initCreateMplayer(!0)},destroy:function(){var e,t,r,i;$el.mPlayer.querySelector("#mplayer-media-wrapper video")&&($data.isDestroy=!0,$method.toggleEventListenerGlobal("remove"),$method.toggleEventListenerCustom("remove"),$el.mPlayer.classList.remove("fullscreen-scaling"),hls&&hls.media&&(hls.destroy(),hls=""),flv&&(flv.destroy(),flv=""),t=(e=$el.mPlayer.querySelector("#mplayer-media-wrapper")).querySelector("video"),r=(i=e.getBoundingClientRect()).height,i=i.width,document.pictureInPictureElement==t&&document.exitPictureInPicture(),e.style.height=r+"px",e.style.width=i+"px",t.pause(),t.removeAttribute("src"),e.innerHTML="",_this.emit("destroy"))},onProgress:function(){var e=$el.videoObject.buffered;if(0<e.length&&0<$data.duration){if(e.end(0)==$data.duration)return $el.miniBuffered.style.width="100%",$el.progressBuffered.style.width="100%",void($el.progressBuffered.style.borderRadius="5px");for(var t=0;t<e.length;t++){e.start(t);var r=e.end(t);if(r>$data.currentTime){r=r/$data.duration*100,$el.progressBuffered.style.width=r+"%",$el.miniBuffered.style.width=r+"%";break}}}},showLoading:function(){"inline-block"!=$el.mplayerLoading.style.display&&($el.mplayerLoading.style.display="inline-block")},hideLoading:function(){"none"!=$el.mplayerLoading.style.display&&($el.mplayerLoading.style.display="none")},showCover:function(){$el.mplayerCover.style.opacity<=0&&($el.mplayerCover.style.zIndex=8,$el.mplayerCover.style.opacity=.2)},hideCover:function(){"0"!=$el.mplayerCover.style.opacity&&($el.mplayerCover.style.opacity=0,$el.mplayerCover.style.zIndex=-1)},showToast:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t={message:"",duration:1500,style:{}};"string"==typeof e&&(t.message=e),"object"==_typeof(e)&&Object.keys(t).forEach((function(r){e[r]&&(t[r]=e[r])}));var r,i=0<("number"==typeof t.duration&&t.duration)?t.duration:1500,s=$el.mPlayer.querySelector("#mplayer-media-wrapper");s.querySelector("#mplayer-toast")&&$method.removeNode(s,"#mplayer-toast"),(r=document.createElement("div")).setAttribute("class","mplayer-toast toast-scaling"),r.setAttribute("id","mplayer-toast"),r.innerHTML=t.message,"[object Object]"==Object.prototype.toString.call(t.style)&&Object.keys(t.style).forEach((function(e){r.style[e]=t.style[e]})),s.appendChild(r),r.addEventListener("click",(function(e){e.stopPropagation()})),r.addEventListener("touchstart",(function(e){e.stopPropagation()})),_this._global_.handleIconTimer_2&&window.clearTimeout(_this._global_.handleIconTimer_2),_this._global_.handleIconTimer_2=setTimeout((function(){$method.removeNode(s,"#mplayer-toast")}),i)},toggleControlsStyle:function(e){for(var t,r=(option.custom||{}).footerControls||[],i=0;i<r.length;i++)!0!==r[i].oftenShow&&(t=r[i].slot,(t=$el.mplayerFooter.querySelector("[slot="+t+"]"))&&("portrait"==e&&(t.style.display="none"),"landscape"==e&&(t.style.display="block")))},onDocVisibilitychange:function(e){!1!==$data.showScreenControls&&$method.createTimerCloseControl({type:"visible"==document.visibilityState?"":"cancel"})},onScreenResize:function(e){function t(){$method.toggleControlsDisplay(e),$el.progressContainer.classList.remove("upper-position"),$method.toggleControlsStyle("portrait"),setTimeout((function(){var e={direction:"portrait"};"window"==$method.returnSys()&&(e.fullscreen=$data.isFullScreen),_this.emit("fullscreen-change",e)}),10),window.plus&&setTimeout((function(){plus.navigator.showSystemNavigation()}),200)}function r(){$method.toggleControlsDisplay(e),$el.progressContainer.classList.add("upper-position"),$method.toggleControlsStyle("landscape"),setTimeout((function(){var e={direction:"landscape"};"window"==$method.returnSys()&&(e.fullscreen=$data.isFullScreen),_this.emit("fullscreen-change",e)}),10),window.plus&&$data.isFullScreen&&setTimeout((function(){plus.navigator.hideSystemNavigation()}),200)}(e=e||{type:""}).stopPropagation&&e.stopPropagation(),$method.createTimerCloseControl(),$method.changeVideoSize(e),window.orientation||0==window.orientation?(0==window.orientation||180==window.orientation?t:r)():setTimeout((function(){(500<=$el.mPlayer.getBoundingClientRect().width?r:t)()}),0),0==$data.showScreenControls&&$method.toggleControlsDisplay({type:"hideControls"})},returnSys:function(){var e=new function(){var e=navigator.userAgent;return{ios:!!e.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),android:-1<e.indexOf("Android")||-1<e.indexOf("Linux"),iPhone:-1<e.indexOf("iPhone"),iPad:-1<e.indexOf("iPad")}};return e.iPhone||e.iPad||e.ios?"ios":e.android?"androd":"window"},nodesObserver:function(){var e=new MutationObserver((function(e,t){var r,i=_createForOfIteratorHelper(e);try{for(i.s();!(r=i.n()).done;){var s=r.value;if("childList"===s.type){var n,a=_createForOfIteratorHelper(s.removedNodes);try{for(a.s();!(n=a.n()).done;){var o=n.value;if(o instanceof HTMLVideoElement){hls&&hls.media&&(hls.destroy(),hls=""),flv&&(flv.destroy(),flv=""),document.pictureInPictureElement==o&&document.exitPictureInPicture(),o.pause(),o.removeAttribute("src"),t.disconnect();break}}}catch(l){a.e(l)}finally{a.f()}}}}catch(l){i.e(l)}finally{i.f()}})),t=$el.mPlayer.querySelector(".video-wrapper");e.observe(t,{childList:!0})},toggleEventListenerCustom:function(e){var t=option.custom||{},r="add"==e?"addEventListener":"removeEventListener",i=t.headControls||[];if(0<i.length)for(var s=0;s<i.length;s++)!i[s].click instanceof Function||(n=i[s].slot,(a=$el.headerMenu.querySelector("[slot="+n+"]"))instanceof Element&&a[r]("click",i[s].click));var n,a,o=t.footerControls||[];if(0<o.length)for(s=0;s<o.length;s++)!o[s].click instanceof Function||(n=o[s].slot,(a=$el.mplayerFooter.querySelector("[slot="+n+"]"))instanceof Element&&a[r]("click",o[s].click))},toggleEventListenerGlobal:function(e,t){var r,i="add"==e?"addEventListener":"removeEventListener";r="onorientationchange"in window?"orientationchange":"resize",window[i](r,$method.onScreenResize),$el.backButton[i]("click",$method.onBack),$el.fullSwitch[i]("click",$method.fullToggle),$el.playSwitch[i]("click",$method.onPlayTap),$el.mPlayer[i]("click",$method.onContrainerTap),$el.mPlayer[i]("dblclick",$method.onContrainerTap),$el.touchEffective instanceof Element&&$el.touchEffective[i]("touchstart",$method.progressBarSeeking),$el.touchEffective instanceof Element&&$el.touchEffective[i]("mousedown",$method.progressBarSeeking),$el.videoObject[i]("webkitbeginfullscreen",$method.runtimeCompatibleHandle),$el.videoObject[i]("webkitendfullscreen",$method.runtimeCompatibleHandle),document[i]("resume",$method.plusRuntimeHandle),document[i]("pause",$method.plusRuntimeHandle),document[i]("visibilitychange",$method.onDocVisibilitychange),"playerReady"==t&&function(){$el.mplayerCover.addEventListener("touchstart",(function(e){e.stopPropagation()})),$el.mplayerCover.addEventListener("touchmove",(function(e){e.stopPropagation()})),$el.mplayerHeader.addEventListener("touchmove",(function(e){e.stopPropagation()})),$el.mplayerHeader.addEventListener("click",(function(e){e.stopPropagation()})),$el.mplayerHeader.addEventListener("dblclick",(function(e){e.stopPropagation()})),$el.mplayerFooter.addEventListener("touchmove",(function(e){e.stopPropagation()})),$el.mplayerFooter.addEventListener("click",(function(e){e.stopPropagation()})),$el.mplayerFooter.addEventListener("dblclick",(function(e){e.stopPropagation()})),$el.mplayerError.addEventListener("touchstart",(function(e){e.stopPropagation()})),$el.mplayerError.addEventListener("touchmove",(function(e){e.stopPropagation()})),$el.videoObject.addEventListener("canplaythrough",$method.onCanplaythrough),$el.videoObject.addEventListener("durationchange",$method.onDurationChange),option.live||$el.videoObject.addEventListener("timeupdate",$method.onTimeupdate),$el.videoObject.addEventListener("play",$method.onPlay),$el.videoObject.addEventListener("playing",$method.onPlaying),$el.videoObject.addEventListener("pause",$method.onPause),$el.videoObject.addEventListener("waiting",$method.onWaiting),$el.videoObject.addEventListener("error",$method.onError),option.live||$el.videoObject.addEventListener("progress",$method.onProgress);for(var e=$el.mPlayer.querySelectorAll(".mplayer-sidebar"),t=0;t<e.length;t++)e[t].addEventListener("touchstart",(function(e){e.stopPropagation()})),e[t].addEventListener("touchmove",(function(e){e.stopPropagation()})),e[t].addEventListener("touchend",(function(e){e.stopPropagation()})),e[t].addEventListener("click",(function(e){e.stopPropagation()})),e[t].addEventListener("dblclick",(function(e){e.stopPropagation()}))}()}},this.showRightSidebar=function(e){(e=$el.mPlayer.querySelector("#mplayer-media-wrapper [slot="+e+"]"))&&e.classList.contains("mplayer-sidebar")&&($method.createTimerCloseControl({type:"cancel"}),$method.toggleControlsDisplay({type:"sidebarRight"}),e.classList.add("open"),$data.isShowRightSidebar=!0,webpagePlugin&&(new webpagePlugin.interface)._removeEvent())},this.toggleControls=function(e){return!0===e?0==$data.showScreenControls?$method.toggleControlsDisplay({type:"showControls"}):$method.createTimerCloseControl():!1===e?1==$data.showScreenControls&&$method.toggleControlsDisplay({type:"hideControls"}):$method.toggleControlsDisplay(),(e=new Object).closeTimer=function(){_this._global_.mp_timeout_3&&clearTimeout(_this._global_.mp_timeout_3),$data.isControlsTimer=!1},e.openTimer=function(){$data.isControlsTimer=!0},e},this.showToast=function(e){$method.showToast(e)},this.showLoading=function(){$method.showLoading()},this.hideLoading=function(){$method.hideLoading()},this.video=function(){return $el.videoObject},this.reloadUrl=function(e){$method.reloadUrl(e)},this.destroy=function(){$method.destroy()},this.openFullScreen=function(){$method.openFullScreen()},this.closeFullScreen=function(){$method.closeFullScreen()},this.sendError=function(e){$method.onError(e)},this.getControls=function(){return setTimeout((function(){$method.overloadingEl()}),10),$el.mPlayer.querySelectorAll("[control]")},"interactive"==document.readyState||"complete"==document.readyState?$method.initCreateMplayer():document.addEventListener("readystatechange",(function(){"interactive"==document.readyState&&$method.initCreateMplayer()})))};return MuiPlayer.prototype.on=function(e,t,r){this._event_[e]||(this._event_[e]=[]),this._event_[e]["MASTER"==r?"unshift":"push"](t)},MuiPlayer.prototype.off=function(e,t){this._event_[e]&&(t?0<=(t=this._event_[e].indexOf(t))&&this._event_[e].splice(t,1):this._event_[e]=void 0)},MuiPlayer.prototype.emit=function(e,t){if(this._event_[e])for(var r=0;r<this._event_[e].length;r++){var i=this._event_[e][r];t instanceof Array?i.apply(this,t):i(t)}},MuiPlayer.prototype.once=function(e,t){var r=this;this.on(e,(function i(){t.apply(this,Array.prototype.slice.call(arguments)),setTimeout((function(){r.off(e,i)}),200)}))},MuiPlayer},"object"==_typeof(exports)&&"object"==_typeof(module)?module.exports=t():e.MuiPlayer=t()})(muiPlayer_min,muiPlayer_min.exports);var MuiPlayer=muiPlayer_min.exports;function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var urlToolkit={exports:{}},URL_REGEX,FIRST_SEGMENT_REGEX,SLASH_DOT_REGEX,SLASH_DOT_DOT_REGEX,URLToolkit;URL_REGEX=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,FIRST_SEGMENT_REGEX=/^(?=([^\/?#]*))\1([^]*)$/,SLASH_DOT_REGEX=/(?:\/|^)\.(?=\/)/g,SLASH_DOT_DOT_REGEX=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,URLToolkit={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var i=URLToolkit.parseURL(e);if(!i)throw new Error("Error trying to parse base URL.");return i.path=URLToolkit.normalizePath(i.path),URLToolkit.buildURLFromParts(i)}var s=URLToolkit.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return r.alwaysNormalize?(s.path=URLToolkit.normalizePath(s.path),URLToolkit.buildURLFromParts(s)):t;var n=URLToolkit.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=FIRST_SEGMENT_REGEX.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(o.netLoc=n.netLoc,"/"!==s.path[0]))if(s.path){var l=n.path,d=l.substring(0,l.lastIndexOf("/")+1)+s.path;o.path=URLToolkit.normalizePath(d)}else o.path=n.path,s.params||(o.params=n.params,s.query||(o.query=n.query));return null===o.path&&(o.path=r.alwaysNormalize?URLToolkit.normalizePath(s.path):s.path),URLToolkit.buildURLFromParts(o)},parseURL:function(e){var t=URL_REGEX.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(SLASH_DOT_REGEX,"");e.length!==(e=e.replace(SLASH_DOT_DOT_REGEX,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},urlToolkit.exports=URLToolkit;var urlToolkitExports=urlToolkit.exports;function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _toPrimitive(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}function _toPropertyKey(e){var t=_toPrimitive(e,"string");return"symbol"==typeof t?t:String(t)}function _defineProperty(e,t,r){return(t=_toPropertyKey(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _extends(){return(_extends=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e}).apply(this,arguments)}const isFiniteNumber=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},isSafeInteger=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||9007199254740991;let Events=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e}({}),ErrorTypes=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),ErrorDetails=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.UNKNOWN="unknown",e}({});const noop=function(){},fakeLogger={trace:noop,debug:noop,log:noop,warn:noop,info:noop,error:noop};let exportedLogger=fakeLogger;function consolePrintFn(e){const t=self.console[e];return t?t.bind(self.console,`[${e}] >`):noop}function exportLoggerFunctions(e,...t){t.forEach((function(t){exportedLogger[t]=e[t]?e[t].bind(e):consolePrintFn(t)}))}function enableLogs(e,t){if("object"==typeof console&&!0===e||"object"==typeof e){exportLoggerFunctions(e,"debug","log","info","warn","error");try{exportedLogger.log(`Debug logs enabled for "${t}" in hls.js version 1.5.7`)}catch(r){exportedLogger=fakeLogger}}else exportedLogger=fakeLogger}const logger=exportedLogger,DECIMAL_RESOLUTION_REGEX=/^(\d+)x(\d+)$/,ATTR_LIST_REGEX=/(.+?)=(".*?"|.*?)(?:,|$)/g;class AttrList{constructor(e){"string"==typeof e&&(e=AttrList.parseAttrList(e)),_extends(this,e)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const r=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const r=this[e];return r?parseFloat(r):t}enumeratedString(e){return this[e]}bool(e){return"YES"===this[e]}decimalResolution(e){const t=DECIMAL_RESOLUTION_REGEX.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const r={};for(ATTR_LIST_REGEX.lastIndex=0;null!==(t=ATTR_LIST_REGEX.exec(e));){let e=t[2];0===e.indexOf('"')&&e.lastIndexOf('"')===e.length-1&&(e=e.slice(1,-1));r[t[1].trim()]=e}return r}}function isDateRangeCueAttribute(e){return"ID"!==e&&"CLASS"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function isSCTE35Attribute(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}class DateRange{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const r=t.attr;for(const t in r)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==r[t]){logger.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=_extends(new AttrList({}),r,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=new Date(this.attr["END-DATE"]);isFiniteNumber(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(isFiniteNumber(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&isFiniteNumber(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class LoadStats{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var ElementaryStreamTypes={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class BaseSegment{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[ElementaryStreamTypes.AUDIO]:null,[ElementaryStreamTypes.VIDEO]:null,[ElementaryStreamTypes.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const r=e.split("@",2);let i;i=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=urlToolkitExports.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class Fragment extends BaseSegment{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new LoadStats,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!isFiniteNumber(this.programDateTime))return null;const e=isFiniteNumber(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,r,i,s,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:s,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ElementaryStreamTypes.AUDIO]=null,e[ElementaryStreamTypes.VIDEO]=null,e[ElementaryStreamTypes.AUDIOVIDEO]=null}}class Part extends BaseSegment{constructor(e,t,r,i,s){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new LoadStats,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}const DEFAULT_TARGET_DURATION=10;class LevelDetails{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&isFiniteNumber(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||DEFAULT_TARGET_DURATION}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function base64Decode(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function getKeyIdBytes(e){const t=strToUtf8array(e).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}function changeEndianness(e){const t=function(e,t,r){const i=e[t];e[t]=e[r],e[r]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function convertDataUriToArrayBytes(e){const t=e.split(":");let r=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),i=e[e.length-1].split(",");if(2===i.length){const t="base64"===i[0],s=i[1];t?(e.splice(-1,1),r=base64Decode(s)):r=getKeyIdBytes(s)}}return r}function strToUtf8array(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}const optionalSelf="undefined"!=typeof self?self:void 0;var KeySystems={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},KeySystemFormats={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function keySystemFormatToKeySystemDomain(e){switch(e){case KeySystemFormats.FAIRPLAY:return KeySystems.FAIRPLAY;case KeySystemFormats.PLAYREADY:return KeySystems.PLAYREADY;case KeySystemFormats.WIDEVINE:return KeySystems.WIDEVINE;case KeySystemFormats.CLEARKEY:return KeySystems.CLEARKEY}}var KeySystemIds={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function keySystemIdToKeySystemDomain(e){if(e===KeySystemIds.WIDEVINE)return KeySystems.WIDEVINE}function keySystemDomainToKeySystemFormat(e){switch(e){case KeySystems.FAIRPLAY:return KeySystemFormats.FAIRPLAY;case KeySystems.PLAYREADY:return KeySystemFormats.PLAYREADY;case KeySystems.WIDEVINE:return KeySystemFormats.WIDEVINE;case KeySystems.CLEARKEY:return KeySystemFormats.CLEARKEY}}function getKeySystemsForConfig(e){const{drmSystems:t,widevineLicenseUrl:r}=e,i=t?[KeySystems.FAIRPLAY,KeySystems.WIDEVINE,KeySystems.PLAYREADY,KeySystems.CLEARKEY].filter((e=>!!t[e])):[];return!i[KeySystems.WIDEVINE]&&r&&i.push(KeySystems.WIDEVINE),i}const requestMediaKeySystemAccess=null!=optionalSelf&&null!=(_optionalSelf$navigat=optionalSelf.navigator)&&_optionalSelf$navigat.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var _optionalSelf$navigat;function getSupportedMediaKeySystemConfigurations(e,t,r,i){let s;switch(e){case KeySystems.FAIRPLAY:s=["cenc","sinf"];break;case KeySystems.WIDEVINE:case KeySystems.PLAYREADY:s=["cenc"];break;case KeySystems.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return createMediaKeySystemConfigurations(s,t,r,i)}function createMediaKeySystemConfigurations(e,t,r,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs="${e}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}))),videoCapabilities:r.map((e=>({contentType:`video/mp4; codecs="${e}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null})))}]}function sliceUint8(e,t,r){return Uint8Array.prototype.slice?e.slice(t,r):new Uint8Array(Array.prototype.slice.call(e,t,r))}const isHeader$2=(e,t)=>t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,isFooter=(e,t)=>t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,getID3Data=(e,t)=>{const r=t;let i=0;for(;isHeader$2(e,t);){i+=10;i+=readSize(e,t+6),isFooter(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(r,r+i)},readSize=(e,t)=>{let r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3],r},canParse$2=(e,t)=>isHeader$2(e,t)&&readSize(e,t+6)+10<=e.length-t,getTimeStamp=e=>{const t=getID3Frames(e);for(let r=0;r<t.length;r++){const e=t[r];if(isTimeStampFrame(e))return readTimeStamp(e)}},isTimeStampFrame=e=>e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,getFrameData=e=>{const t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=readSize(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}},getID3Frames=e=>{let t=0;const r=[];for(;isHeader$2(e,t);){const i=readSize(e,t+6);t+=10;const s=t+i;for(;t+8<s;){const i=getFrameData(e.subarray(t)),s=decodeFrame(i);s&&r.push(s),t+=i.size+10}isFooter(e,t)&&(t+=10)}return r},decodeFrame=e=>"PRIV"===e.type?decodePrivFrame(e):"W"===e.type[0]?decodeURLFrame(e):decodeTextFrame(e),decodePrivFrame=e=>{if(e.size<2)return;const t=utf8ArrayToStr(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}},decodeTextFrame=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1;const r=utf8ArrayToStr(e.data.subarray(t),!0);t+=r.length+1;const i=utf8ArrayToStr(e.data.subarray(t));return{key:e.type,info:r,data:i}}const t=utf8ArrayToStr(e.data.subarray(1));return{key:e.type,data:t}},decodeURLFrame=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1;const r=utf8ArrayToStr(e.data.subarray(t),!0);t+=r.length+1;const i=utf8ArrayToStr(e.data.subarray(t));return{key:e.type,info:r,data:i}}const t=utf8ArrayToStr(e.data);return{key:e.type,data:t}},readTimeStamp=e=>{if(8===e.data.byteLength){const t=new Uint8Array(e.data),r=1&t[3];let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}},utf8ArrayToStr=(e,t=!1)=>{const r=getTextDecoder();if(r){const i=r.decode(e);if(t){const e=i.indexOf("\0");return-1!==e?i.substring(0,e):i}return i.replace(/\0/g,"")}const i=e.length;let s,n,a,o="",l=0;for(;l<i;){if(s=e[l++],0===s&&t)return o;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:n=e[l++],o+=String.fromCharCode((31&s)<<6|63&n);break;case 14:n=e[l++],a=e[l++],o+=String.fromCharCode((15&s)<<12|(63&n)<<6|(63&a)<<0)}}return o};let decoder;function getTextDecoder(){if(!navigator.userAgent.includes("PlayStation 4"))return decoder||void 0===self.TextDecoder||(decoder=new self.TextDecoder("utf-8")),decoder}const Hex={hexDump:function(e){let t="";for(let r=0;r<e.length;r++){let i=e[r].toString(16);i.length<2&&(i="0"+i),t+=i}return t}},UINT32_MAX$1=Math.pow(2,32)-1,push=[].push,RemuxerTrackIdConfig={video:1,audio:2,id3:3,text:4};function bin2str(e){return String.fromCharCode.apply(null,e)}function readUint16(e,t){const r=e[t]<<8|e[t+1];return r<0?65536+r:r}function readUint32(e,t){const r=readSint32(e,t);return r<0?4294967296+r:r}function readUint64(e,t){let r=readUint32(e,t);return r*=Math.pow(2,32),r+=readUint32(e,t+4),r}function readSint32(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function writeUint32(e,t,r){e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function hasMoofData(e){const t=e.byteLength;for(let r=0;r<t;){const i=readUint32(e,r);if(i>8&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=i>1?r+i:t}return!1}function findBox(e,t){const r=[];if(!t.length)return r;const i=e.byteLength;for(let s=0;s<i;){const n=readUint32(e,s),a=n>1?s+n:i;if(bin2str(e.subarray(s+4,s+8))===t[0])if(1===t.length)r.push(e.subarray(s+8,a));else{const i=findBox(e.subarray(s+8,a),t.slice(1));i.length&&push.apply(r,i)}s=a}return r}function parseSegmentIndex(e){const t=[],r=e[0];let i=8;const s=readUint32(e,i);i+=4;let n=0,a=0;0===r?(n=readUint32(e,i),a=readUint32(e,i+4),i+=8):(n=readUint64(e,i),a=readUint64(e,i+8),i+=16),i+=2;let o=e.length+a;const l=readUint16(e,i);i+=2;for(let d=0;d<l;d++){let r=i;const n=readUint32(e,r);r+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return logger.warn("SIDX has hierarchical references (not supported)"),null;const l=readUint32(e,r);r+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,r+=4,i=r}return{earliestPresentationTime:n,timescale:s,version:r,referencesCount:l,references:t}}function parseInitSegment(e){const t=[],r=findBox(e,["moov","trak"]);for(let i=0;i<r.length;i++){const e=r[i],s=findBox(e,["tkhd"])[0];if(s){let r=s[0];const i=readUint32(s,0===r?12:20),n=findBox(e,["mdia","mdhd"])[0];if(n){r=n[0];const s=readUint32(n,0===r?12:20),a=findBox(e,["mdia","hdlr"])[0];if(a){const r=bin2str(a.subarray(8,12)),n={soun:ElementaryStreamTypes.AUDIO,vide:ElementaryStreamTypes.VIDEO}[r];if(n){const r=parseStsd(findBox(e,["mdia","minf","stbl","stsd"])[0]);t[i]={timescale:s,type:n},t[n]=_objectSpread2({timescale:s,id:i},r)}}}}}return findBox(e,["moov","mvex","trex"]).forEach((e=>{const r=readUint32(e,4),i=t[r];i&&(i.default={duration:readUint32(e,12),flags:readUint32(e,20)})})),t}function parseStsd(e){const t=e.subarray(8),r=t.subarray(86),i=bin2str(t.subarray(4,8));let s=i;const n="enca"===i||"encv"===i;if(n){const e=findBox(t,[i])[0];findBox(e.subarray("enca"===i?28:78),["sinf"]).forEach((e=>{const t=findBox(e,["schm"])[0];if(t){const r=bin2str(t.subarray(4,8));if("cbcs"===r||"cenc"===r){const t=findBox(e,["frma"])[0];t&&(s=bin2str(t))}}}))}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const e=findBox(r,["avcC"])[0];s+="."+toHex(e[1])+toHex(e[2])+toHex(e[3]);break}case"mp4a":{const e=findBox(t,[i])[0],r=findBox(e.subarray(28),["esds"])[0];if(r&&r.length>12){let e=4;if(3!==r[e++])break;e=skipBERInteger(r,e),e+=2;const t=r[e++];if(128&t&&(e+=2),64&t&&(e+=r[e++]),4!==r[e++])break;e=skipBERInteger(r,e);const i=r[e++];if(64!==i)break;if(s+="."+toHex(i),e+=12,5!==r[e++])break;e=skipBERInteger(r,e);const n=r[e++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&r[e])>>5)),s+="."+a}break}case"hvc1":case"hev1":{const e=findBox(r,["hvcC"])[0],t=e[1],i=["","A","B","C"][t>>6],n=31&t,a=readUint32(e,2),o=(32&t)>>5?"H":"L",l=e[12],d=e.subarray(6,12);s+="."+i+n,s+="."+a.toString(16).toUpperCase(),s+="."+o+l;let c="";for(let r=d.length;r--;){const e=d[r];if(e||c){c="."+e.toString(16).toUpperCase()+c}}s+=c;break}case"dvh1":case"dvhe":{const e=findBox(r,["dvcC"])[0],t=e[2]>>1&127,i=e[2]<<5&32|e[3]>>3&31;s+="."+addLeadingZero(t)+"."+addLeadingZero(i);break}case"vp09":{const e=findBox(r,["vpcC"])[0],t=e[4],i=e[5],n=e[6]>>4&15;s+="."+addLeadingZero(t)+"."+addLeadingZero(i)+"."+addLeadingZero(n);break}case"av01":{const e=findBox(r,["av1C"])[0],t=e[1]>>>5,i=31&e[1],n=e[2]>>>7?"H":"M",a=(64&e[2])>>6,o=(32&e[2])>>5,l=2===t&&a?o?12:10:a?10:8,d=(16&e[2])>>4,c=(8&e[2])>>3,h=(4&e[2])>>2,u=3&e[2],f=1,g=1,m=1,p=0;s+="."+t+"."+addLeadingZero(i)+n+"."+addLeadingZero(l)+"."+d+"."+c+h+u+"."+addLeadingZero(f)+"."+addLeadingZero(g)+"."+addLeadingZero(m)+"."+p;break}}return{codec:s,encrypted:n}}function skipBERInteger(e,t){const r=t+5;for(;128&e[t++]&&t<r;);return t}function toHex(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function addLeadingZero(e){return(e<10?"0":"")+e}function patchEncyptionData(e,t){if(!e||!t)return e;const r=t.keyId;if(r&&t.isCommonEncryption){findBox(e,["moov","trak"]).forEach((e=>{const t=findBox(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let i=findBox(t,["enca"]);const s=i.length>0;s||(i=findBox(t,["encv"])),i.forEach((e=>{findBox(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=parseSinf(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(logger.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Hex.hexDump(e)} -> ${Hex.hexDump(r)}`),t.set(r,8))}}))}))}))}return e}function parseSinf(e){const t=findBox(e,["schm"])[0];if(t){const r=bin2str(t.subarray(4,8));if("cbcs"===r||"cenc"===r)return findBox(e,["schi","tenc"])[0]}return logger.error("[eme] missing 'schm' box"),null}function getStartDTS(e,t){return findBox(t,["moof","traf"]).reduce(((t,r)=>{const i=findBox(r,["tfdt"])[0],s=i[0],n=findBox(r,["tfhd"]).reduce(((t,r)=>{const n=readUint32(r,4),a=e[n];if(a){let e=readUint32(i,4);if(1===s){if(e===UINT32_MAX$1)return logger.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=UINT32_MAX$1+1,e+=readUint32(i,8)}const r=e/(a.timescale||9e4);if(isFiniteNumber(r)&&(null===t||r<t))return r}return t}),null);return null!==n&&isFiniteNumber(n)&&(null===t||n<t)?n:t}),null)}function getDuration(e,t){let r=0,i=0,s=0;const n=findBox(e,["moof","traf"]);for(let a=0;a<n.length;a++){const e=n[a],o=findBox(e,["tfhd"])[0],l=t[readUint32(o,4)];if(!l)continue;const d=l.default,c=readUint32(o,0)|(null==d?void 0:d.flags);let h=null==d?void 0:d.duration;8&c&&(h=readUint32(o,2&c?12:8));const u=l.timescale||9e4,f=findBox(e,["trun"]);for(let t=0;t<f.length;t++){if(r=computeRawDurationFromSamples(f[t]),!r&&h){r=h*readUint32(f[t],4)}l.type===ElementaryStreamTypes.VIDEO?i+=r/u:l.type===ElementaryStreamTypes.AUDIO&&(s+=r/u)}}if(0===i&&0===s){let t=1/0,r=0,i=0;const s=findBox(e,["sidx"]);for(let e=0;e<s.length;e++){const n=parseSegmentIndex(s[e]);if(null!=n&&n.references){t=Math.min(t,n.earliestPresentationTime/n.timescale);const e=n.references.reduce(((e,t)=>e+t.info.duration||0),0);r=Math.max(r,e+n.earliestPresentationTime/n.timescale),i=r-t}}if(i&&isFiniteNumber(i))return i}return i||s}function computeRawDurationFromSamples(e){const t=readUint32(e,0);let r=8;1&t&&(r+=4),4&t&&(r+=4);let i=0;const s=readUint32(e,4);for(let n=0;n<s;n++){if(256&t){i+=readUint32(e,r),r+=4}512&t&&(r+=4),1024&t&&(r+=4),2048&t&&(r+=4)}return i}function offsetStartDTS(e,t,r){findBox(t,["moof","traf"]).forEach((t=>{findBox(t,["tfhd"]).forEach((i=>{const s=readUint32(i,4),n=e[s];if(!n)return;const a=n.timescale||9e4;findBox(t,["tfdt"]).forEach((e=>{const t=e[0],i=r*a;if(i){let r=readUint32(e,4);if(0===t)r-=i,r=Math.max(r,0),writeUint32(e,4,r);else{r*=Math.pow(2,32),r+=readUint32(e,8),r-=i,r=Math.max(r,0);const t=Math.floor(r/(UINT32_MAX$1+1)),s=Math.floor(r%(UINT32_MAX$1+1));writeUint32(e,4,t),writeUint32(e,8,s)}}}))}))}))}function segmentValidRange(e){const t={valid:null,remainder:null},r=findBox(e,["moof"]);if(r.length<2)return t.remainder=e,t;const i=r[r.length-1];return t.valid=sliceUint8(e,0,i.byteOffset-8),t.remainder=sliceUint8(e,i.byteOffset-8),t}function appendUint8Array(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function parseSamples(e,t){const r=[],i=t.samples,s=t.timescale,n=t.id;let a=!1;return findBox(i,["moof"]).map((o=>{const l=o.byteOffset-8;findBox(o,["traf"]).map((o=>{const d=findBox(o,["tfdt"]).map((e=>{const t=e[0];let r=readUint32(e,4);return 1===t&&(r*=Math.pow(2,32),r+=readUint32(e,8)),r/s}))[0];return void 0!==d&&(e=d),findBox(o,["tfhd"]).map((d=>{const c=readUint32(d,4),h=16777215&readUint32(d,0);let u=0;const f=0!=(16&h);let g=0;const m=0!=(32&h);let p=8;c===n&&(0!=(1&h)&&(p+=8),0!=(2&h)&&(p+=4),0!=(8&h)&&(u=readUint32(d,p),p+=4),f&&(g=readUint32(d,p),p+=4),m&&(p+=4),"video"===t.type&&(a=isHEVC(t.codec)),findBox(o,["trun"]).map((n=>{const o=n[0],d=16777215&readUint32(n,0),c=0!=(1&d);let h=0;const f=0!=(4&d),m=0!=(256&d);let p=0;const y=0!=(512&d);let E=0;const v=0!=(1024&d),T=0!=(2048&d);let S=0;const L=readUint32(n,4);let A=8;c&&(h=readUint32(n,A),A+=4),f&&(A+=4);let b=h+l;for(let l=0;l<L;l++){if(m?(p=readUint32(n,A),A+=4):p=u,y?(E=readUint32(n,A),A+=4):E=g,v&&(A+=4),T&&(S=0===o?readUint32(n,A):readSint32(n,A),A+=4),t.type===ElementaryStreamTypes.VIDEO){let t=0;for(;t<E;){const n=readUint32(i,b);if(b+=4,isSEIMessage(a,i[b])){parseSEIMessageFromNALu(i.subarray(b,b+n),a?2:1,e+S/s,r)}b+=n,t+=n+4}}e+=p/s}})))}))}))})),r}function isHEVC(e){if(!e)return!1;const t=e.indexOf("."),r=t<0?e:e.substring(0,t);return"hvc1"===r||"hev1"===r||"dvh1"===r||"dvhe"===r}function isSEIMessage(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function parseSEIMessageFromNALu(e,t,r,i){const s=discardEPB(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);const e=s.length-n;let t=n;if(o<e)n+=o;else if(o>e){logger.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===s[t++]){const e=readUint16(s,t);if(t+=2,49===e){const e=readUint32(s,t);if(t+=4,1195456820===e){const e=s[t++];if(3===e){const n=s[t++],o=31&n,l=64&n,d=l?2+3*o:0,c=new Uint8Array(d);if(l){c[0]=n;for(let e=1;e<d;e++)c[e]=s[t++]}i.push({type:e,payloadType:a,pts:r,bytes:c})}}}}}else if(5===a&&o>16){const e=[];for(let r=0;r<16;r++){const i=s[t++].toString(16);e.push(1==i.length?"0"+i:i),3!==r&&5!==r&&7!==r&&9!==r||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let r=0;r<n;r++)l[r]=s[t++];i.push({payloadType:a,pts:r,uuid:e.join(""),userData:utf8ArrayToStr(l),userDataBytes:l})}}}function discardEPB(e){const t=e.byteLength,r=[];let i=1;for(;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return e;const s=t-r.length,n=new Uint8Array(s);let a=0;for(i=0;i<s;a++,i++)a===r[0]&&(a++,r.shift()),n[i]=e[a];return n}function parseEmsg(e){const t=e[0];let r="",i="",s=0,n=0,a=0,o=0,l=0,d=0;if(0===t){for(;"\0"!==bin2str(e.subarray(d,d+1));)r+=bin2str(e.subarray(d,d+1)),d+=1;for(r+=bin2str(e.subarray(d,d+1)),d+=1;"\0"!==bin2str(e.subarray(d,d+1));)i+=bin2str(e.subarray(d,d+1)),d+=1;i+=bin2str(e.subarray(d,d+1)),d+=1,s=readUint32(e,12),n=readUint32(e,16),o=readUint32(e,20),l=readUint32(e,24),d=28}else if(1===t){d+=4,s=readUint32(e,d),d+=4;const t=readUint32(e,d);d+=4;const n=readUint32(e,d);for(d+=4,a=2**32*t+n,isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=readUint32(e,d),d+=4,l=readUint32(e,d),d+=4;"\0"!==bin2str(e.subarray(d,d+1));)r+=bin2str(e.subarray(d,d+1)),d+=1;for(r+=bin2str(e.subarray(d,d+1)),d+=1;"\0"!==bin2str(e.subarray(d,d+1));)i+=bin2str(e.subarray(d,d+1)),d+=1;i+=bin2str(e.subarray(d,d+1)),d+=1}return{schemeIdUri:r,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(d,e.byteLength)}}function mp4Box(e,...t){const r=t.length;let i=8,s=r;for(;s--;)i+=t[s].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(e,4),s=0,i=8;s<r;s++)n.set(t[s],i),i+=t[s].byteLength;return n}function mp4pssh(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");let i,s,n;if(t){i=1,s=new Uint8Array(16*t.length);for(let e=0;e<t.length;e++){const r=t[e];if(16!==r.byteLength)throw new RangeError("Invalid key");s.set(r,16*e)}}else i=0,s=new Uint8Array;i>0?(n=new Uint8Array(4),t.length>0&&new DataView(n.buffer).setUint32(0,t.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return r&&r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),mp4Box([112,115,115,104],new Uint8Array([i,0,0,0]),e,n,s,a,r||new Uint8Array)}function parsePssh(e){if(!(e instanceof ArrayBuffer)||e.byteLength<32)return null;const t={version:0,systemId:"",kids:null,data:null},r=new DataView(e),i=r.getUint32(0);if(e.byteLength!==i&&i>44)return null;if(1886614376!==r.getUint32(4))return null;if(t.version=r.getUint32(8)>>>24,t.version>1)return null;t.systemId=Hex.hexDump(new Uint8Array(e,12,16));const s=r.getUint32(28);if(0===t.version){if(i-32<s)return null;t.data=new Uint8Array(e,32,s)}else if(1===t.version){t.kids=[];for(let r=0;r<s;r++)t.kids.push(new Uint8Array(e,32+16*r,16))}return t}let keyUriToKeyIdMap={};class LevelKey{static clearKeyUriToKeyIdMap(){keyUriToKeyIdMap={}}constructor(e,t,r,i=[1],s=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=r,this.keyFormatVersions=i,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&"AES-128"!==e}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case KeySystemFormats.FAIRPLAY:case KeySystemFormats.WIDEVINE:case KeySystemFormats.PLAYREADY:case KeySystemFormats.CLEARKEY:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof e&&("AES-128"!==this.method||this.iv||logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const t=createInitializationVector(e);return new LevelKey(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=convertDataUriToArrayBytes(this.uri);if(t)switch(this.keyFormat){case KeySystemFormats.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case KeySystemFormats.PLAYREADY:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mp4pssh(e,null,t);const r=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),i=String.fromCharCode.apply(null,Array.from(r)),s=i.substring(i.indexOf("<"),i.length),n=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const e=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(e){const t=base64Decode(e).subarray(0,16);changeEndianness(t),this.keyId=t}}break}default:{let e=t.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=keyUriToKeyIdMap[this.uri];if(!e){const t=Object.keys(keyUriToKeyIdMap).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),keyUriToKeyIdMap[this.uri]=e}this.keyId=e}return this}}function createInitializationVector(e){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}const VARIABLE_REPLACEMENT_REGEX=/\{\$([a-zA-Z0-9-_]+)\}/g;function hasVariableReferences(e){return VARIABLE_REPLACEMENT_REGEX.test(e)}function substituteVariablesInAttributes(e,t,r){if(null!==e.variableList||e.hasVariableRefs)for(let i=r.length;i--;){const s=r[i],n=t[s];n&&(t[s]=substituteVariables(e,n))}}function substituteVariables(e,t){if(null!==e.variableList||e.hasVariableRefs){const r=e.variableList;return t.replace(VARIABLE_REPLACEMENT_REGEX,(t=>{const i=t.substring(2,t.length-1),s=null==r?void 0:r[i];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),t):s}))}return t}function addVariableDefinition(e,t,r){let i,s,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){i=t.QUERYPARAM;try{const e=new self.URL(r).searchParams;if(!e.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${r}"`);s=e.get(i)}catch(a){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=t.NAME,s=t.VALUE;i in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=s||""}function importVariableDefinition(e,t,r){const i=t.IMPORT;if(r&&i in r){let t=e.variableList;t||(e.variableList=t={}),t[i]=r[i]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function getMediaSource(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const sampleEntryCodesISO={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function isCodecType(e,t){const r=sampleEntryCodesISO[t];return!!r&&!!r[e.slice(0,4)]}function areCodecsMediaSourceSupported(e,t,r=!0){return!e.split(",").some((e=>!isCodecMediaSourceSupported(e,t,r)))}function isCodecMediaSourceSupported(e,t,r=!0){var i;const s=getMediaSource(r);return null!=(i=null==s?void 0:s.isTypeSupported(mimeTypeForCodec(e,t)))&&i}function mimeTypeForCodec(e,t){return`${t}/mp4;codecs="${e}"`}function videoCodecPreferenceValue(e){if(e){const t=e.substring(0,4);return sampleEntryCodesISO.video[t]}return 2}function codecsSetSelectionPreferenceValue(e){return e.split(",").reduce(((e,t)=>{const r=sampleEntryCodesISO.video[t];return r?(2*r+e)/(e?3:2):(sampleEntryCodesISO.audio[t]+e)/(e?2:1)}),0)}const CODEC_COMPATIBLE_NAMES={};function getCodecCompatibleNameLower(e,t=!0){if(CODEC_COMPATIBLE_NAMES[e])return CODEC_COMPATIBLE_NAMES[e];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[e];for(let i=0;i<r.length;i++)if(isCodecMediaSourceSupported(r[i],"audio",t))return CODEC_COMPATIBLE_NAMES[e]=r[i],r[i];return e}const AUDIO_CODEC_REGEXP=/flac|opus/i;function getCodecCompatibleName(e,t=!0){return e.replace(AUDIO_CODEC_REGEXP,(e=>getCodecCompatibleNameLower(e.toLowerCase(),t)))}function pickMostCompleteCodecName(e,t){return e&&"mp4a"!==e?e:t}function convertAVC1ToAVCOTI(e){const t=e.split(".");if(t.length>2){let e=t.shift()+".";return e+=parseInt(t.shift()).toString(16),e+=("000"+parseInt(t.shift()).toString(16)).slice(-4),e}return e}const MASTER_PLAYLIST_REGEX=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,MASTER_PLAYLIST_MEDIA_REGEX=/#EXT-X-MEDIA:(.*)/g,IS_MEDIA_PLAYLIST=/^#EXT(?:INF|-X-TARGETDURATION):/m,LEVEL_PLAYLIST_REGEX_FAST=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),LEVEL_PLAYLIST_REGEX_SLOW=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class M3U8Parser{static findGroup(e,t){for(let r=0;r<e.length;r++){const i=e[r];if(i.id===t)return i}}static resolve(e,t){return urlToolkitExports.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return IS_MEDIA_PLAYLIST.test(e)}static parseMasterPlaylist(e,t){const r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:hasVariableReferences(e)},i=[];let s;for(MASTER_PLAYLIST_REGEX.lastIndex=0;null!=(s=MASTER_PLAYLIST_REGEX.exec(e));)if(s[1]){var n;const e=new AttrList(s[1]);substituteVariablesInAttributes(r,e,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=substituteVariables(r,s[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:M3U8Parser.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),setCodecs(e.CODECS,o),null!=(n=o.unknownCodecs)&&n.length||i.push(o),r.levels.push(o)}else if(s[3]){const e=s[3],i=s[4];switch(e){case"SESSION-DATA":{const e=new AttrList(i);substituteVariablesInAttributes(r,e,["DATA-ID","LANGUAGE","VALUE","URI"]);const t=e["DATA-ID"];t&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[t]=e);break}case"SESSION-KEY":{const e=parseKey(i,t,r);e.encrypted&&e.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(e)):logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":{const e=new AttrList(i);substituteVariablesInAttributes(r,e,["NAME","VALUE","QUERYPARAM"]),addVariableDefinition(r,e,t)}break;case"CONTENT-STEERING":{const e=new AttrList(i);substituteVariablesInAttributes(r,e,["SERVER-URI","PATHWAY-ID"]),r.contentSteering={uri:M3U8Parser.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=parseStartTimeOffset(i)}}const a=i.length>0&&i.length<r.levels.length;return r.levels=a?i:r.levels,0===r.levels.length&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,r){let i;const s={},n=r.levels,a={AUDIO:n.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:n.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(MASTER_PLAYLIST_MEDIA_REGEX.lastIndex=0;null!==(i=MASTER_PLAYLIST_MEDIA_REGEX.exec(e));){const e=new AttrList(i[1]),n=e.TYPE;if(n){const i=a[n],l=s[n]||[];s[n]=l,substituteVariablesInAttributes(r,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const d=e.LANGUAGE,c=e["ASSOC-LANGUAGE"],h=e.CHANNELS,u=e.CHARACTERISTICS,f=e["INSTREAM-ID"],g={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||d||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:d,url:e.URI?M3U8Parser.resolve(e.URI,t):""};if(c&&(g.assocLang=c),h&&(g.channels=h),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=i&&i.length){const e=M3U8Parser.findGroup(i,g.groupId)||i[0];assignCodec(g,e,"audioCodec"),assignCodec(g,e,"textCodec")}l.push(g)}}return s}static parseLevelPlaylist(e,t,r,i,s,n){const a=new LevelDetails(t),o=a.fragments;let l,d,c,h=null,u=0,f=0,g=0,m=0,p=null,y=new Fragment(i,t),E=-1,v=!1,T=null;for(LEVEL_PLAYLIST_REGEX_FAST.lastIndex=0,a.m3u8=e,a.hasVariableRefs=hasVariableReferences(e);null!==(l=LEVEL_PLAYLIST_REGEX_FAST.exec(e));){v&&(v=!1,y=new Fragment(i,t),y.start=g,y.sn=u,y.cc=m,y.level=r,h&&(y.initSegment=h,y.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null,T&&(y.setByteRange(T),T=null)));const e=l[1];if(e){y.duration=parseFloat(e);const t=(" "+l[2]).slice(1);y.title=t||null,y.tagList.push(t?["INF",e,t]:["INF",e])}else if(l[3]){if(isFiniteNumber(y.duration)){y.start=g,c&&setFragLevelKeys(y,c,a),y.sn=u,y.level=r,y.cc=m,o.push(y);const e=(" "+l[3]).slice(1);y.relurl=substituteVariables(a,e),assignProgramDateTime(y,p),p=y,g+=y.duration,u++,f=0,v=!0}}else if(l[4]){const e=(" "+l[4]).slice(1);p?y.setByteRange(e,p):y.setByteRange(e)}else if(l[5])y.rawProgramDateTime=(" "+l[5]).slice(1),y.tagList.push(["PROGRAM-DATE-TIME",y.rawProgramDateTime]),-1===E&&(E=o.length);else{if(l=l[0].match(LEVEL_PLAYLIST_REGEX_SLOW),!l){logger.warn("No matches on slow regex match for level playlist!");continue}for(d=1;d<l.length&&void 0===l[d];d++);const e=(" "+l[d]).slice(1),s=(" "+l[d+1]).slice(1),g=l[d+2]?(" "+l[d+2]).slice(1):"";switch(e){case"PLAYLIST-TYPE":a.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":u=a.startSN=parseInt(s);break;case"SKIP":{const e=new AttrList(s);substituteVariablesInAttributes(a,e,["RECENTLY-REMOVED-DATERANGES"]);const t=e.decimalInteger("SKIPPED-SEGMENTS");if(isFiniteNumber(t)){a.skippedSegments=t;for(let e=t;e--;)o.unshift(null);u+=t}const r=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(a.recentlyRemovedDateranges=r.split("\t"));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(s),1);break;case"VERSION":a.version=parseInt(s);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(s||g)&&y.tagList.push(g?[s,g]:[s]);break;case"DISCONTINUITY":m++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([e]);break;case"BITRATE":y.tagList.push([e,s]);break;case"DATERANGE":{const e=new AttrList(s);substituteVariablesInAttributes(a,e,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),substituteVariablesInAttributes(a,e,e.clientAttrs);const t=new DateRange(e,a.dateRanges[e.ID]);t.isValid||a.skippedSegments?a.dateRanges[t.id]=t:logger.warn(`Ignoring invalid DATERANGE tag: "${s}"`),y.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{const e=new AttrList(s);substituteVariablesInAttributes(a,e,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in e?importVariableDefinition(a,e,n):addVariableDefinition(a,e,t)}break;case"DISCONTINUITY-SEQUENCE":m=parseInt(s);break;case"KEY":{const e=parseKey(s,t,a);if(e.isSupported()){if("NONE"===e.method){c=void 0;break}c||(c={}),c[e.keyFormat]&&(c=_extends({},c)),c[e.keyFormat]=e}else logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":a.startTimeOffset=parseStartTimeOffset(s);break;case"MAP":{const e=new AttrList(s);if(substituteVariablesInAttributes(a,e,["BYTERANGE","URI"]),y.duration){const s=new Fragment(i,t);setInitSegment(s,e,r,c),h=s,y.initSegment=h,h.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=h.rawProgramDateTime)}else{const t=y.byteRangeEndOffset;if(t){const e=y.byteRangeStartOffset;T=`${t-e}@${e}`}else T=null;setInitSegment(y,e,r,c),h=y,v=!0}break}case"SERVER-CONTROL":{const e=new AttrList(s);a.canBlockReload=e.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=e.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&e.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),a.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new AttrList(s);a.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=a.partList;e||(e=a.partList=[]);const r=f>0?e[e.length-1]:void 0,i=f++,n=new AttrList(s);substituteVariablesInAttributes(a,n,["BYTERANGE","URI"]);const o=new Part(n,y,t,i,r);e.push(o),y.duration+=o.duration;break}case"PRELOAD-HINT":{const e=new AttrList(s);substituteVariablesInAttributes(a,e,["URI"]),a.preloadHint=e;break}case"RENDITION-REPORT":{const e=new AttrList(s);substituteVariablesInAttributes(a,e,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(e);break}default:logger.warn(`line parsed but not handled: ${l}`)}}}p&&!p.relurl?(o.pop(),g-=p.duration,a.partList&&(a.fragmentHint=p)):a.partList&&(assignProgramDateTime(y,p),y.cc=m,a.fragmentHint=y,c&&setFragLevelKeys(y,c,a));const S=o.length,L=o[0],A=o[S-1];if(g+=a.skippedSegments*a.targetduration,g>0&&S&&A){a.averagetargetduration=g/S;const e=A.sn;a.endSN="initSegment"!==e?e:0,a.live||(A.endList=!0),L&&(a.startCC=L.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(g+=a.fragmentHint.duration),a.totalduration=g,a.endCC=m,E>0&&backfillProgramDateTimes(o,E),a}}function parseKey(e,t,r){var i,s;const n=new AttrList(e);substituteVariablesInAttributes(r,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&logger.error(`Invalid IV: ${n.IV}`);const h=o?M3U8Parser.resolve(o,t):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new LevelKey(a,h,c,u,l)}function parseStartTimeOffset(e){const t=new AttrList(e).decimalFloatingPoint("TIME-OFFSET");return isFiniteNumber(t)?t:null}function setCodecs(e,t){let r=(e||"").split(/[ ,]+/).filter((e=>e));["video","audio","text"].forEach((e=>{const i=r.filter((t=>isCodecType(t,e)));i.length&&(t[`${e}Codec`]=i.join(","),r=r.filter((e=>-1===i.indexOf(e))))})),t.unknownCodecs=r}function assignCodec(e,t,r){const i=t[r];i&&(e[r]=i)}function backfillProgramDateTimes(e,t){let r=e[t];for(let i=t;i--;){const t=e[i];if(!t)return;t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}function assignProgramDateTime(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),isFiniteNumber(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function setInitSegment(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function setFragLevelKeys(e,t,r){e.levelkeys=t;const{encryptedFragments:i}=r;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||i.push(e)}var PlaylistContextType={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},PlaylistLevelType={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function mapContextToLevelType(e){const{type:t}=e;switch(t){case PlaylistContextType.AUDIO_TRACK:return PlaylistLevelType.AUDIO;case PlaylistContextType.SUBTITLE_TRACK:return PlaylistLevelType.SUBTITLE;default:return PlaylistLevelType.MAIN}}function getResponseUrl(e,t){let r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}class PlaylistLoader{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,i=t.loader,s=new(r||i)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:PlaylistContextType.MANIFEST,url:r,deliveryDirectives:null})}onLevelLoading(e,t){const{id:r,level:i,pathwayId:s,url:n,deliveryDirectives:a}=t;this.load({id:r,level:i,pathwayId:s,responseType:"text",type:PlaylistContextType.LEVEL,url:n,deliveryDirectives:a})}onAudioTrackLoading(e,t){const{id:r,groupId:i,url:s,deliveryDirectives:n}=t;this.load({id:r,groupId:i,level:null,responseType:"text",type:PlaylistContextType.AUDIO_TRACK,url:s,deliveryDirectives:n})}onSubtitleTrackLoading(e,t){const{id:r,groupId:i,url:s,deliveryDirectives:n}=t;this.load({id:r,groupId:i,level:null,responseType:"text",type:PlaylistContextType.SUBTITLE_TRACK,url:s,deliveryDirectives:n})}load(e){var t;const r=this.hls.config;let i,s=this.getInternalLoader(e);if(s){const t=s.context;if(t&&t.url===e.url&&t.level===e.level)return void logger.trace("[playlist-loader]: playlist request ongoing");logger.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(i=e.type===PlaylistContextType.MANIFEST?r.manifestLoadPolicy.default:_extends({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),isFiniteNumber(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===PlaylistContextType.LEVEL&&null!==e.level?t=this.hls.levels[e.level].details:e.type===PlaylistContextType.AUDIO_TRACK&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===PlaylistContextType.SUBTITLE_TRACK&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,r=t.targetduration;if(e&&r){const t=1e3*Math.max(3*e,.8*r);i=_extends({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,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:(e,t,r,i)=>{const s=this.getInternalLoader(r);this.resetInternalLoader(r.type);const n=e.data;0===n.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(e,t,r,i||null,s):this.handleMasterPlaylist(e,t,r,i)):this.handleManifestParsingError(e,r,new Error("no EXTM3U delimiter"),i||null,t)},onError:(e,t,r,i)=>{this.handleNetworkError(t,r,!1,e,i)},onTimeout:(e,t,r)=>{this.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,a,o)}handleMasterPlaylist(e,t,r,i){const s=this.hls,n=e.data,a=getResponseUrl(e,r),o=M3U8Parser.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,r,o.playlistParsingError,i,t);const{contentSteering:l,levels:d,sessionData:c,sessionKeys:h,startTimeOffset:u,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=M3U8Parser.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((e=>!e.url))||!d[0].audioCodec||d[0].attrs.AUDIO||(logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:""}))}s.trigger(Events.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:c,sessionKeys:h,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,r,i,s){const n=this.hls,{id:a,level:o,type:l}=r,d=getResponseUrl(e,r),c=isFiniteNumber(o)?o:isFiniteNumber(a)?a:0,h=mapContextToLevelType(r),u=M3U8Parser.parseLevelPlaylist(e.data,d,c,h,0,this.variableList);if(l===PlaylistContextType.MANIFEST){const e={attrs:new AttrList({}),bitrate:0,details:u,name:"",url:d};n.trigger(Events.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:d,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=u,this.handlePlaylistLoaded(u,e,t,r,i,s)}handleManifestParsingError(e,t,r,i,s){this.hls.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.MANIFEST_PARSING_ERROR,fatal:t.type===PlaylistContextType.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:s})}handleNetworkError(e,t,r=!1,i,s){let n=`A network ${r?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===PlaylistContextType.LEVEL?n+=`: ${e.level} id: ${e.id}`:e.type!==PlaylistContextType.AUDIO_TRACK&&e.type!==PlaylistContextType.SUBTITLE_TRACK||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);logger.warn(`[playlist-loader]: ${n}`);let o=ErrorDetails.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case PlaylistContextType.MANIFEST:o=r?ErrorDetails.MANIFEST_LOAD_TIMEOUT:ErrorDetails.MANIFEST_LOAD_ERROR,l=!0;break;case PlaylistContextType.LEVEL:o=r?ErrorDetails.LEVEL_LOAD_TIMEOUT:ErrorDetails.LEVEL_LOAD_ERROR,l=!1;break;case PlaylistContextType.AUDIO_TRACK:o=r?ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case PlaylistContextType.SUBTITLE_TRACK:o=r?ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:ErrorDetails.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(e.type);const c={type:ErrorTypes.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:s};if(i){const r=(null==t?void 0:t.url)||e.url;c.response=_objectSpread2({url:r,data:void 0},i)}this.hls.trigger(Events.ERROR,c)}handlePlaylistLoaded(e,t,r,i,s,n){const a=this.hls,{type:o,level:l,id:d,groupId:c,deliveryDirectives:h}=i,u=getResponseUrl(t,i),f=mapContextToLevelType(i),g="number"==typeof i.level&&f===PlaylistLevelType.MAIN?l:void 0;if(!e.fragments.length){const e=new Error("No Segments found in Playlist");return void a.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:u,error:e,reason:e.message,response:t,context:i,level:g,parent:f,networkDetails:s,stats:r})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const m=e.playlistParsingError;if(m)a.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_PARSING_ERROR,fatal:!1,url:u,error:m,reason:m.message,response:t,context:i,level:g,parent:f,networkDetails:s,stats:r});else switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case PlaylistContextType.MANIFEST:case PlaylistContextType.LEVEL:a.trigger(Events.LEVEL_LOADED,{details:e,level:g||0,id:d||0,stats:r,networkDetails:s,deliveryDirectives:h});break;case PlaylistContextType.AUDIO_TRACK:a.trigger(Events.AUDIO_TRACK_LOADED,{details:e,id:d||0,groupId:c||"",stats:r,networkDetails:s,deliveryDirectives:h});break;case PlaylistContextType.SUBTITLE_TRACK:a.trigger(Events.SUBTITLE_TRACK_LOADED,{details:e,id:d||0,groupId:c||"",stats:r,networkDetails:s,deliveryDirectives:h})}}}function sendAddTrackEvent(e,t){let r;try{r=new Event("addtrack")}catch(i){r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function addCueToTrack(e,t){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){logger.debug(`[texttrack-utils]: ${i}`);try{const r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(s){logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}"disabled"===r&&(e.mode=r)}function clearCurrentCues(e){const t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(let r=e.cues.length;r--;)e.removeCue(e.cues[r]);"disabled"===t&&(e.mode=t)}function removeCuesInRange(e,t,r,i){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){const s=getCuesInRange(e.cues,t,r);for(let t=0;t<s.length;t++)i&&!i(s[t])||e.removeCue(s[t])}"disabled"===s&&(e.mode=s)}function getFirstCueIndexAfterTime(e,t){if(t<e[0].startTime)return 0;const r=e.length-1;if(t>e[r].endTime)return-1;let i=0,s=r;for(;i<=s;){const n=Math.floor((s+i)/2);if(t<e[n].startTime)s=n-1;else{if(!(t>e[n].startTime&&i<r))return n;i=n+1}}return e[i].startTime-t<t-e[s].startTime?i:s}function getCuesInRange(e,t,r){const i=[],s=getFirstCueIndexAfterTime(e,t);if(s>-1)for(let n=s,a=e.length;n<a;n++){const s=e[n];if(s.startTime>=t&&s.endTime<=r)i.push(s);else if(s.startTime>r)return i}return i}function filterSubtitleTracks(e){const t=[];for(let r=0;r<e.length;r++){const i=e[r];"subtitles"!==i.kind&&"captions"!==i.kind||!i.label||t.push(e[r])}return t}var MetadataSchema={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const MIN_CUE_DURATION=.25;function getCueClass(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function createCueWithDataFields(e,t,r,i,s){let n=new e(t,r,"");try{n.value=i,s&&(n.type=s)}catch(a){n=new e(t,r,JSON.stringify(s?_objectSpread2({type:s},i):i))}return n}const MAX_CUE_ENDTIME=(()=>{const e=getCueClass();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function dateRangeDateToTimelineSeconds(e,t){return e.getTime()/1e3-t}function hexToArrayBuffer(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class ID3TrackController{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(clearCurrentCues(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const r=e[t];if("metadata"===r.kind&&"id3"===r.label)return sendAddTrackEvent(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:r,enableID3MetadataCues:i}}}=this;if(!r&&!i)return;const{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=getCueClass();if(n)for(let a=0;a<s.length;a++){const e=s[a].type;if(e===MetadataSchema.emsg&&!r||!i)continue;const t=getID3Frames(s[a].data);if(t){const r=s[a].pts;let i=r+s[a].duration;i>MAX_CUE_ENDTIME&&(i=MAX_CUE_ENDTIME);i-r<=0&&(i=r+MIN_CUE_DURATION);for(let s=0;s<t.length;s++){const a=t[s];if(!isTimeStampFrame(a)){this.updateId3CueEnds(r,e);const t=createCueWithDataFields(n,r,i,a,e);t&&this.id3Track.addCue(t)}}}}}updateId3CueEnds(e,t){var r;const i=null==(r=this.id3Track)?void 0:r.cues;if(i)for(let s=i.length;s--;){const r=i[s];r.type===t&&r.startTime<e&&r.endTime===MAX_CUE_ENDTIME&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:i}){const{id3Track:s,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(s&&(a||o)){let e;e="audio"===i?e=>e.type===MetadataSchema.audioId3&&o:"video"===i?e=>e.type===MetadataSchema.emsg&&a:e=>e.type===MetadataSchema.audioId3&&o||e.type===MetadataSchema.emsg&&a,removeCuesInRange(s,t,r,e)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:r,id3Track:i}=this,{dateRanges:s}=t,n=Object.keys(s);if(i){const e=Object.keys(r).filter((e=>!n.includes(e)));for(let t=e.length;t--;){const s=e[t];Object.keys(r[s].cues).forEach((e=>{i.removeCue(r[s].cues[e])})),delete r[s]}}const a=t.fragments[t.fragments.length-1];if(0===n.length||!isFiniteNumber(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=getCueClass();for(let d=0;d<n.length;d++){const e=n[d],t=s[e],i=dateRangeDateToTimelineSeconds(t.startDate,o),a=r[e],c=(null==a?void 0:a.cues)||{};let h=(null==a?void 0:a.durationKnown)||!1,u=MAX_CUE_ENDTIME;const f=t.endDate;if(f)u=dateRangeDateToTimelineSeconds(f,o),h=!0;else if(t.endOnNext&&!h){const e=n.reduce(((e,r)=>{if(r!==t.id){const i=s[r];if(i.class===t.class&&i.startDate>t.startDate&&(!e||t.startDate<e.startDate))return i}return e}),null);e&&(u=dateRangeDateToTimelineSeconds(e.startDate,o),h=!0)}const g=Object.keys(t.attr);for(let r=0;r<g.length;r++){const s=g[r];if(!isDateRangeCueAttribute(s))continue;const n=c[s];if(n)h&&!a.durationKnown&&(n.endTime=u);else if(l){let r=t.attr[s];isSCTE35Attribute(s)&&(r=hexToArrayBuffer(r));const n=createCueWithDataFields(l,i,u,{key:s,data:r},MetadataSchema.dateRange);n&&(n.id=e,this.id3Track.addCue(n),c[s]=n)}}r[e]={cues:c,dateRange:t,durationKnown:h}}}}class LatencyController{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(null===e)return null;const{holdBack:t,partHoldBack:r,targetduration:i}=e,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&r||t;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:n*i);const d=i;return l+Math.min(1*this.stallCount,d)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,r=this.levelDetails;if(null===e||null===t||null===r)return null;const i=r.edge,s=e-t-this.edgeStalled,n=i-r.totalduration,a=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,s),a)}get drift(){const{levelDetails:e}=this;return null===e?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(Events.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(Events.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var r;t.details===ErrorDetails.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(r=this.levelDetails)&&r.live&&logger.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:s}=this.config;if(!i||1===s||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=r-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),r=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(t,Math.max(1,r))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}const HdcpLevels=["NONE","TYPE-0","TYPE-1",null];function isHdcpLevel(e){return HdcpLevels.indexOf(e)>-1}const VideoRangeValues=["SDR","PQ","HLG"];function isVideoRange(e){return!!e&&VideoRangeValues.indexOf(e)>-1}var HlsSkip={No:"",Yes:"YES",v2:"v2"};function getSkipValue(e,t){const{canSkipUntil:r,canSkipDateRanges:i,endSN:s}=e;return r&&(void 0!==t?t-s:0)<r?i?HlsSkip.v2:HlsSkip.Yes:HlsSkip.No}class HlsUrlParameters{constructor(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Level{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>!!e)).map((e=>e.substring(0,4))).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return hasGroup(this._audioGroups,e)}hasSubtitleGroup(e){return hasGroup(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function hasGroup(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function updateFromToPTS(e,t){const r=t.startPTS;if(isFiniteNumber(r)){let i,s=0;t.sn>e.sn?(s=r-e.start,i=e):(s=e.start-r,i=t),i.duration!==s&&(i.duration=s)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration}else t.start=Math.max(e.start-t.duration,0)}function updateFragPTSDTS(e,t,r,i,s,n){i-r<=0&&(logger.warn("Fragment should have a positive duration",t),i=r+t.duration,n=s+t.duration);let a=r,o=i;const l=t.startPTS,d=t.endPTS;if(isFiniteNumber(l)){const e=Math.abs(l-r);isFiniteNumber(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(r,l),r=Math.min(r,l),s=Math.min(s,t.startDTS),o=Math.min(i,d),i=Math.max(i,d),n=Math.max(n,t.endDTS)}const c=r-t.start;0!==t.start&&(t.start=r),t.duration=i-t.start,t.startPTS=r,t.maxStartPTS=a,t.startDTS=s,t.endPTS=i,t.minEndPTS=o,t.endDTS=n;const h=t.sn;if(!e||h<e.startSN||h>e.endSN)return 0;let u;const f=h-e.startSN,g=e.fragments;for(g[f]=t,u=f;u>0;u--)updateFromToPTS(g[u],g[u-1]);for(u=f;u<g.length-1;u++)updateFromToPTS(g[u],g[u+1]);return e.fragmentHint&&updateFromToPTS(g[g.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function mergeDetails(e,t){let r=null;const i=e.fragments;for(let l=i.length-1;l>=0;l--){const e=i[l].initSegment;if(e){r=e;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let s,n=0;if(mapFragmentIntersection(e,t,((e,i)=>{e.relurl&&(n=e.cc-i.cc),isFiniteNumber(e.startPTS)&&isFiniteNumber(e.endPTS)&&(i.start=i.startPTS=e.startPTS,i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.duration=e.endPTS-e.startPTS,i.duration&&(s=i),t.PTSKnown=t.alignedSliding=!0),i.elementaryStreams=e.elementaryStreams,i.loader=e.loader,i.stats=e.stats,e.initSegment&&(i.initSegment=e.initSegment,r=e.initSegment)})),r){(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach((e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=r)?void 0:t.relurl)||(e.initSegment=r)}))}if(t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some((e=>!e)),t.deltaUpdateFailed){logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=mergeDateRanges(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const a=t.fragments;if(n){logger.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<a.length;e++)a[e].cc+=n}t.skippedSegments&&(t.startCC=t.fragments[0].cc),mapPartIntersection(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?updateFragPTSDTS(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):adjustSliding(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const e=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=e),t.driftEndTime=o,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function mergeDateRanges(e,t,r){const i=_extends({},e);return r&&r.forEach((e=>{delete i[e]})),Object.keys(t).forEach((e=>{const r=new DateRange(t[e].attr,i[e]);r.isValid?i[e]=r:logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),i}function mapPartIntersection(e,t,r){if(e&&t){let i=0;for(let s=0,n=e.length;s<=n;s++){const n=e[s],a=t[s+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?r(n,a):i--}}}function mapFragmentIntersection(e,t,r){const i=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let d=s;d<=n;d++){const e=l[a+d];let s=o[d];i&&!s&&d<i&&(s=t.fragments[d]=e),e&&s&&r(e,s)}}function adjustSliding(e,t){const r=t.startSN+t.skippedSegments-e.startSN,i=e.fragments;r<0||r>=i.length||addSliding(t,i[r].start)}function addSliding(e,t){if(t){const r=e.fragments;for(let i=e.skippedSegments;i<r.length;i++)r[i].start+=t;e.fragmentHint&&(e.fragmentHint.start+=t)}}function computeReloadInterval(e,t=1/0){let r=1e3*e.targetduration;if(e.updated){const i=e.fragments,s=4;if(i.length&&r*s>t){const e=1e3*i[i.length-1].duration;e<r&&(r=e)}}else r/=2;return Math.round(r)}function getFragmentWithSN(e,t,r){if(null==e||!e.details)return null;const i=e.details;let s=i.fragments[t-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===t?s:t<i.startSN&&r&&r.sn===t?r:null)}function getPartWith(e,t,r){var i;return null!=e&&e.details?findPart(null==(i=e.details)?void 0:i.partList,t,r):null}function findPart(e,t,r){if(e)for(let i=e.length;i--;){const s=e[i];if(s.index===r&&s.fragment.sn===t)return s}return null}function reassignFragmentLevelIndexes(e){e.forEach(((e,t)=>{const{details:r}=e;null!=r&&r.fragments&&r.fragments.forEach((e=>{e.level=t}))}))}function isTimeoutError(e){switch(e.details){case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_TIMEOUT:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function getRetryConfig(e,t){const r=isTimeoutError(t);return e.default[(r?"timeout":"error")+"Retry"]}function getRetryDelay(e,t){const r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function getLoaderConfigWithoutReties(e){return _objectSpread2(_objectSpread2({},e),{errorRetry:null,timeoutRetry:null})}function shouldRetry(e,t,r,i){if(!e)return!1;const s=null==i?void 0:i.code,n=t<e.maxNumRetry&&(retryForHttpStatus(s)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,n):n}function retryForHttpStatus(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}const BinarySearch={search:function(e,t){let r=0,i=e.length-1,s=null,n=null;for(;r<=i;){s=(r+i)/2|0,n=e[s];const a=t(n);if(a>0)r=s+1;else{if(!(a<0))return n;i=s-1}}return null}};function findFragmentByPDT(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!isFiniteNumber(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;r=r||0;for(let i=0;i<e.length;++i){const s=e[i];if(pdtWithinToleranceTest(t,r,s))return s}return null}function findFragmentByPTS(e,t,r=0,i=0){let s=null;if(e){s=t[e.sn-t[0].sn+1]||null;const i=e.endDTS-r;i>0&&i<15e-7&&(r+=15e-7)}else 0===r&&0===t[0].start&&(s=t[0]);if(s&&(!e||e.level===s.level)&&0===fragmentWithinToleranceTest(r,i,s))return s;const n=BinarySearch.search(t,fragmentWithinToleranceTest.bind(null,r,i));return!n||n===e&&s?s:n}function fragmentWithinToleranceTest(e=0,t=0,r){if(r.start<=e&&r.start+r.duration>e)return 0;const i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function pdtWithinToleranceTest(e,t,r){const i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function findFragWithCC(e,t){return BinarySearch.search(e,(e=>e.cc<t?1:e.cc>t?-1:0))}var NetworkErrorAction={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ErrorActionFlags={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class ErrorController{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=logger.log.bind(logger,"[info]:"),this.warn=logger.warn.bind(logger,"[warning]:"),this.error=logger.error.bind(logger,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(Events.ERROR,this.onError,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Events.ERROR,this.onError,this),e.off(Events.ERROR,this.onErrorOut,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===PlaylistLevelType.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var r,i;if(t.fatal)return;const s=this.hls,n=t.context;switch(t.details){case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ErrorDetails.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction={action:NetworkErrorAction.DoNothing,flags:ErrorActionFlags.None});case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox);case ErrorDetails.LEVEL_EMPTY_ERROR:case ErrorDetails.LEVEL_PARSING_ERROR:{var a,o;const e=t.parent===PlaylistLevelType.MAIN?t.level:s.loadLevel;t.details===ErrorDetails.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(o=a.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.SUBTITLE_LOAD_ERROR:case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const e=s.levels[s.loadLevel];if(e&&(n.type===PlaylistContextType.AUDIO_TRACK&&e.hasAudioGroup(n.groupId)||n.type===PlaylistContextType.SUBTITLE_TRACK&&e.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox,void(t.errorAction.flags=ErrorActionFlags.MoveAllAlternatesMatchingHost)}return;case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.levels[s.loadLevel],r=null==e?void 0:e.attrs["HDCP-LEVEL"];r?t.errorAction={action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHDCP,hdcpLevel:r}:this.keySystemError(t)}return;case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.REMUX_ALLOC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(i=t.level)?i:s.loadLevel));case ErrorDetails.INTERNAL_EXCEPTION:case ErrorDetails.BUFFER_APPENDING_ERROR:case ErrorDetails.BUFFER_FULL_ERROR:case ErrorDetails.LEVEL_SWITCH_ERROR:case ErrorDetails.BUFFER_STALLED_ERROR:case ErrorDetails.BUFFER_SEEK_OVER_HOLE:case ErrorDetails.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:NetworkErrorAction.DoNothing,flags:ErrorActionFlags.None})}t.type===ErrorTypes.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const r=getRetryConfig(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(shouldRetry(r,i,isTimeoutError(e),e.response))return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,retryConfig:r,retryCount:i};const s=this.getLevelSwitchAction(e,t);return r&&(s.retryConfig=r,s.retryCount=i),s}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],{fragLoadPolicy:s,keyLoadPolicy:n}=t.config,a=getRetryConfig(e.details.startsWith("key")?n:s,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(i){e.details!==ErrorDetails.FRAG_GAP&&i.fragmentError++;if(shouldRetry(a,o,isTimeoutError(e),e.response))return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,r);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const r=this.hls;null==t&&(t=r.loadLevel);const i=this.hls.levels[t];if(i){var s,n;const t=e.details;i.loadError++,t===ErrorDetails.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:d,loadLevel:c,minAutoLevel:h,maxAutoLevel:u}=r;r.autoLevelEnabled||(r.loadLevel=-1);const f=null==(s=e.frag)?void 0:s.type,g=(f===PlaylistLevelType.AUDIO&&t===ErrorDetails.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===ErrorDetails.BUFFER_ADD_CODEC_ERROR||t===ErrorDetails.BUFFER_APPEND_ERROR))&&d.some((({audioCodec:e})=>i.audioCodec!==e)),m="video"===e.sourceBufferName&&(t===ErrorDetails.BUFFER_ADD_CODEC_ERROR||t===ErrorDetails.BUFFER_APPEND_ERROR)&&d.some((({codecSet:e,audioCodec:t})=>i.codecSet!==e&&i.audioCodec===t)),{type:p,groupId:y}=null!=(n=e.context)?n:{};for(let r=d.length;r--;){const s=(r+c)%d.length;if(s!==c&&s>=h&&s<=u&&0===d[s].loadError){var a,o;const r=d[s];if(t===ErrorDetails.FRAG_GAP&&e.frag){const t=d[s].details;if(t){const r=findFragmentByPTS(e.frag,t.fragments,e.frag.start);if(null!=r&&r.gap)continue}}else{if(p===PlaylistContextType.AUDIO_TRACK&&r.hasAudioGroup(y)||p===PlaylistContextType.SUBTITLE_TRACK&&r.hasSubtitleGroup(y))continue;if(f===PlaylistLevelType.AUDIO&&null!=(a=i.audioGroups)&&a.some((e=>r.hasAudioGroup(e)))||f===PlaylistLevelType.SUBTITLE&&null!=(o=i.subtitleGroups)&&o.some((e=>r.hasSubtitleGroup(e)))||g&&i.audioCodec===r.audioCodec||!g&&i.audioCodec!==r.audioCodec||m&&i.codecSet===r.codecSet)continue}l=s;break}}if(l>-1&&r.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.None,nextAutoLevel:l}}return{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case NetworkErrorAction.DoNothing:break;case NetworkErrorAction.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ErrorDetails.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,r=e.errorAction;if(!r)return;const{flags:i,hdcpLevel:s,nextAutoLevel:n}=r;switch(i){case ErrorActionFlags.None:this.switchLevel(e,n);break;case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:s&&(t.maxHdcpLevel=HdcpLevels[HdcpLevels.indexOf(s)-1],r.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}r.resolved||this.switchLevel(e,n)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}}class BasePlaylistController{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=logger.log.bind(logger,`${t}:`),this.warn=logger.warn.bind(logger,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t){const r=null==t?void 0:t.renditionReports;if(r){let s=-1;for(let n=0;n<r.length;n++){const a=r[n];let o;try{o=new self.URL(a.URI,t.url).href}catch(i){logger.warn(`Could not construct new URL for Rendition Report: ${i}`),o=a.URI||""}if(o===e){s=n;break}o===e.substring(0,o.length)&&(s=n)}if(-1!==s){const e=r[s],i=parseInt(e["LAST-MSN"])||(null==t?void 0:t.lastPartSn);let n=parseInt(e["LAST-PART"])||(null==t?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);n>=0&&e>t.partTarget&&(n+=1)}return new HlsUrlParameters(i,n>=0?n:void 0,HlsSkip.No)}}}loadPlaylist(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,r){const{details:i,stats:s}=t,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;if(i.advancedDateTime=Date.now()-a,i.live||null!=r&&r.live){if(i.reloaded(r),r&&this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),r&&i.fragments.length>0&&mergeDetails(r,i),!this.canLoad||!i.live)return;let a,o,l;if(i.canBlockReload&&i.endSN&&i.advanced){const e=this.hls.config.lowLatencyMode,s=i.lastPartSn,n=i.endSN,d=i.lastPartIndex,c=s===n,h=e?0:d;-1!==d?(o=c?n+1:s,l=c?h:d+1):o=n+1;const u=i.age,f=u+i.ageHeader;let g=Math.min(f-i.partTarget,1.5*i.targetduration);if(g>0){if(r&&g>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${g} with playlist age: ${i.age}`),g=0;else{const e=Math.floor(g/i.targetduration);if(o+=e,void 0!==l){l+=Math.round(g%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${g} skip sn ${e} to part ${l}`)}i.tuneInGoal=g}if(a=this.getDeliveryDirectives(i,t.deliveryDirectives,o,l),e||!c)return void this.loadPlaylist(a)}else(i.canBlockReload||i.canSkipUntil)&&(a=this.getDeliveryDirectives(i,t.deliveryDirectives,o,l));const d=this.hls.mainForwardBufferInfo,c=d?d.end-d.len:0,h=computeReloadInterval(i,1e3*(i.edge-c));i.updated&&n>this.requestScheduled+h&&(this.requestScheduled=s.loading.start),void 0!==o&&i.canBlockReload?this.requestScheduled=s.loading.first+h-(1e3*i.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+h<n?this.requestScheduled=n:this.requestScheduled-n<=0&&(this.requestScheduled+=h);let u=this.requestScheduled-n;u=Math.max(0,u),this.log(`reload live playlist ${e} in ${Math.round(u)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(a)),u)}else this.clearTimer()}getDeliveryDirectives(e,t,r,i){let s=getSkipValue(e,r);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,s=HlsSkip.No),new HlsUrlParameters(r,i,s)}checkRetry(e){const t=e.details,r=isTimeoutError(e),i=e.errorAction,{action:s,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(s===NetworkErrorAction.RetryRequest||!i.resolved&&s===NetworkErrorAction.SendAlternateToPenaltyBox);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(r&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=getRetryDelay(a,n);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,i.resolved=!0}return o}}class EWMA{constructor(e,t=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=r}sample(e,t){const r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class EwmaBandWidthEstimator{constructor(e,t,r,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_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new EWMA(e),this.fast_=new EWMA(t),this.defaultTTFB_=i,this.ttfb_=new EWMA(e)}update(e,t){const{slow_:r,fast_:i,ttfb_:s}=this;r.halfLife!==e&&(this.slow_=new EWMA(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new EWMA(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new EWMA(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){const r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)}sampleTTFB(e){const t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const SUPPORTED_INFO_DEFAULT={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},SUPPORTED_INFO_CACHE={};function requiresMediaCapabilitiesDecodingInfo(e,t,r,i,s,n){const a=e.audioCodec?e.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,d=l?parseInt(l):o?1/0:2;let c=null;if(null!=a&&a.length)try{c=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce(((e,r)=>{if(r){const i=t.groups[r];if(!i)throw new Error(`Audio track group ${r} not found`);Object.keys(i.channels).forEach((t=>{e[t]=(e[t]||0)+i.channels[t]}))}return e}),{2:0})}catch(h){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(s,8e6))||!!c&&isFiniteNumber(d)&&Object.keys(c).some((e=>parseInt(e)>d))}function getMediaDecodingInfoPromise(e,t,r){const i=e.videoCodec,s=e.audioCodec;if(!i||!s||!r)return Promise.resolve(SUPPORTED_INFO_DEFAULT);const n={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},a=e.videoRange;"SDR"!==a&&(n.transferFunction=a.toLowerCase());const o=i.split(",").map((e=>({type:"media-source",video:_objectSpread2(_objectSpread2({},n),{},{contentType:mimeTypeForCodec(e,"video")})})));return s&&e.audioGroups&&e.audioGroups.forEach((e=>{var r;e&&(null==(r=t.groups[e])||r.tracks.forEach((t=>{if(t.groupId===e){const e=t.channels||"",r=parseFloat(e);isFiniteNumber(r)&&r>2&&o.push.apply(o,s.split(",").map((e=>({type:"media-source",audio:{contentType:mimeTypeForCodec(e,"audio"),channels:""+r}}))))}})))})),Promise.all(o.map((e=>{const t=getMediaDecodingInfoKey(e);return SUPPORTED_INFO_CACHE[t]||(SUPPORTED_INFO_CACHE[t]=r.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:o,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:o,decodingInfoResults:[],error:e})))}function getMediaDecodingInfoKey(e){const{audio:t,video:r}=e,i=r||t;if(i){const e=i.contentType.split('"')[1];if(r)return`r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${e}_${Math.ceil(r.bitrate/1e5)}`;if(t)return`c${t.channels}${t.spatialRendering?"s":"n"}_${e}`}return""}function isHdrSupported(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}function getVideoSelectionOptions(e,t){let r=!1,i=[];return e&&(r="SDR"!==e,i=[e]),t&&(i=t.allowedVideoRanges||VideoRangeValues.slice(0),r=void 0!==t.preferHDR?t.preferHDR:isHdrSupported(),i=r?i.filter((e=>"SDR"!==e)):["SDR"]),{preferHDR:r,allowedVideoRanges:i}}function getStartCodecTier(e,t,r,i,s){const n=Object.keys(e),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=a&&2===parseInt(a);let d=!0,c=!1,h=1/0,u=1/0,f=1/0,g=0,m=[];const{preferHDR:p,allowedVideoRanges:y}=getVideoSelectionOptions(t,s);for(let T=n.length;T--;){const t=e[n[T]];d=t.channels[2]>0,h=Math.min(h,t.minHeight),u=Math.min(u,t.minFramerate),f=Math.min(f,t.minBitrate);const r=y.filter((e=>t.videoRanges[e]>0));r.length>0&&(c=!0,m=r)}h=isFiniteNumber(h)?h:0,u=isFiniteNumber(u)?u:0;const E=Math.max(1080,h),v=Math.max(30,u);f=isFiniteNumber(f)?f:r,r=Math.max(f,r),c||(t=void 0,m=[]);return{codecSet:n.reduce(((t,i)=>{const s=e[i];if(i===t)return t;if(s.minBitrate>r)return logStartCodecCandidateIgnored(i,`min bitrate of ${s.minBitrate} > current estimate of ${r}`),t;if(!s.hasDefaultAudio)return logStartCodecCandidateIgnored(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return logStartCodecCandidateIgnored(i,`audio codec preference "${o}" not found`),t;if(a&&!l){if(!s.channels[a])return logStartCodecCandidateIgnored(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(s.channels)})`),t}else if((!o||l)&&d&&0===s.channels[2])return logStartCodecCandidateIgnored(i,"no renditions with stereo sound found"),t;return s.minHeight>E?(logStartCodecCandidateIgnored(i,`min resolution of ${s.minHeight} > maximum of ${E}`),t):s.minFramerate>v?(logStartCodecCandidateIgnored(i,`min framerate of ${s.minFramerate} > maximum of ${v}`),t):m.some((e=>s.videoRanges[e]>0))?s.maxScore<g?(logStartCodecCandidateIgnored(i,`max score of ${s.maxScore} < selected max of ${g}`),t):t&&(codecsSetSelectionPreferenceValue(i)>=codecsSetSelectionPreferenceValue(t)||s.fragmentError>e[t].fragmentError)?t:(g=s.maxScore,i):(logStartCodecCandidateIgnored(i,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),t)}),void 0),videoRanges:m,preferHDR:p,minFramerate:u,minBitrate:f}}function logStartCodecCandidateIgnored(e,t){logger.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function getAudioTracksByGroup(e){return e.reduce(((e,t)=>{let r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);const i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function getCodecTiers(e,t,r,i){return e.slice(r,i+1).reduce(((e,r)=>{if(!r.codecSet)return e;const i=r.audioGroups;let s=e[r.codecSet];s||(e[r.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,r.bitrate);const n=Math.min(r.height,r.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,r.frameRate),s.maxScore=Math.max(s.maxScore,r.score),s.fragmentError+=r.fragmentError,s.videoRanges[r.videoRange]=(s.videoRanges[r.videoRange]||0)+1,i&&i.forEach((e=>{if(!e)return;const r=t.groups[e];s.hasDefaultAudio=s.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach((e=>{s.channels[e]=(s.channels[e]||0)+r.channels[e]}))})),e}),{})}function findMatchingOption(e,t,r){if("attrs"in e){const r=t.indexOf(e);if(-1!==r)return r}for(let i=0;i<t.length;i++){if(matchesOption(e,t[i],r))return i}return-1}function matchesOption(e,t,r){const{groupId:i,name:s,lang:n,assocLang:a,characteristics:o,default:l}=e,d=e.forced;return(void 0===i||t.groupId===i)&&(void 0===s||t.name===s)&&(void 0===n||t.lang===n)&&(void 0===n||t.assocLang===a)&&(void 0===l||t.default===l)&&(void 0===d||t.forced===d)&&(void 0===o||characteristicsMatch(o,t.characteristics))&&(void 0===r||r(e,t))}function characteristicsMatch(e,t=""){const r=e.split(","),i=t.split(",");return r.length===i.length&&!r.some((e=>-1===i.indexOf(e)))}function audioMatchPredicate(e,t){const{audioCodec:r,channels:i}=e;return!(void 0!==r&&(t.audioCodec||"").substring(0,4)!==r.substring(0,4)||void 0!==i&&i!==(t.channels||"2"))}function findClosestLevelWithAudioGroup(e,t,r,i,s){const n=t[i],a=t.reduce(((e,t,r)=>{const i=t.uri;return(e[i]||(e[i]=[])).push(r),e}),{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),c=searchDownAndUpList(t,i,(t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==d)return!1;const i=t.audioGroups,n=r.filter((e=>!i||-1!==i.indexOf(e.groupId)));return findMatchingOption(e,n,s)>-1}));return c>-1?c:searchDownAndUpList(t,i,(t=>{const i=t.audioGroups,n=r.filter((e=>!i||-1!==i.indexOf(e.groupId)));return findMatchingOption(e,n,s)>-1}))}function searchDownAndUpList(e,t,r){for(let i=t;i;i--)if(r(e[i]))return i;for(let i=t+1;i<e.length;i++)if(r(e[i]))return i;return-1}class AbrController{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:e,partCurrent:t,hls:r}=this,{autoLevelEnabled:i,media:s}=r;if(!e||!s)return;const n=performance.now(),a=t?t.stats:e.stats,o=t?t.duration:e.duration,l=n-a.loading.start,d=r.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||e.level<=d)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!i||s.paused||!s.playbackRate||!s.readyState)return;const c=r.mainForwardBufferInfo;if(null===c)return;const h=this.bwEstimator.getEstimateTTFB(),u=Math.abs(s.playbackRate);if(l<=Math.max(h,o/(2*u)*1e3))return;const f=c.len/u,g=a.loading.first?a.loading.first-a.loading.start:-1,m=a.loaded&&g>-1,p=this.getBwEstimate(),y=r.levels,E=y[e.level],v=a.total||Math.max(a.loaded,Math.round(o*E.averageBitrate/8));let T=m?l-g:l;T<1&&m&&(T=Math.min(l,8*a.loaded/p));const S=m?1e3*a.loaded/T:0,L=S?(v-a.loaded)/S:8*v/p+h/1e3;if(L<=f)return;const A=S?8*S:p;let b,R=Number.POSITIVE_INFINITY;for(b=e.level-1;b>d;b--){const e=y[b].maxBitrate;if(R=this.getTimeToLoadFrag(h/1e3,A,o*e,!y[b].details),R<f)break}if(R>=L)return;if(R>10*o)return;r.nextLoadLevel=r.nextAutoLevel=b,m?this.bwEstimator.sample(l-Math.min(h,g),a.loaded):this.bwEstimator.sampleTTFB(l);const C=y[b].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>C&&this.resetEstimator(C),this.clearTimer(),logger.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${L.toFixed(3)} s\n Estimated load time for down switch fragment: ${R.toFixed(3)} s\n TTFB estimate: ${0|g} ms\n Current BW estimate: ${isFiniteNumber(p)?0|p:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${b} @ ${0|C} bps`),r.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:a})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(logger.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new EwmaBandWidthEstimator(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Events.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const r=t.frag;if(!this.ignoreFragment(r)){var i;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ErrorDetails.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:r,partCurrent:i}=this;if(e&&r&&e.sn===r.sn&&e.level===r.level){const t=performance.now(),r=i?i.stats:e.stats,s=t-r.loading.start,n=r.loading.first?r.loading.first-r.loading.start:-1;if(r.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(e,n),r.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(e,t,r,i){return e+r/t+(i?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const r=this.hls.config,{loading:i}=t.stats,s=i.end-i.start;isFiniteNumber(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:r}){const i=r?r.stats:t.stats;if(t.type===PlaylistLevelType.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=r?r.duration:t.duration,s=this.hls.levels[t.level],n=(s.loaded?s.loaded.bytes:0)+i.loaded,a=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:i,frag:t,part:r,id:t.type};this.onFragBuffered(Events.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:r,part:i}=t,s=null!=i&&i.stats.loaded?i.stats:r.stats;if(s.aborted)return;if(this.ignoreFragment(r))return;const n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==PlaylistLevelType.MAIN||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,r=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,s=this.findBestLevel(r,t,e,0,i,1,1);if(s>-1)return s;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return logger.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,i)&&t[e].loadError<=t[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:r}=this,{maxAutoLevel:i,config:s,minAutoLevel:n}=r,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=s.abrBandWidthFactor,c=s.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,i,l,0,d,c);if(e>=0)return e}let h=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){h=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-e,logger.info(`[abr] bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),d=c=1}}const u=this.findBestLevel(o,n,i,l,h,d,c);if(logger.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`),u>-1)return u;const f=r.levels[n],g=r.levels[r.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:r.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,r,i,s,n,a){var o;const l=i+s,d=this.lastLoadedFragLevel,c=-1===d?this.hls.firstLevel:d,{fragCurrent:h,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const y=f[c],E=!(null==y||null==(o=y.details)||!o.live),v=-1===m||-1===d;let T,S="SDR",L=(null==y?void 0:y.frameRate)||0;const{audioPreference:A,videoPreference:b}=p,R=this.audioTracksByGroup||(this.audioTracksByGroup=getAudioTracksByGroup(g));if(v){if(-1!==this.firstSelection)return this.firstSelection;const i=getStartCodecTier(this.codecTiers||(this.codecTiers=getCodecTiers(f,R,t,r)),S,e,A,b),{codecSet:s,videoRanges:n,minFramerate:a,minBitrate:o,preferHDR:l}=i;T=s,S=l?n[n.length-1]:n[0],L=a,e=Math.max(e,o),logger.log(`[abr] picked start tier ${JSON.stringify(i)}`)}else T=null==y?void 0:y.codecSet,S=null==y?void 0:y.videoRange;const C=u?u.duration:h?h.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,_=[];for(let P=r;P>=t;P--){var I;const t=f[P],o=P>c;if(!t)continue;if(p.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const r=navigator.mediaCapabilities;"function"==typeof(null==r?void 0:r.decodingInfo)&&requiresMediaCapabilitiesDecodingInfo(t,R,S,L,e,A)?(t.supportedPromise=getMediaDecodingInfoPromise(t,R,r),t.supportedPromise.then((e=>{if(!this.hls)return;t.supportedResult=e;const r=this.hls.levels,i=r.indexOf(t);e.error?logger.warn(`[abr] MediaCapabilities decodingInfo error: "${e.error}" for level ${i} ${JSON.stringify(e)}`):e.supported||(logger.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${i} ${JSON.stringify(e)}`),i>-1&&r.length>1&&(logger.log(`[abr] Removing unsupported level ${i}`),this.hls.removeLevel(i)))}))):t.supportedResult=SUPPORTED_INFO_DEFAULT}if(T&&t.codecSet!==T||S&&t.videoRange!==S||o&&L>t.frameRate||!o&&L>0&&L<t.frameRate||t.supportedResult&&(null==(I=t.supportedResult.decodingInfoResults)||!I[0].smooth)){_.push(P);continue}const h=t.details,g=(u?null==h?void 0:h.partTarget:null==h?void 0:h.averagetargetduration)||C;let b;b=o?a*e:n*e;const k=C&&i>=2*C&&0===s?f[P].averageBitrate:f[P].maxBitrate,w=this.getTimeToLoadFrag(D,b,k*g,void 0===h);if(b>=k&&(P===d||0===t.loadError&&0===t.fragmentError)&&(w<=D||!isFiniteNumber(w)||E&&!this.bitrateTestDelay||w<l)){const e=this.forcedAutoLevel;return P===m||-1!==e&&e===m||(_.length&&logger.trace(`[abr] Skipped level(s) ${_.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${f[_[0]].codecs}" ${f[_[0]].videoRange}; not compatible with "${y.codecs}" ${S}`),logger.info(`[abr] switch candidate:${c}->${P} adjustedbw(${Math.round(b)})-bitrate=${Math.round(b-k)} ttfb:${D.toFixed(1)} avgDuration:${g.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${w.toFixed(1)} firstSelection:${v} codecSet:${T} videoRange:${S} hls.loadLevel:${m}`)),v&&(this.firstSelection=P),P}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:r}=this.hls,i=Math.min(Math.max(e,r),t);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i)}}class TaskLoop{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var FragmentState={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class FragmentTracker{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const r=this.activePartLists[t];if(r)for(let i=r.length;i--;){const t=r[i];if(!t)break;const s=t.end;if(t.start<=e&&null!==s&&e<=s)return t}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:r}=this,i=Object.keys(r);for(let s=i.length;s--;){const n=r[i[s]];if((null==n?void 0:n.body.type)===t&&n.buffered){const t=n.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,r,i){this.timeRanges&&(this.timeRanges[e]=t);const s=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((i=>{const n=this.fragments[i];if(!n)return;if(s>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===r&&this.removeFragment(n.body));const a=n.range[e];a&&a.time.some((e=>{const r=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&this.removeFragment(n.body),r}))}))}detectPartialFragments(e){const t=this.timeRanges,{frag:r,part:i}=e;if(!t||"initSegment"===r.sn)return;const s=getFragmentKey(r),n=this.fragments[s];if(!n||n.buffered&&r.gap)return;const a=!r.relurl;if(Object.keys(t).forEach((e=>{const s=r.elementaryStreams[e];if(!s)return;const o=t[e],l=a||!0===s.partial;n.range[e]=this.getBufferedTimes(r,i,l,o)})),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=r.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),isPartial(n)||this.removeParts(r.sn-1,r.type)}else this.removeFragment(n.body)}removeParts(e,t){const r=this.activePartLists[t];r&&(this.activePartLists[t]=r.filter((t=>t.fragment.sn>=e)))}fragBuffered(e,t){const r=getFragmentKey(e);let i=this.fragments[r];!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(e,t,r,i){const s={time:[],partial:r},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let d=0;d<i.length;d++){const e=i.start(d)-this.bufferPadding,t=i.end(d)+this.bufferPadding;if(l>=e&&o<=t){s.time.push({startPTS:Math.max(n,i.start(d)),endPTS:Math.min(a,i.end(d))});break}if(n<t&&a>e){const e=Math.max(n,i.start(d)),t=Math.min(a,i.end(d));t>e&&(s.partial=!0,s.time.push({startPTS:e,endPTS:t}))}else if(a<=e)break}return s}getPartialFragment(e){let t,r,i,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const d=o[l];d&&isPartial(d)&&(r=d.body.start-a,i=d.body.end+a,e>=r&&e<=i&&(t=Math.min(e-r,i-e),n<=t&&(s=d.body,n=t)))})),s}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||isPartial(t))}getState(e){const t=getFragmentKey(e),r=this.fragments[t];return r?r.buffered?isPartial(r)?FragmentState.PARTIAL:FragmentState.OK:FragmentState.APPENDING:FragmentState.NOT_LOADED}isTimeBuffered(e,t,r){let i,s;for(let n=0;n<r.length;n++){if(i=r.start(n)-this.bufferPadding,s=r.end(n)+this.bufferPadding,e>=i&&t<=s)return!0;if(t<=i)return!1}return!1}onFragLoaded(e,t){const{frag:r,part:i}=t;if("initSegment"===r.sn||r.bitrateTest)return;const s=i?null:t,n=getFragmentKey(r);this.fragments[n]={body:r,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:i,timeRanges:s}=t;if("initSegment"===r.sn)return;const n=r.type;if(i){let e=this.activePartLists[n];e||(this.activePartLists[n]=e=[]),e.push(i)}this.timeRanges=s,Object.keys(s).forEach((e=>{const t=s[e];this.detectEvictedFragments(e,t,n,i)}))}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=getFragmentKey(e);return!!this.fragments[t]}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,r,i,s){i&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==r||i&&!o.gap||o.start<t&&o.end>e&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(e){const t=getFragmentKey(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const t=e.sn;this.activePartLists[e.type]=r.filter((e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function isPartial(e){var t,r,i;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(r=e.range.audio)?void 0:r.partial)||(null==(i=e.range.audiovideo)?void 0:i.partial))}function getFragmentKey(e){return`${e.type}_${e.level}_${e.sn}`}const noopBuffered={length:0,start:()=>0,end:()=>0};class BufferHelper{static isBuffered(e,t){try{if(e){const r=BufferHelper.getBuffered(e);for(let e=0;e<r.length;e++)if(t>=r.start(e)&&t<=r.end(e))return!0}}catch(r){}return!1}static bufferInfo(e,t,r){try{if(e){const i=BufferHelper.getBuffered(e),s=[];let n;for(n=0;n<i.length;n++)s.push({start:i.start(n),end:i.end(n)});return this.bufferedInfo(s,t,r)}}catch(i){}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,r){t=Math.max(0,t),e.sort((function(e,t){const r=e.start-t.start;return r||t.end-e.end}));let i=[];if(r)for(let l=0;l<e.length;l++){const t=i.length;if(t){const s=i[t-1].end;e[l].start-s<r?e[l].end>s&&(i[t-1].end=e[l].end):i.push(e[l])}else i.push(e[l])}else i=e;let s,n=0,a=t,o=t;for(let l=0;l<i.length;l++){const e=i[l].start,d=i[l].end;if(t+r>=e&&t<d)a=e,o=d,n=o-t;else if(t+r<e){s=e;break}}return{len:n,start:a||0,end:o||0,nextStart:s}}static getBuffered(e){try{return e.buffered}catch(t){return logger.log("failed to get media.buffered",t),noopBuffered}}}class ChunkMetadata{constructor(e,t,r,i=0,s=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=getNewPerformanceTiming(),this.buffering={audio:getNewPerformanceTiming(),video:getNewPerformanceTiming(),audiovideo:getNewPerformanceTiming()},this.level=e,this.sn=t,this.id=r,this.size=i,this.part=s,this.partial=n}}function getNewPerformanceTiming(){return{start:0,executeStart:0,executeEnd:0,end:0}}function findFirstFragWithCC(e,t){for(let i=0,s=e.length;i<s;i++){var r;if((null==(r=e[i])?void 0:r.cc)===t)return e[i]}return null}function shouldAlignOnDiscontinuities(e,t,r){return!(!t||!(r.endCC>r.startCC||e&&e.cc<r.startCC))}function findDiscontinuousReferenceFrag(e,t){const r=e.fragments,i=t.fragments;if(!i.length||!r.length)return void logger.log("No fragments to align");const s=findFirstFragWithCC(r,i[0].cc);if(s&&(!s||s.startPTS))return s;logger.log("No frag in previous level to align on")}function adjustFragmentStart(e,t){if(e){const r=e.start+t;e.start=e.startPTS=r,e.endPTS=r+e.duration}}function adjustSlidingStart(e,t){const r=t.fragments;for(let i=0,s=r.length;i<s;i++)adjustFragmentStart(r[i],e);t.fragmentHint&&adjustFragmentStart(t.fragmentHint,e),t.alignedSliding=!0}function alignStream(e,t,r){t&&(alignDiscontinuities(e,r,t),!r.alignedSliding&&t&&alignMediaPlaylistByPDT(r,t),r.alignedSliding||!t||r.skippedSegments||adjustSliding(t,r))}function alignDiscontinuities(e,t,r){if(shouldAlignOnDiscontinuities(e,r,t)){const e=findDiscontinuousReferenceFrag(r,t);e&&isFiniteNumber(e.start)&&(logger.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),adjustSlidingStart(e.start,t))}}function alignMediaPlaylistByPDT(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const r=e.fragments,i=t.fragments;if(!r.length||!i.length)return;let s,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(s=findFirstFragWithCC(i,a),n=findFirstFragWithCC(r,a)),s&&n||(s=i[Math.floor(i.length/2)],n=findFirstFragWithCC(r,s.cc)||r[Math.floor(r.length/2)]);const o=s.programDateTime,l=n.programDateTime;if(!o||!l)return;adjustSlidingStart((l-o)/1e3-(n.start-s.start),e)}const MIN_CHUNK_SIZE=Math.pow(2,17);class FragmentLoader{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const r=e.url;if(!r)return Promise.reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,s=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(createGapLoadError(e));e.gap=!1}const l=this.loader=e.loader=s?new s(i):new n(i),d=createLoaderContext(e),c=getLoaderConfigWithoutReties(i.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:MIN_CHUNK_SIZE};e.stats=l.stats,l.load(d,h,{onSuccess:(t,r,i,s)=>{this.resetLoader(e,l);let n=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:s})},onError:(t,i,s,n)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:_objectSpread2({url:r,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:n}))},onAbort:(t,r,i)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:(t,r,i)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:i,stats:t}))},onProgress:(r,i,s,n)=>{t&&t({frag:e,part:null,payload:s,networkDetails:n})}})}))}loadPart(e,t,r){this.abort();const i=this.config,s=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(createGapLoadError(e,t));const l=this.loader=e.loader=s?new s(i):new n(i),d=createLoaderContext(e,t),c=getLoaderConfigWithoutReties(i.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:MIN_CHUNK_SIZE};t.stats=l.stats,l.load(d,h,{onSuccess:(i,s,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const d={frag:e,part:t,payload:i.data,networkDetails:o};r(d),a(d)},onError:(r,i,s,n)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:_objectSpread2({url:d.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:s,stats:n}))},onAbort:(r,i,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:r}))},onTimeout:(r,i,s)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:s,stats:r}))}})}))}updateStatsFromPart(e,t){const r=e.stats,i=t.stats,s=i.total;if(r.loaded+=i.loaded,s){const i=Math.round(e.duration/t.duration),n=Math.min(Math.round(r.loaded/s),i),a=(i-n)*Math.round(r.loaded/n);r.total=r.loaded+a}else r.total=Math.max(r.loaded,r.total);const n=r.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(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function createLoaderContext(e,t=null){const r=t||e,i={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},s=r.byteRangeStartOffset,n=r.byteRangeEndOffset;if(isFiniteNumber(s)&&isFiniteNumber(n)){var a;let t=s,r=n;if("initSegment"===e.sn&&"AES-128"===(null==(a=e.decryptdata)?void 0:a.method)){const e=n-s;e%16&&(r=n+(16-e%16)),0!==s&&(i.resetIV=!0,t=s-16)}i.rangeStart=t,i.rangeEnd=r}return i}function createGapLoadError(e,t){const r=new Error(`GAP ${e.gap?"tag":"attribute"} found`),i={type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new LoadError(i)}class LoadError extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class AESCrypto{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class FastAESKey{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function removePadding(e){const t=e.byteLength,r=t&&new DataView(e.buffer).getUint8(t-1);return r?sliceUint8(e,0,t-r):e}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_(e){const t=new DataView(e),r=new Uint32Array(4);for(let i=0;i<4;i++)r[i]=t.getUint32(4*i);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],s=r[1],n=r[2],a=r[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,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let r=g^g<<1^g<<2^g<<3^g<<4;r=r>>>8^255&r^99,e[f]=r,t[r]=f;const o=u[f],m=u[o],p=u[m];let y=257*u[r]^16843008*r;i[f]=y<<24|y>>>8,s[f]=y<<16|y>>>16,n[f]=y<<8|y>>>24,a[f]=y,y=16843009*p^65537*m^257*o^16843008*f,l[r]=y<<24|y>>>8,d[r]=y<<16|y>>>16,c[r]=y<<8|y>>>24,h[r]=y,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let r=!0,i=0;for(;i<t.length&&r;)r=t[i]===this.key[i],i++;if(r)return;this.key=t;const s=this.keySize=t.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const n=this.ksRows=4*(s+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],m=u[2],p=u[3];let y,E;for(a=0;a<n;a++)a<s?y=l[a]=t[a]:(E=y,a%s==0?(E=E<<8|E>>>24,E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[255&E],E^=h[a/s|0]<<24):s>6&&a%s==4&&(E=c[E>>>24]<<24|c[E>>>16&255]<<16|c[E>>>8&255]<<8|c[255&E]),l[a]=y=(l[a-s]^E)>>>0);for(o=0;o<n;o++)a=n-o,E=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?E:f[c[E>>>24]]^g[c[E>>>16&255]]^m[c[E>>>8&255]]^p[c[255&E]],d[o]=d[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,r){const i=this.keySize+6,s=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],c=a[3],h=this.uint8ArrayToUint32Array_(r);let u=h[0],f=h[1],g=h[2],m=h[3];const p=new Int32Array(e),y=new Int32Array(p.length);let E,v,T,S,L,A,b,R,C,D,_,I,P,k;const w=this.networkToHostOrderSwap;for(;t<p.length;){for(C=w(p[t]),D=w(p[t+1]),_=w(p[t+2]),I=w(p[t+3]),L=C^s[0],A=I^s[1],b=_^s[2],R=D^s[3],P=4,k=1;k<i;k++)E=o[L>>>24]^l[A>>16&255]^d[b>>8&255]^c[255&R]^s[P],v=o[A>>>24]^l[b>>16&255]^d[R>>8&255]^c[255&L]^s[P+1],T=o[b>>>24]^l[R>>16&255]^d[L>>8&255]^c[255&A]^s[P+2],S=o[R>>>24]^l[L>>16&255]^d[A>>8&255]^c[255&b]^s[P+3],L=E,A=v,b=T,R=S,P+=4;E=n[L>>>24]<<24^n[A>>16&255]<<16^n[b>>8&255]<<8^n[255&R]^s[P],v=n[A>>>24]<<24^n[b>>16&255]<<16^n[R>>8&255]<<8^n[255&L]^s[P+1],T=n[b>>>24]<<24^n[R>>16&255]<<16^n[L>>8&255]<<8^n[255&A]^s[P+2],S=n[R>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[255&b]^s[P+3],y[t]=w(E^u),y[t+1]=w(S^f),y[t+2]=w(T^g),y[t+3]=w(v^m),u=C,f=D,g=_,m=I,t+=4}return y.buffer}}const CHUNK_SIZE=16;class Decrypter{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(r){}null===this.subtle&&(this.useSoftware=!0)}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?removePadding(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,r){return this.useSoftware?new Promise(((i,s)=>{this.softwareDecrypt(new Uint8Array(e),t,r);const n=this.flush();n?i(n.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,r)}softwareDecrypt(e,t,r){const{currentIV:i,currentResult:s,remainderData:n}=this;this.logOnce("JS AES decrypt"),n&&(e=appendUint8Array(n,e),this.remainderData=null);const a=this.getValidChunk(e);if(!a.length)return null;i&&(r=i);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new AESDecryptor),o.expandKey(t);const l=s;return this.currentResult=o.decrypt(a.buffer,0,r),this.currentIV=sliceUint8(a,-16).buffer,l||null}webCryptoDecrypt(e,t,r){const i=this.subtle;return this.key===t&&this.fastAesKey||(this.key=t,this.fastAesKey=new FastAESKey(i,t)),this.fastAesKey.expandKey().then((t=>{if(!i)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new AESCrypto(i,new Uint8Array(r)).decrypt(e.buffer,t)})).catch((i=>(logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,r))))}onWebCryptoError(e,t,r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const r=e.length-e.length%CHUNK_SIZE;return r!==e.length&&(t=sliceUint8(e,0,r),this.remainderData=sliceUint8(e,r)),t}logOnce(e){this.logEnabled&&(logger.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const TimeRanges={toString:function(e){let t="";const r=e.length;for(let i=0;i<r;i++)t+=`[${e.start(i).toFixed(3)}-${e.end(i).toFixed(3)}]`;return t}},State={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class BaseStreamController extends TaskLoop{constructor(e,t,r,i,s){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=State.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=s,this.logPrefix=i,this.log=logger.log.bind(logger,`${i}:`),this.warn=logger.warn.bind(logger,`${i}:`),this.hls=e,this.fragmentLoader=new FragmentLoader(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Decrypter(e.config),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=State.STOPPED}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const r=t.partList;if(null!=r&&r.length){const e=r[r.length-1];return BufferHelper.isBuffered(this.media,e.start+e.duration/2)}const i=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(i)}getLevelDetails(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levelLastLoaded)?void 0:e.details}onMediaAttached(e,t){const r=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),r.addEventListener("seeking",this.onvseeking),r.addEventListener("ended",this.onvended);const i=this.config;this.levels&&i.autoStartLoad&&this.state===State.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(){const e=this.media;null!=e&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:r,mediaBuffer:i,state:s}=this,n=r?r.currentTime:0,a=BufferHelper.bufferInfo(i||r,n,e.maxBufferHole);if(this.log(`media seeking to ${isFiniteNumber(n)?n.toFixed(3):n}, state: ${s}`),this.state===State.ENDED)this.resetLoadingState();else if(t){const r=e.maxFragLookUpTolerance,i=t.start-r,s=t.start+t.duration+r;if(!a.len||s<a.start||i>a.end){const e=n>s;(n<i||e)&&(e&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}r&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),this.lastCurrentTime=n),this.loadedmetadata||a.len||(this.nextLoadPosition=this.startPosition=n),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=State.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,r){this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){this._doFragLoad(e,t,r,(t=>{if(this.fragContextChanged(e))return this.warn(`Fragment ${e.sn}${t.part?" p: "+t.part.index:""} of level ${e.level} was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const r=this.state;this.fragContextChanged(e)?(r===State.FRAG_LOADING||!this.fragCurrent&&r===State.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=State.IDLE):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(Events.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state!==State.STOPPED&&this.state!==State.ERROR&&(this.warn(t),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===FragmentState.APPENDING){const t=e.type,i=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,i?i.len:this.config.maxBufferLength);this.reduceMaxBufferLength(s)&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===FragmentState.PARTIAL&&r.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,r=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:r};this.hls.trigger(Events.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((t=>{if(!t||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:r}=this,{payload:i}=t,s=e.decryptdata;if(i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&"AES-128"===s.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer).catch((t=>{throw r.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((i=>{const s=self.performance.now();return r.trigger(Events.FRAG_DECRYPTED,{frag:e,payload:i,stats:{tstart:n,tdecrypt:s}}),t.payload=i,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)})).catch((t=>{this.state!==State.STOPPED&&this.state!==State.ERROR&&(this.warn(t),this.resetFragmentLoading(e))}))}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const r=e.frag.stats;this.state=State.IDLE,e.frag.data=new Uint8Array(e.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var r,i,s,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===PlaylistLevelType.MAIN?"level":"track"} ${e.level} (frag:[${(null!=(r=e.startPTS)?r:NaN).toFixed(3)}-${(null!=(i=e.endPTS)?i:NaN).toFixed(3)}] > buffer:${a?TimeRanges.toString(BufferHelper.getBuffered(a)):"(detached)"})`),"initSegment"!==e.sn){var o;if(e.type!==PlaylistLevelType.SUBTITLE){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return void(this.state=State.IDLE)}const t=null==(o=this.levels)?void 0:o[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=State.IDLE,a&&(!this.loadedmetadata&&e.type==PlaylistLevelType.MAIN&&a.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:r,part:i,partsLoaded:s}=e,n=!s||0===s.length||s.some((e=>!e)),a=new ChunkMetadata(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=null,i){var s;const n=null==t?void 0:t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${e.level}`),this.state=State.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Events.KEY_LOADED,e),this.state===State.KEY_LOADING&&(this.state=State.IDLE),e})),this.hls.trigger(Events.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),r=Math.max(e.start,r||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){const s=n.partList;if(s&&i){r>e.end&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(s,e,r);if(o>-1){const l=s[o];let d;return this.log(`Loading part sn: ${e.sn} p: ${l.index} cc: ${e.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=State.FRAG_LOADING,d=a?a.then((r=>!r||this.fragContextChanged(r.frag)?null:this.doFragPartsLoad(e,l,t,i))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,i).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Events.FRAG_LOADING,{frag:e,part:l,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!e.url||this.loadedEndOfParts(s,r))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(r.toFixed(3))}`),isFiniteNumber(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=State.FRAG_LOADING;const o=this.config.progressive;let l;return l=o&&a?a.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,i))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,o?i:void 0),a]).then((([e])=>(!o&&e&&i&&i(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Events.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(e,t,r,i){return new Promise(((s,n)=>{var a;const o=[],l=null==(a=r.details)?void 0:a.partList,d=t=>{this.fragmentLoader.loadPart(e,t,i).then((i=>{o[t.index]=i;const n=i.part;this.hls.trigger(Events.FRAG_LOADED,i);const a=getPartWith(r,e.sn,t.index+1)||findPart(l,e.sn,t.index+1);if(!a)return s({frag:e,part:n,partsLoaded:o});d(a)})).catch(n)};d(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===ErrorDetails.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(Events.ERROR,t)}else this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==State.PARSING)return void(this.fragCurrent||this.state===State.STOPPED||this.state===State.ERROR||(this.state=State.IDLE));const{frag:r,part:i,level:s}=t,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(r,i,s,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:r}=this,{level:i,sn:s,part:n}=e;if(null==t||!t[i])return this.warn(`Levels object was unset while buffering fragment ${s} of level ${i}. The current chunk will not be buffered.`),null;const a=t[i],o=n>-1?getPartWith(a,s,n):null,l=o?o.fragment:getFragmentWithSN(a,s,r);return l?(r&&r!==l&&(l.stats=r.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(e,t,r,i,s){var n;if(!e||this.state!==State.PARSING)return;const{data1:a,data2:o}=e;let l=a;if(a&&o&&(l=appendUint8Array(a,o)),null==(n=l)||!n.length)return;const d={type:e.type,frag:t,part:r,chunkMeta:i,parent:t.type,data:l};if(this.hls.trigger(Events.BUFFER_APPENDING,d),e.dropped&&e.independent&&!r){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!BufferHelper.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const r=t.currentTime,i=BufferHelper.bufferInfo(t,r,0),s=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-n,i.end-n),r+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){const r=this.getLoadPosition();return isFiniteNumber(r)?this.getFwdBufferInfoAtPos(e,r,t):null}getFwdBufferInfoAtPos(e,t,r){const{config:{maxBufferHole:i}}=this,s=BufferHelper.bufferInfo(e,t,i);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,r);if(n&&s.nextStart<n.end)return BufferHelper.bufferInfo(e,t,Math.max(s.nextStart,i))}return s}getMaxBufferLength(e){const{config:t}=this;let r;return r=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}reduceMaxBufferLength(e){const t=this.config,r=e||t.maxBufferLength;return t.maxMaxBufferLength>=r&&(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0)}getAppendedFrag(e,t=PlaylistLevelType.MAIN){const r=this.fragmentTracker.getAppendedFrag(e,PlaylistLevelType.MAIN);return r&&"fragment"in r?r.fragment:r}getNextFragment(e,t){const r=t.fragments,i=r.length;if(!i)return null;const{config:s}=this,n=r[0].start;let a;if(t.live){const o=s.initialLiveManifestSize;if(i<o)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${o})`),null;(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n)&&(a=this.getInitialLiveFragment(t,r),this.startPosition=this.nextLoadPosition=a?this.hls.liveSyncPosition||a.start:e)}else e<=n&&(a=r[0]);if(!a){const r=s.lowLatencyMode?t.partEnd:t.fragmentEnd;a=this.getFragmentAtPosition(e,r,t)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===FragmentState.OK||r===FragmentState.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,i,s){const n=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(null===a)return a;if(e=a,n&&e&&!e.gap&&r.nextStart){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i);if(null!==t&&r.len+t.len>=s)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,r){let i=-1,s=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,i>-1&&r<o.start)break;const l=o.loaded;l?i=-1:(s||o.independent||n)&&o.fragment===t&&(i=a),s=l}return i}loadedEndOfParts(e,t){const r=e[e.length-1];return r&&t>r.start&&r.loaded}getInitialLiveFragment(e,t){const r=this.fragPrevious;let i=null;if(r){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),i=findFragmentByPDT(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){const n=t[s-e.startSN];r.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=findFragWithCC(t,r.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(i=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,r){const{config:i}=this;let{fragPrevious:s}=this,{fragments:n,endSN:a}=r;const{fragmentHint:o}=r,l=i.maxFragLookUpTolerance,d=r.partList,c=!!(i.lowLatencyMode&&null!=d&&d.length&&o);let h;if(c&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),e<t){h=findFragmentByPTS(s,n,e,e>t-l?0:l)}else h=n[n.length-1];if(h){const e=h.sn-r.startSN,t=this.fragmentTracker.getState(h);if((t===FragmentState.OK||t===FragmentState.PARTIAL&&h.gap)&&(s=h),s&&h.sn===s.sn&&(!c||d[0].fragment.sn>h.sn)){if(s&&h.level===s.level){const t=n[e+1];h=h.sn<a&&this.fragmentTracker.getState(t)!==FragmentState.OK?t:null}}}return h}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const i=this.hls.liveSyncPosition,s=r.currentTime,n=e.fragments[0].start,a=e.edge,o=s>=n-t.maxFragLookUpTolerance&&s<=a;if(null!==i&&r.duration>i&&(s<i||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&r.readyState<4||s<a-n)&&(this.loadedmetadata||(this.nextLoadPosition=i),r.readyState&&(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),r.currentTime=i))}}alignPlaylists(e,t,r){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const s=e.fragments[0].start,n=!t,a=e.alignedSliding&&isFiniteNumber(s);if(n||!a&&!s){const{fragPrevious:s}=this;alignStream(s,r,e);const n=e.fragments[0].start;return this.log(`Live playlist sliding: ${n.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${s?s.sn:"na"} fragments: ${i}`),n}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let r=this.startPosition;if(r<t&&(r=-1),-1===r||-1===this.lastCurrentTime){const i=null!==this.startTimeOffset,s=i?this.startTimeOffset:e.startTimeOffset;null!==s&&isFiniteNumber(s)?(r=t+s,s<0&&(r+=e.totalduration),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Start time offset ${s} found in ${i?"multivariant":"media"} playlist, adjust startPosition to ${r}`),this.startPosition=r):e.live?r=this.hls.liveSyncPosition||t:this.startPosition=r=0,this.lastCurrentTime=r}this.nextLoadPosition=r}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&"initSegment"!==e.sn&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===State.FRAG_LOADING_WAITING_RETRY)||(this.state=State.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const r=t.frag;if(!r||r.type!==e||!this.levels)return;var i;if(this.fragContextChanged(r))return void this.warn(`Frag load error must match current frag to retry ${r.url} > ${null==(i=this.fragCurrent)?void 0:i.url}`);const s=t.details===ErrorDetails.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(r,!0);const n=t.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===NetworkErrorAction.RetryRequest&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const i=getRetryDelay(l,o);this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${i}ms`),n.resolved=!0,this.retryDate=self.performance.now()+i,this.state=State.FRAG_LOADING_WAITING_RETRY}else if(l&&n){if(this.resetFragmentErrors(e),!(o<l.maxNumRetry))return void logger.warn(`${t.details} reached or exceeded max retry (${o})`);s||a===NetworkErrorAction.RemoveAlternatePermanently||(n.resolved=!0)}else(null==n?void 0:n.action)===NetworkErrorAction.SendAlternateToPenaltyBox?this.state=State.WAITING_LEVEL:this.state=State.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===State.PARSING||this.state===State.PARSED){const t=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,t),i=r&&r.len>.5;i&&this.reduceMaxBufferLength(r.len);const s=!i;return s&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(e){e===PlaylistLevelType.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==State.STOPPED&&(this.state=State.IDLE)}afterBufferFlushed(e,t,r){if(!e)return;const i=BufferHelper.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,r),this.state===State.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=State.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,r,i){var s;const n=r.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce(((t,s)=>{const a=e.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${o})`),t||!1;const l=i?0:updateFragPTSDTS(n,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(Events.LEVEL_PTS_UPDATED,{details:n,level:r,drift:l,type:s,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1)&&null===(null==(s=this.transmuxer)?void 0:s.error)){const t=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===r.fragmentError&&(r.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(t.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of level "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=State.PARSED,this.hls.trigger(Events.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class ChunkCache{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let r;return e.length?(r=1===e.length?e[0]:concatUint8Arrays(e,t),this.reset(),r):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function concatUint8Arrays(e,t){const r=new Uint8Array(t);let i=0;for(let s=0;s<e.length;s++){const t=e[s];r.set(t,i),i+=t.length}return r}function hasUMDWorker(){return"function"==typeof __HLS_WORKER_BUNDLE__}function injectWorker(){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"}),t=self.URL.createObjectURL(e);return{worker:new self.Worker(t),objectURL:t}}function loadWorker(e){const t=new self.URL(e,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}function dummyTrack(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,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(e,t,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,r){}demux(e,t){this.cachedData&&(e=appendUint8Array(this.cachedData,e),this.cachedData=null);let r,i=getID3Data(e,0),s=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?getTimeStamp(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&isFiniteNumber(o))&&(this.basePTS=initPTSFn(o,t,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:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){const t=this.appendFrame(n,e,s);t?(this.frameIndex++,this.lastPTS=t.sample.pts,s+=t.length,r=s):s=l}else canParse$2(e,s)?(i=getID3Data(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,r=s):s++;if(s===l&&r!==l){const t=sliceUint8(e,r);this.cachedData?this.cachedData=appendUint8Array(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:dummyTrack(),id3Track:a,textTrack:dummyTrack()}}demuxSampleAes(e,t,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:dummyTrack(),id3Track:this._id3Track,textTrack:dummyTrack()}}destroy(){}}const initPTSFn=(e,t,r)=>{if(isFiniteNumber(e))return 90*e;return 9e4*t+(r?9e4*r.baseTime/r.timescale:0)};function getAudioConfig(e,t,r,i){let s,n,a,o;const l=navigator.userAgent.toLowerCase(),d=i,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[r+2])>>>6);const h=(60&t[r+2])>>>2;if(!(h>c.length-1))return a=(1&t[r+2])<<2,a|=(192&t[r+3])>>>6,logger.log(`manifest codec:${i}, ADTS type:${s}, samplingIndex:${h}`),/firefox/i.test(l)?h>=6?(s=5,o=new Array(4),n=h-3):(s=2,o=new Array(2),n=h):-1!==l.indexOf("android")?(s=2,o=new Array(2),n=h):(s=5,o=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&h>=6?n=h-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(h>=6&&1===a||/vivaldi/i.test(l))||!i&&1===a)&&(s=2,o=new Array(2)),n=h)),o[0]=s<<3,o[0]|=(14&h)>>1,o[1]|=(1&h)<<7,o[1]|=a<<3,5===s&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:c[h],channelCount:a,codec:"mp4a.40."+s,manifestCodec:d};{const t=new Error(`invalid ADTS sampling index:${h}`);e.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}}function isHeaderPattern$1(e,t){return 255===e[t]&&240==(246&e[t+1])}function getHeaderLength(e,t){return 1&e[t+1]?7:9}function getFullFrameLength(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function canGetFrameLength(e,t){return t+5<e.length}function isHeader$1(e,t){return t+1<e.length&&isHeaderPattern$1(e,t)}function canParse$1(e,t){return canGetFrameLength(e,t)&&isHeaderPattern$1(e,t)&&getFullFrameLength(e,t)<=e.length-t}function probe$1(e,t){if(isHeader$1(e,t)){const r=getHeaderLength(e,t);if(t+r>=e.length)return!1;const i=getFullFrameLength(e,t);if(i<=r)return!1;const s=t+i;return s===e.length||isHeader$1(e,s)}return!1}function initTrackConfig(e,t,r,i,s){if(!e.samplerate){const n=getAudioConfig(t,r,i,s);if(!n)return;e.config=n.config,e.samplerate=n.samplerate,e.channelCount=n.channelCount,e.codec=n.codec,e.manifestCodec=n.manifestCodec,logger.log(`parsed codec:${e.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function getFrameDuration(e){return 9216e4/e}function parseFrameHeader(e,t){const r=getHeaderLength(e,t);if(t+r<=e.length){const i=getFullFrameLength(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}function appendFrame$2(e,t,r,i,s){const n=i+s*getFrameDuration(e.samplerate),a=parseFrameHeader(t,r);let o;if(a){const{frameLength:i,headerLength:s}=a,l=s+i,d=Math.max(0,r+l-t.length);d?(o=new Uint8Array(l-s),o.set(t.subarray(r+s,t.length),0)):o=t.subarray(r+s,r+l);const c={unit:o,pts:n};return d||e.samples.push(c),{sample:c,length:l,missing:d}}const l=t.length-r;o=new Uint8Array(l),o.set(t.subarray(r,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let chromeVersion$1=null;const BitratesMap=[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],SamplingRateMap=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],SamplesCoefficients=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],BytesInSlot=[0,1,1,4];function appendFrame$1(e,t,r,i,s){if(r+24>t.length)return;const n=parseHeader(t,r);if(n&&r+n.frameLength<=t.length){const a=i+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(r,r+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function parseHeader(e,t){const r=e[t+1]>>3&3,i=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==r&&0!==s&&15!==s&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*BitratesMap[14*(3===r?3-i:3===i?3:4)+s-1],d=SamplingRateMap[3*(3===r?0:2===r?1:2)+n],c=3===o?1:2,h=SamplesCoefficients[r][i],u=BytesInSlot[i],f=8*h*u,g=Math.floor(h*l/d+a)*u;if(null===chromeVersion$1){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);chromeVersion$1=e?parseInt(e[1]):0}return!!chromeVersion$1&&chromeVersion$1<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:d,channelCount:c,frameLength:g,samplesPerFrame:f}}}function isHeaderPattern(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function isHeader(e,t){return t+1<e.length&&isHeaderPattern(e,t)}function canParse(e,t){return isHeaderPattern(e,t)&&4<=e.length-t}function probe(e,t){if(t+1<e.length&&isHeaderPattern(e,t)){const r=4,i=parseHeader(e,t);let s=r;null!=i&&i.frameLength&&(s=i.frameLength);const n=t+s;return n===e.length||isHeader(e,n)}return!1}class AACDemuxer extends BaseAudioDemuxer{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,r,i){super.resetInitSegment(e,t,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=getID3Data(e,0);let r=(null==t?void 0:t.length)||0;if(probe(e,r))return!1;for(let i=e.length;r<i;r++)if(probe$1(e,r))return logger.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return canParse$1(e,t)}appendFrame(e,t,r){initTrackConfig(e,this.observer,t,r,e.manifestCodec);const i=appendFrame$2(e,t,r,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}}const emsgSchemePattern=/\/emsg[-/]ID3/i;class MP4Demuxer{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,r,i){const s=this.videoTrack=dummyTrack("video",1),n=this.audioTrack=dummyTrack("audio",1),a=this.txtTrack=dummyTrack("text",1);if(this.id3Track=dummyTrack("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=parseInitSegment(e);if(o.video){const{id:e,timescale:t,codec:r}=o.video;s.id=e,s.timescale=a.timescale=t,s.codec=r}if(o.audio){const{id:e,timescale:t,codec:r}=o.audio;n.id=e,n.timescale=t,n.codec=r}a.id=RemuxerTrackIdConfig.text,s.sampleDuration=0,s.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return hasMoofData(e)}demux(e,t){this.timeOffset=t;let r=e;const i=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=appendUint8Array(this.remainderData,e));const t=segmentValidRange(r);this.remainderData=t.remainder,i.samples=t.valid||new Uint8Array}else i.samples=r;const n=this.extractID3Track(i,t);return s.samples=parseSamples(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return r.samples=parseSamples(e,t),{videoTrack:t,audioTrack:dummyTrack(),id3Track:i,textTrack:dummyTrack()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const i=findBox(e.samples,["emsg"]);i&&i.forEach((e=>{const i=parseEmsg(e);if(emsgSchemePattern.test(i.schemeIdUri)){const e=isFiniteNumber(i.presentationTime)?i.presentationTime/i.timeScale:t+i.presentationTimeDelta/i.timeScale;let s=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const n=i.payload;r.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:MetadataSchema.emsg,duration:s})}}))}return r}demuxSampleAes(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const getAudioBSID=(e,t)=>{let r=0,i=5;t+=i;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=e[t];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,r=r?r<<o|s[0]:s[0],t+=1,i-=o}return r};class AC3Demuxer extends BaseAudioDemuxer{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,r,i){super.resetInitSegment(e,t,r,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,r){const i=appendFrame(e,t,r,this.basePTS,this.frameIndex);if(-1!==i){return{sample:e.samples[e.samples.length-1],length:i,missing:0}}}static probe(e){if(!e)return!1;const t=getID3Data(e,0);if(!t)return!1;const r=t.length;return 11===e[r]&&119===e[r+1]&&void 0!==getTimeStamp(t)&&getAudioBSID(e,r)<16}}function appendFrame(e,t,r,i,s){if(r+8>t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;const n=t[r+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[r+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(r+l>t.length)return-1;const d=t[r+6]>>5;let c=0;2===d?c+=2:(1&d&&1!==d&&(c+=2),4&d&&(c+=2));const h=(t[r+6]<<8|t[r+7])>>12-c&1,u=[2,1,2,3,3,4,4,5][d]+h,f=t[r+5]>>3,g=7&t[r+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|d<<3|h<<2|o>>4,o<<4&224]),p=i+s*(1536/a*9e4),y=t.subarray(r,r+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:y,pts:p}),l}class BaseVideoParser{constructor(){this.VideoSample=null}createVideoSample(e,t,r,i){return{key:e,frame:!1,pts:t,dts:r,units:[],debug:i,length:0}}getLastNalUnit(e){var t;let r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){const e=i.units;r=e[e.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const r=t.samples,i=r.length;if(!i)return void t.dropped++;{const t=r[i-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}e.debug.length&&logger.log(e.pts+"/"+e.dts+":"+e.debug)}}class ExpGolomb{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");i.set(e.subarray(r,r+s)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const r=this.word>>>32-t;if(e>32&&logger.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?r<<t|this.readBits(t):r}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t,r=8,i=8;for(let s=0;s<e;s++)0!==i&&(t=this.readEG(),i=(r+t+256)%256),r=0===i?r:i}readSPS(){let e,t,r,i=0,s=0,n=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),d=this.readUEG.bind(this),c=this.readBoolean.bind(this),h=this.skipBits.bind(this),u=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);o();const m=o();if(l(5),h(3),o(),f(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){const e=d();if(3===e&&h(1),f(),f(),h(1),c())for(t=3!==e?8:12,r=0;r<t;r++)c()&&g(r<6?16:64)}f();const p=d();if(0===p)d();else if(1===p)for(h(1),u(),u(),e=d(),r=0;r<e;r++)u();f(),h(1);const y=d(),E=d(),v=l(1);0===v&&h(1),h(1),c()&&(i=d(),s=d(),n=d(),a=d());let T=[1,1];if(c()&&c()){switch(o()){case 1:T=[1,1];break;case 2:T=[12,11];break;case 3:T=[10,11];break;case 4:T=[16,11];break;case 5:T=[40,33];break;case 6:T=[24,11];break;case 7:T=[20,11];break;case 8:T=[32,11];break;case 9:T=[80,33];break;case 10:T=[18,11];break;case 11:T=[15,11];break;case 12:T=[64,33];break;case 13:T=[160,99];break;case 14:T=[4,3];break;case 15:T=[3,2];break;case 16:T=[2,1];break;case 255:T=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(y+1)-2*i-2*s),height:(2-v)*(E+1)*16-(v?2:4)*(n+a),pixelRatio:T}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class AvcVideoParser extends BaseVideoParser{parseAVCPES(e,t,r,i,s){const n=this.parseAVCNALu(e,r.data);let a,o=this.VideoSample,l=!1;r.data=null,o&&n.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts,"")),n.forEach((i=>{var n;switch(i.type){case 1:{let t=!1;a=!0;const s=i.data;if(l&&s.length>4){const e=new ExpGolomb(s).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var d;if(t)null!=(d=o)&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts,"")),o.frame=!0,o.key=t;break}case 5:a=!0,null!=(n=o)&&n.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,parseSEIMessageFromNALu(i.data,1,r.pts,t.samples);break;case 7:{var c,h;a=!0,l=!0;const t=i.data,r=new ExpGolomb(t).readSPS();if(!e.sps||e.width!==r.width||e.height!==r.height||(null==(c=e.pixelRatio)?void 0:c[0])!==r.pixelRatio[0]||(null==(h=e.pixelRatio)?void 0:h[1])!==r.pixelRatio[1]){e.width=r.width,e.height=r.height,e.pixelRatio=r.pixelRatio,e.sps=[t],e.duration=s;const i=t.subarray(1,4);let n="avc1.";for(let e=0;e<3;e++){let t=i[e].toString(16);t.length<2&&(t="0"+t),n+=t}e.codec=n}break}case 8:a=!0,e.pps=[i.data];break;case 9:a=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+i.type+" ")}if(o&&a){o.units.push(i)}})),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const r=t.byteLength;let i=e.naluState||0;const s=i,n=[];let a,o,l,d=0,c=-1,h=0;for(-1===i&&(c=0,h=31&t[0],i=0,d=1);d<r;)if(a=t[d++],i)if(1!==i)if(a)if(1===a){if(o=d-i-1,c>=0){const e={data:t.subarray(c,o),type:h};n.push(e)}else{const r=this.getLastNalUnit(e.samples);r&&(s&&d<=4-s&&r.state&&(r.data=r.data.subarray(0,r.data.byteLength-s)),o>0&&(r.data=appendUint8Array(r.data,t.subarray(0,o)),r.state=0))}d<r?(l=31&t[d],c=d,h=l,i=0):i=-1}else i=0;else i=3;else i=a?0:2;else i=a?0:1;if(c>=0&&i>=0){const e={data:t.subarray(c,r),type:h,state:i};n.push(e)}if(0===n.length){const r=this.getLastNalUnit(e.samples);r&&(r.data=appendUint8Array(r.data,t))}return e.naluState=i,n}}class SampleAesDecrypter{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Decrypter(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,r){const i=e[t].unit;if(i.length<=16)return;const s=i.subarray(16,i.length-i.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then((s=>{const n=new Uint8Array(s);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)}))}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t);let i=0;for(let s=32;s<e.length-16;s+=160,i+=16)r.set(e.subarray(s,s+16),i);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let i=0;for(let s=32;s<e.length-16;s+=160,i+=16)e.set(r.subarray(i,i+16),s);return e}decryptAvcSample(e,t,r,i,s){const n=discardEPB(s.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,r+1,i)}))}decryptAvcSamples(e,t,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void i();const s=e[t].units;for(;!(r>=s.length);r++){const n=s[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,r,i,n),this.decrypter.isSync())))return}}}}const PACKET_LENGTH=188;class TSDemuxer{constructor(e,t,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.videoParser=new AvcVideoParser}static probe(e){const t=TSDemuxer.syncOffset(e);return t>0&&logger.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),-1!==t}static syncOffset(e){const t=e.length;let r=Math.min(5*PACKET_LENGTH,t-PACKET_LENGTH)+1,i=0;for(;i<r;){let s=!1,n=-1,a=0;for(let o=i;o<t;o+=PACKET_LENGTH){if(71!==e[o]||t-o!==PACKET_LENGTH&&71!==e[o+PACKET_LENGTH]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(r=Math.min(n+99*PACKET_LENGTH,e.length-PACKET_LENGTH)+1)),s||(s=0===parsePID(e,o)),s&&a>1&&(0===n&&a>2||o+PACKET_LENGTH>r))return n}i++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:RemuxerTrackIdConfig[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,r,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=TSDemuxer.createTrack("video"),this._audioTrack=TSDemuxer.createTrack("audio",i),this._id3Track=TSDemuxer.createTrack("id3"),this._txtTrack=TSDemuxer.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=r,this._duration=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:r}=this;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,r=!1,i=!1){let s;r||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let d=n.pid,c=n.pesData,h=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,y=this._pmtId,E=e.length;if(this.remainderData&&(E=(e=appendUint8Array(this.remainderData,e)).length,this.remainderData=null),E<PACKET_LENGTH&&!i)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const v=Math.max(0,TSDemuxer.syncOffset(e));E-=(E-v)%PACKET_LENGTH,E<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,E,e.buffer.byteLength-E));let T=0;for(let L=v;L<E;L+=PACKET_LENGTH)if(71===e[L]){const t=!!(64&e[L+1]),i=parsePID(e,L);let E;if((48&e[L+3])>>4>1){if(E=L+5+e[L+4],E===L+PACKET_LENGTH)continue}else E=L+4;switch(i){case d:t&&(c&&(s=parsePES(c))&&this.videoParser.parseAVCPES(n,l,s,!1,this._duration),c={data:[],size:0}),c&&(c.data.push(e.subarray(E,L+PACKET_LENGTH)),c.size+=L+PACKET_LENGTH-E);break;case h:if(t){if(f&&(s=parsePES(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(E,L+PACKET_LENGTH)),f.size+=L+PACKET_LENGTH-E);break;case u:t&&(g&&(s=parsePES(g))&&this.parseID3PES(o,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(E,L+PACKET_LENGTH)),g.size+=L+PACKET_LENGTH-E);break;case 0:t&&(E+=e[E]+1),y=this._pmtId=parsePAT(e,E);break;case y:{t&&(E+=e[E]+1);const i=parsePMT(e,E,this.typeSupported,r);d=i.videoPid,d>0&&(n.pid=d,n.segmentCodec=i.segmentVideoCodec),h=i.audioPid,h>0&&(a.pid=h,a.segmentCodec=i.segmentAudioCodec),u=i.id3Pid,u>0&&(o.pid=u),null===m||p||(logger.warn(`MPEG-TS PMT found at ${L} after unknown PID '${m}'. Backtracking to sync byte @${v} to parse all TS packets.`),m=null,L=v-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=i}}else T++;if(T>0){const e=new Error(`Found ${T} TS packet/s that do not start with 0x47`);this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message})}n.pesData=c,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:r,id3Track:i,textTrack:s}=e,n=r.pesData,a=t.pesData,o=i.pesData;let l;if(n&&(l=parsePES(n))?(this.videoParser.parseAVCPES(r,s,l,!0,this._duration),r.pesData=null):r.pesData=n,a&&(l=parsePES(a))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=parsePES(o))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(e,t,r){const i=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,t);return this.decrypt(i,s)}decrypt(e,t){return new Promise((r=>{const{audioTrack:i,videoTrack:s}=e;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,(()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,(()=>{r(e)})):r(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(()=>{r(e)}))}))}destroy(){this._duration=0}parseAACPES(e,t){let r=0;const i=this.aacOverFlow;let s,n,a,o=t.data;if(i){this.aacOverFlow=null;const t=i.missing,s=i.sample.unit.byteLength;if(-1===t)o=appendUint8Array(i.sample.unit,o);else{const n=s-t;i.sample.unit.set(o.subarray(0,t),n),e.samples.push(i.sample),r=i.missing}}for(s=r,n=o.length;s<n-1&&!isHeader$1(o,s);s++);if(s!==r){let e;const t=s<n-1;e=t?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES";const r=new Error(e);if(logger.warn(`parsing error: ${e}`),this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:r,reason:e}),!t)return}if(initTrackConfig(e,this.observer,o,s,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!i)return void logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=getFrameDuration(e.samplerate);a=i.sample.pts+t}}let l,d=0;for(;s<n;){if(l=appendFrame$2(e,o,s,a,d),s+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;s<n-1&&!isHeader$1(o,s);s++);}}parseMPEGPES(e,t){const r=t.data,i=r.length;let s=0,n=0;const a=t.pts;if(void 0!==a)for(;n<i;)if(isHeader(r,n)){const t=appendFrame$1(e,r,n,a,s);if(!t)break;n+=t.length,s++}else n++;else logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const r=t.data,i=t.pts;if(void 0===i)return void logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const s=r.length;let n,a=0,o=0;for(;o<s&&(n=appendFrame(e,r,o,i,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=_extends({},t,{type:this._videoTrack?MetadataSchema.emsg:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function parsePID(e,t){return((31&e[t+1])<<8)+e[t+2]}function parsePAT(e,t){return(31&e[t+10])<<8|e[t+11]}function parsePMT(e,t,r,i){const s={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},n=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<n;){const n=parsePID(e,t),a=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){logEncryptedSamplesFoundInUnencryptedStream("ADTS AAC");break}case 15:-1===s.audioPid&&(s.audioPid=n);break;case 21:-1===s.id3Pid&&(s.id3Pid=n);break;case 219:if(!i){logEncryptedSamplesFoundInUnencryptedStream("H.264");break}case 27:-1===s.videoPid&&(s.videoPid=n,s.segmentVideoCodec="avc");break;case 3:case 4:r.mpeg||r.mp3?-1===s.audioPid&&(s.audioPid=n,s.segmentAudioCodec="mp3"):logger.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){logEncryptedSamplesFoundInUnencryptedStream("AC-3");break}case 129:r.ac3?-1===s.audioPid&&(s.audioPid=n,s.segmentAudioCodec="ac3"):logger.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===s.audioPid&&a>0){let i=t+5,o=a;for(;o>2;){switch(e[i]){case 106:!0!==r.ac3?logger.log("AC-3 audio found, not supported in this browser for now"):(s.audioPid=n,s.segmentAudioCodec="ac3")}const t=e[i+1]+2;i+=t,o-=t}}break;case 194:case 135:logger.warn("Unsupported EC-3 in M2TS found");break;case 36:logger.warn("Unsupported HEVC in M2TS found")}t+=a+5}return s}function logEncryptedSamplesFoundInUnencryptedStream(e){logger.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function parsePES(e){let t,r,i,s,n,a=0;const o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=appendUint8Array(o[0],o[1]),o.splice(1,1);t=o[0];if(1===(t[0]<<16)+(t[1]<<8)+t[2]){if(r=(t[4]<<8)+t[5],r&&r>e.size-6)return null;const l=t[7];192&l&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?(n=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,s-n>54e5&&(logger.warn(`${Math.round((s-n)/9e4)}s delta between PTS and DTS, align them`),s=n)):n=s),i=t[8];let d=i+9;if(e.size<=d)return null;e.size-=d;const c=new Uint8Array(e.size);for(let e=0,r=o.length;e<r;e++){t=o[e];let r=t.byteLength;if(d){if(d>r){d-=r;continue}t=t.subarray(d),r-=d,d=0}c.set(t,a),a+=r}return r&&(r-=i+3),{data:c,pts:s,dts:n,len:r}}return null}class MP3Demuxer extends BaseAudioDemuxer{resetInitSegment(e,t,r,i){super.resetInitSegment(e,t,r,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=getID3Data(e,0);let r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==getTimeStamp(t)&&getAudioBSID(e,r)<=16)return!1;for(let i=e.length;r<i;r++)if(probe(e,r))return logger.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return canParse(e,t)}appendFrame(e,t,r){if(null!==this.basePTS)return appendFrame$1(e,t,r,this.basePTS,this.frameIndex)}}class AAC{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const UINT32_MAX=Math.pow(2,32)-1;class MP4{static init(){let e;for(e in MP4.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},MP4.types)MP4.types.hasOwnProperty(e)&&(MP4.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);MP4.HDLR_TYPES={video:t,audio:r};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);MP4.STTS=MP4.STSC=MP4.STCO=s,MP4.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),MP4.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),MP4.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),MP4.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);MP4.FTYP=MP4.box(MP4.types.ftyp,n,o,n,a),MP4.DINF=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,i))}static box(e,...t){let r=8,i=t.length;const s=i;for(;i--;)r+=t[i].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(e,4),i=0,r=8;i<s;i++)n.set(t[i],r),r+=t[i].byteLength;return n}static hdlr(e){return MP4.box(MP4.types.hdlr,MP4.HDLR_TYPES[e])}static mdat(e){return MP4.box(MP4.types.mdat,e)}static mdhd(e,t){t*=e;const r=Math.floor(t/(UINT32_MAX+1)),i=Math.floor(t%(UINT32_MAX+1));return MP4.box(MP4.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,r>>24,r>>16&255,r>>8&255,255&r,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(e){return MP4.box(MP4.types.mdia,MP4.mdhd(e.timescale,e.duration),MP4.hdlr(e.type),MP4.minf(e))}static mfhd(e){return MP4.box(MP4.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?MP4.box(MP4.types.minf,MP4.box(MP4.types.smhd,MP4.SMHD),MP4.DINF,MP4.stbl(e)):MP4.box(MP4.types.minf,MP4.box(MP4.types.vmhd,MP4.VMHD),MP4.DINF,MP4.stbl(e))}static moof(e,t,r){return MP4.box(MP4.types.moof,MP4.mfhd(e),MP4.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=MP4.trak(e[t]);return MP4.box.apply(null,[MP4.types.moov,MP4.mvhd(e[0].timescale,e[0].duration)].concat(r).concat(MP4.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=MP4.trex(e[t]);return MP4.box.apply(null,[MP4.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(UINT32_MAX+1)),i=Math.floor(t%(UINT32_MAX+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,r>>24,r>>16&255,r>>8&255,255&r,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(MP4.types.mvhd,s)}static sdtp(e){const t=e.samples||[],r=new Uint8Array(4+t.length);let i,s;for(i=0;i<t.length;i++)s=t[i].flags,r[i+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return MP4.box(MP4.types.sdtp,r)}static stbl(e){return MP4.box(MP4.types.stbl,MP4.stsd(e),MP4.box(MP4.types.stts,MP4.STTS),MP4.box(MP4.types.stsc,MP4.STSC),MP4.box(MP4.types.stsz,MP4.STSZ),MP4.box(MP4.types.stco,MP4.STCO))}static avc1(e){let t,r,i,s=[],n=[];for(t=0;t<e.sps.length;t++)r=e.sps[t],i=r.byteLength,s.push(i>>>8&255),s.push(255&i),s=s.concat(Array.prototype.slice.call(r));for(t=0;t<e.pps.length;t++)r=e.pps[t],i=r.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(r));const a=MP4.box(MP4.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,d=e.pixelRatio[0],c=e.pixelRatio[1];return MP4.box(MP4.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return MP4.box(MP4.types.mp4a,MP4.audioStsd(e),MP4.box(MP4.types.esds,MP4.esds(e)))}static mp3(e){return MP4.box(MP4.types[".mp3"],MP4.audioStsd(e))}static ac3(e){return MP4.box(MP4.types["ac-3"],MP4.audioStsd(e),MP4.box(MP4.types.dac3,e.config))}static stsd(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(e)):"ac3"===e.segmentCodec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.ac3(e)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp4a(e)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(e))}static tkhd(e){const t=e.id,r=e.duration*e.timescale,i=e.width,s=e.height,n=Math.floor(r/(UINT32_MAX+1)),a=Math.floor(r%(UINT32_MAX+1));return MP4.box(MP4.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,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,s>>8&255,255&s,0,0]))}static traf(e,t){const r=MP4.sdtp(e),i=e.id,s=Math.floor(t/(UINT32_MAX+1)),n=Math.floor(t%(UINT32_MAX+1));return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),MP4.box(MP4.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n])),MP4.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,MP4.box(MP4.types.trak,MP4.tkhd(e),MP4.mdia(e))}static trex(e){const t=e.id;return MP4.box(MP4.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const r=e.samples||[],i=r.length,s=12+16*i,n=new Uint8Array(s);let a,o,l,d,c,h;for(t+=8+s,n.set(["video"===e.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<i;a++)o=r[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(MP4.types.trun,n)}static initSegment(e){MP4.types||MP4.init();const t=MP4.moov(e);return appendUint8Array(MP4.FTYP,t)}}MP4.types=void 0,MP4.HDLR_TYPES=void 0,MP4.STTS=void 0,MP4.STSC=void 0,MP4.STCO=void 0,MP4.STSZ=void 0,MP4.VMHD=void 0,MP4.SMHD=void 0,MP4.STSD=void 0,MP4.FTYP=void 0,MP4.DINF=void 0;const MPEG_TS_CLOCK_FREQ_HZ=9e4;function toTimescaleFromBase(e,t,r=1,i=!1){const s=e*t*r;return i?Math.round(s):s}function toTimescaleFromScale(e,t,r=1,i=!1){return toTimescaleFromBase(e,t,1/r,i)}function toMsFromMpegTsClock(e,t=!1){return toTimescaleFromBase(e,1e3,1/MPEG_TS_CLOCK_FREQ_HZ,t)}function toMpegTsClockFromTimescale(e,t=1){return toTimescaleFromBase(e,MPEG_TS_CLOCK_FREQ_HZ,1/t)}const MAX_SILENT_FRAME_DURATION=1e4,AAC_SAMPLES_PER_FRAME=1024,MPEG_AUDIO_SAMPLE_PER_FRAME=1152,AC3_SAMPLES_PER_FRAME=1536;let chromeVersion=null,safariWebkitVersion=null,now;class MP4Remuxer{constructor(e,t,r,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,null===chromeVersion){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);chromeVersion=e?parseInt(e[1]):0}if(null===safariWebkitVersion){const e=navigator.userAgent.match(/Safari\/(\d+)/i);safariWebkitVersion=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const r=e.reduce(((e,r)=>{const i=r.pts-e;return i<-4294967296?(t=!0,normalizePts(e,r.pts)):i>0?e:r.pts}),e[0].pts);return t&&logger.debug("PTS rollover detected"),r}remux(e,t,r,i,s,n,a,o){let l,d,c,h,u,f,g=s,m=s;const p=e.pid>-1,y=t.pid>-1,E=t.samples.length,v=e.samples.length>0,T=a&&E>0||E>1;if((!p||v)&&(!y||T)||this.ISGenerated||a){if(this.ISGenerated){var S,L,A,b;const e=this.videoTrackConfig;!e||t.width===e.width&&t.height===e.height&&(null==(S=t.pixelRatio)?void 0:S[0])===(null==(L=e.pixelRatio)?void 0:L[0])&&(null==(A=t.pixelRatio)?void 0:A[1])===(null==(b=e.pixelRatio)?void 0:b[1])||this.resetInitSegment()}else c=this.generateIS(e,t,s,n);const r=this.isVideoContiguous;let i,a=-1;if(T&&(a=findKeyframeIndex(t.samples),!r&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){logger.warn(`[mp4-remuxer]: Dropped ${a} out of ${E} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.inputTimeScale,i=m}else-1===a&&(logger.warn(`[mp4-remuxer]: No keyframe found out of ${E} video samples`),f=!1);if(this.ISGenerated){if(v&&T){const r=this.getVideoStartPts(t.samples),i=(normalizePts(e.samples[0].pts,r)-r)/t.inputTimeScale;g+=Math.max(0,i),m+=Math.max(0,-i)}if(v){if(e.samplerate||(logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,s,n)),d=this.remuxAudio(e,g,this.isAudioContiguous,n,y||T||o===PlaylistLevelType.AUDIO?m:void 0),T){const i=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,m,r,i)}}else T&&(l=this.remuxVideo(t,m,r,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(u=flushTextTrackMetadataCueSamples(r,s,this._initPTS,this._initDTS)),i.samples.length&&(h=flushTextTrackUserdataCueSamples(i,s,this._initPTS))),{audio:d,video:l,initSegment:c,independent:f,text:h,id3:u}}generateIS(e,t,r,i){const s=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let d,c,h,u=!l||i,f="audio/mp4";if(u&&(d=c=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):MP4.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(h=e.inputTimeScale,l&&h===l.timescale?u=!1:d=c=s[0].pts-Math.round(h*r))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:MP4.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(h=t.inputTimeScale,l&&h===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=Math.round(h*r);c=Math.min(c,normalizePts(n[0].dts,e)-t),d=Math.min(d,e-t)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:d,timescale:h},this._initDTS={baseTime:c,timescale:h}):d=h=void 0,{tracks:o,initPTS:d,timescale:h}}remuxVideo(e,t,r,i){const s=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS;let d,c,h=this.nextAvcDts,u=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!r||null===h){const e=t*s,i=n[0].pts-normalizePts(n[0].dts,n[0].pts);chromeVersion&&null!==h&&Math.abs(e-i-h)<15e3?r=!0:h=e-i}const y=l.baseTime*s/l.timescale;for(let x=0;x<o;x++){const e=n[x];e.pts=normalizePts(e.pts-y,h),e.dts=normalizePts(e.dts-y,h),e.dts<n[x>0?x-1:x].dts&&(p=!0)}p&&n.sort((function(e,t){const r=e.dts-t.dts,i=e.pts-t.pts;return r||i})),d=n[0].dts,c=n[n.length-1].dts;const E=c-d,v=E?Math.round(E/(o-1)):f||e.inputTimeScale/30;if(r){const e=d-h,r=e>v,i=e<-1;if((r||i)&&(r?logger.warn(`AVC: ${toMsFromMpegTsClock(e,!0)} ms (${e}dts) hole between fragments detected at ${t.toFixed(3)}`):logger.warn(`AVC: ${toMsFromMpegTsClock(-e,!0)} ms (${e}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!i||h>=n[0].pts||chromeVersion)){d=h;const t=n[0].pts-e;if(r)n[0].dts=d,n[0].pts=t;else for(let r=0;r<n.length&&!(n[r].dts>t);r++)n[r].dts-=e,n[r].pts-=e;logger.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(t,!0)}/${toMsFromMpegTsClock(d,!0)}, delta: ${toMsFromMpegTsClock(e,!0)} ms`)}}d=Math.max(0,d);let T=0,S=0,L=d;for(let x=0;x<o;x++){const e=n[x],t=e.units,r=t.length;let i=0;for(let s=0;s<r;s++)i+=t[s].data.length;S+=i,T+=r,e.length=i,e.dts<L?(e.dts=L,L+=v/4|0||1):L=e.dts,g=Math.min(e.pts,g),m=Math.max(e.pts,m)}c=n[o-1].dts;const A=S+4*T+8;let b;try{b=new Uint8Array(A)}catch(w){return void this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:A,reason:`fail allocating video mdat ${A}`})}const R=new DataView(b.buffer);R.setUint32(0,A),b.set(MP4.types.mdat,4);let C=!1,D=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,I=Number.NEGATIVE_INFINITY,P=Number.NEGATIVE_INFINITY;for(let x=0;x<o;x++){const e=n[x],t=e.units;let r,l=0;for(let i=0,s=t.length;i<s;i++){const e=t[i],r=e.data,s=e.data.byteLength;R.setUint32(u,s),u+=4,b.set(r,u),u+=s,l+=4+s}if(x<o-1)f=n[x+1].dts-e.dts,r=n[x+1].pts-e.pts;else{const t=this.config,a=x>0?e.dts-n[x-1].dts:v;if(r=x>0?e.pts-n[x-1].pts:v,t.stretchShortVideoTrack&&null!==this.nextAudioPts){const r=Math.floor(t.maxBufferHole*s),n=(i?g+i*s:this.nextAudioPts)-e.pts;n>r?(f=n-a,f<0?f=a:C=!0,logger.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const d=Math.round(e.pts-e.dts);D=Math.min(D,f),I=Math.max(I,f),_=Math.min(_,r),P=Math.max(P,r),a.push(new Mp4Sample(e.key,f,l,d))}if(a.length)if(chromeVersion){if(chromeVersion<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(safariWebkitVersion&&P-_<I-D&&v/I<.025&&0===a[0].cts){logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=d;for(let t=0,r=a.length;t<r;t++){const i=e+a[t].duration,s=e+a[t].cts;if(t<r-1){const e=i+a[t+1].cts;a[t].duration=e-s}else a[t].duration=t?a[t-1].duration:v;a[t].cts=0,e=i}}f=C||!f?v:f,this.nextAvcDts=h=c+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const k={data1:MP4.moof(e.sequenceNumber++,d,_extends({},e,{samples:a})),data2:b,startPTS:g/s,endPTS:(m+f)/s,startDTS:d/s,endDTS:h/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,k}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return MPEG_AUDIO_SAMPLE_PER_FRAME;case"ac3":return AC3_SAMPLES_PER_FRAME;default:return AAC_SAMPLES_PER_FRAME}}remuxAudio(e,t,r,i,s){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,d=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,h=[],u=void 0!==s;let f=e.samples,g=c?0:8,m=this.nextAudioPts||-1;const p=t*n,y=d.baseTime*n/d.timescale;if(this.isAudioContiguous=r=r||f.length&&m>0&&(i&&Math.abs(p-m)<9e3||Math.abs(normalizePts(f[0].pts-y,p)-m)<20*l),f.forEach((function(e){e.pts=normalizePts(e.pts-y,p)})),!r||m<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;m=0===s?0:i&&!u?Math.max(0,p):f[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let r=0,i=m;r<f.length;r++){const s=f[r],a=s.pts,o=a-i,d=Math.abs(1e3*o/n);if(o<=-t*l&&u)0===r&&(logger.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=m=i=a);else if(o>=t*l&&d<MAX_SILENT_FRAME_DURATION&&u){let t=Math.round(o/l);i=a-t*l,i<0&&(t--,i+=l),0===r&&(this.nextAudioPts=m=i),logger.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(i/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){const t=Math.max(i,0);let n=AAC.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);n||(logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=s.unit.subarray()),f.splice(r,0,{unit:n,pts:t}),i+=l,r++}}s.pts=i,i+=l}}let E,v=null,T=null,S=0,L=f.length;for(;L--;)S+=f[L].unit.byteLength;for(let P=0,k=f.length;P<k;P++){const t=f[P],i=t.unit;let s=t.pts;if(null!==T){h[P-1].duration=Math.round((s-T)/a)}else{if(r&&"aac"===e.segmentCodec&&(s=m),v=s,!(S>0))return;S+=g;try{E=new Uint8Array(S)}catch(I){return void this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,error:I,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!c){new DataView(E.buffer).setUint32(0,S),E.set(MP4.types.mdat,4)}}E.set(i,g);const n=i.byteLength;g+=n,h.push(new Mp4Sample(!0,o,n,0)),T=s}const A=h.length;if(!A)return;const b=h[h.length-1];this.nextAudioPts=m=T+a*b.duration;const R=c?new Uint8Array(0):MP4.moof(e.sequenceNumber++,v/a,_extends({},e,{samples:h}));e.samples=[];const C=v/n,D=m/n,_={data1:R,data2:E,startPTS:C,endPTS:D,startDTS:C,endDTS:D,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,_}remuxEmptyAudio(e,t,r,i){const s=e.inputTimeScale,n=s/(e.samplerate?e.samplerate:s),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,d=(null!==a?a:i.startDTS*s)+l,c=i.endDTS*s+l,h=n*AAC_SAMPLES_PER_FRAME,u=Math.ceil((c-d)/h),f=AAC.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(logger.warn("[mp4-remuxer]: remux empty Audio"),!f)return void logger.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let m=0;m<u;m++){const e=d+m*h;g.push({unit:f,pts:e,dts:e})}return e.samples=g,this.remuxAudio(e,t,r,!1)}}function normalizePts(e,t){let r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function findKeyframeIndex(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function flushTextTrackMetadataCueSamples(e,t,r,i){const s=e.samples.length;if(!s)return;const n=e.inputTimeScale;for(let o=0;o<s;o++){const s=e.samples[o];s.pts=normalizePts(s.pts-r.baseTime*n/r.timescale,t*n)/n,s.dts=normalizePts(s.dts-i.baseTime*n/i.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function flushTextTrackUserdataCueSamples(e,t,r){const i=e.samples.length;if(!i)return;const s=e.inputTimeScale;for(let a=0;a<i;a++){const i=e.samples[a];i.pts=normalizePts(i.pts-r.baseTime*s/r.timescale,t*s)/s}e.samples.sort(((e,t)=>e.pts-t.pts));const n=e.samples;return e.samples=[],{samples:n}}class Mp4Sample{constructor(e,t,r,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=r,this.cts=i,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class PassThroughRemuxer{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,r,i){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(patchEncyptionData(e,i)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:r}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const i=this.initData=parseInitSegment(e);i.audio&&(t=getParsedTrackCodec(i.audio,ElementaryStreamTypes.AUDIO)),i.video&&(r=getParsedTrackCodec(i.video,ElementaryStreamTypes.VIDEO));const s={};i.audio&&i.video?s.audiovideo={container:"video/mp4",codec:t+","+r,initSegment:e,id:"main"}:i.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?s.video={container:"video/mp4",codec:r,initSegment:e,id:"main"}:logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,r,i,s,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};isFiniteNumber(d)||(d=this.lastEndTime=s||0);const h=t.samples;if(null==h||!h.length)return c;const u={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(h),f=this.initData),null==(o=f)||!o.length)return logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=getDuration(h,f),m=getStartDTS(f,h),p=null===m?s:m;(isInvalidInitPts(l,p,s,g)||u.timescale!==l.timescale&&n)&&(u.initPTS=p-s,l&&1===l.timescale&&logger.warn("Adjusting initPTS by "+(u.initPTS-l.baseTime)),this.initPTS=l={baseTime:u.initPTS,timescale:1});const y=e?p-l.baseTime/l.timescale:d,E=y+g;offsetStartDTS(f,h,l.baseTime/l.timescale),g>0?this.lastEndTime=E:(logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const v=!!f.audio,T=!!f.video;let S="";v&&(S+="audio"),T&&(S+="video");const L={data1:h,startPTS:y,startDTS:y,endPTS:E,endDTS:E,type:S,hasAudio:v,hasVideo:T,nb:1,dropped:0};return c.audio="audio"===L.type?L:void 0,c.video="audio"!==L.type?L:void 0,c.initSegment=u,c.id3=flushTextTrackMetadataCueSamples(r,s,l,l),i.samples.length&&(c.text=flushTextTrackUserdataCueSamples(i,s,l)),c}}function isInvalidInitPts(e,t,r,i){if(null===e)return!0;const s=Math.max(i,1),n=t-e.baseTime/e.timescale;return Math.abs(n-r)>s}function getParsedTrackCodec(e,t){const r=null==e?void 0:e.codec;if(r&&r.length>4)return r;if(t===ElementaryStreamTypes.AUDIO){if("ec-3"===r||"ac-3"===r||"alac"===r)return r;if("fLaC"===r||"Opus"===r){return getCodecCompatibleName(r,!1)}const e="mp4a.40.5";return logger.info(`Parsed audio codec "${r}" or audio object type not handled. Using "${e}"`),e}return logger.warn(`Unhandled video codec "${r}"`),"hvc1"===r||"hev1"===r?"hvc1.1.6.L120.90":"av01"===r?"av01.0.04M.08":"avc1.42e01e"}try{now=self.performance.now.bind(self.performance)}catch(err){logger.debug("Unable to use Performance API on this environment"),now=null==optionalSelf?void 0:optionalSelf.Date.now}const muxConfig=[{demux:MP4Demuxer,remux:PassThroughRemuxer},{demux:TSDemuxer,remux:MP4Remuxer},{demux:AACDemuxer,remux:MP4Remuxer},{demux:MP3Demuxer,remux:MP4Remuxer}];muxConfig.splice(2,0,{demux:AC3Demuxer,remux:MP4Remuxer});class Transmuxer{constructor(e,t,r,i,s){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=r,this.vendor=i,this.id=s}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,i){const s=r.transmuxing;s.executeStart=now();let n=new Uint8Array(e);const{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:m,defaultInitPts:p,duration:y,initSegmentData:E}=o,v=getEncryptionType(n,t);if(v&&"AES-128"===v.method){const e=this.getDecrypter();if(!e.isSync())return this.decryptionPromise=e.webCryptoDecrypt(n,v.key.buffer,v.iv.buffer).then((e=>{const t=this.push(e,null,r);return this.decryptionPromise=null,t})),this.decryptionPromise;{let t=e.softwareDecrypt(n,v.key.buffer,v.iv.buffer);if(r.part>-1&&(t=e.flush()),!t)return s.executeEnd=now(),emptyResult(r);n=new Uint8Array(t)}}const T=this.needsProbing(d,c);if(T){const e=this.configureTransmuxer(n);if(e)return logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=now(),emptyResult(r)}(d||c||f||T)&&this.resetInitSegment(E,g,m,y,t),(d||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,v,u,h,r),L=this.currentTransmuxState;return L.contiguous=!0,L.discontinuity=!1,L.trackSwitch=!1,s.executeEnd=now(),S}flush(e){const t=e.transmuxing;t.executeStart=now();const{decrypter:r,currentTransmuxState:i,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));const n=[],{timeOffset:a}=i;if(r){const t=r.flush();t&&n.push(this.push(t,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return t.executeEnd=now(),[emptyResult(e)];const d=o.flush(a);return isPromise(d)?d.then((t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,d,e),n)}flushRemux(e,t,r){const{audioTrack:i,videoTrack:s,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;logger.log(`[transmuxer.ts]: Flushed fragment ${r.sn}${r.part>-1?" p: "+r.part:""} of level ${r.level}`);const d=this.remuxer.remux(i,s,n,a,l,o,!0,this.id);e.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=now()}resetInitialTimestamp(e){const{demuxer:t,remuxer:r}=this;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,r,i,s){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,r,i),a.resetInitSegment(e,t,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,i,s){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,s):this.transmuxUnencrypted(e,r,i,s),n}transmuxUnencrypted(e,t,r,i){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,t,r,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,r,i,s){return this.demuxer.demuxSampleAes(e,t,r).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,this.id),chunkMeta:s})))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:i,vendor:s}=this;let n;for(let h=0,u=muxConfig.length;h<u;h++){var a;if(null!=(a=muxConfig[h].demux)&&a.probe(e)){n=muxConfig[h];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,d=n.remux,c=n.demux;l&&l instanceof d||(this.remuxer=new d(r,t,i,s)),o&&o instanceof c||(this.demuxer=new c(r,t,i),this.probe=c.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Decrypter(this.config)),e}}function getEncryptionType(e,t){let r=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t),r}const emptyResult=e=>({remuxResult:{},chunkMeta:e});function isPromise(e){return"then"in e&&e.then instanceof Function}class TransmuxConfig{constructor(e,t,r,i,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=r,this.duration=i,this.defaultInitPts=s||null}}class TransmuxState{constructor(e,t,r,i,s,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=e,this.contiguous=t,this.accurateTimeOffset=r,this.trackSwitch=i,this.timeOffset=s,this.initSegmentChange=n}}var eventemitter3={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function n(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new s(i,n||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,i,s=[];if(0===this._eventsCount)return s;for(i in e=this._events)t.call(e,i)&&s.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var s=0,n=i.length,a=new Array(n);s<n;s++)a[s]=i[s].fn;return a},o.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,s,n,a){var o=r?r+e:e;if(!this._events[o])return!1;var l,d,c=this._events[o],h=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),h){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,i),!0;case 4:return c.fn.call(c.context,t,i,s),!0;case 5:return c.fn.call(c.context,t,i,s,n),!0;case 6:return c.fn.call(c.context,t,i,s,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(e,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,t);break;case 3:c[d].fn.call(c[d].context,t,i);break;case 4:c[d].fn.call(c[d].context,t,i,s);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(e,t,r){return n(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return n(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,i,s){var n=r?r+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||s&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,d=[],c=o.length;l<c;l++)(o[l].fn!==t||s&&!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(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(eventemitter3);var eventemitter3Exports=eventemitter3.exports,EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class TransmuxerInterface{constructor(e,t,r,i){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=r,this.onFlush=i;const n=(e,t)=>{(t=t||{}).frag=this.frag,t.id=this.id,e===Events.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new EventEmitter,this.observer.on(Events.FRAG_DECRYPTED,n),this.observer.on(Events.ERROR,n);const a=getMediaSource(s.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')},l=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||hasUMDWorker()){try{s.workerPath?(logger.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=loadWorker(s.workerPath)):(logger.log(`injecting Web Worker for "${t}"`),this.workerContext=injectWorker()),this.onwmsg=e=>this.onWorkerMessage(e);const{worker:e}=this.workerContext;e.addEventListener("message",this.onwmsg),e.onerror=e=>{const r=new Error(`${e.message} (${e.filename}:${e.lineno})`);s.enableWorker=!1,logger.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:r})},e.postMessage({cmd:"init",typeSupported:o,vendor:l,id:t,config:JSON.stringify(s)})}catch(err){logger.warn(`Error setting up "${t}" Web Worker, fallback to inline`,err),this.resetWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,o,s,l,t)}return}}this.transmuxer=new Transmuxer(this.observer,o,s,l,t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,r,i,s,n,a,o,l,d){var c,h;l.transmuxing.start=self.performance.now();const{transmuxer:u}=this,f=n?n.start:s.start,g=s.decryptdata,m=this.frag,p=!(m&&s.cc===m.cc),y=!(m&&l.level===m.level),E=m?l.sn-m.sn:-1,v=this.part?l.part-this.part.index:-1,T=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!y&&(1===E||0===E&&(1===v||T&&v<=0)),L=self.performance.now();(y||E||0===s.stats.parsing.start)&&(s.stats.parsing.start=L),!n||!v&&S||(n.stats.parsing.start=L);const A=!(m&&(null==(c=s.initSegment)?void 0:c.url)===(null==(h=m.initSegment)?void 0:h.url)),b=new TransmuxState(p,S,o,y,f,A);if(!S||p||A){logger.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${p}\n trackSwitch: ${y}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${A}`);const e=new TransmuxConfig(r,i,t,a,d);this.configureTransmuxer(e)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:l,state:b},e instanceof ArrayBuffer?[e]:[]);else if(u){const t=u.push(e,g,l,b);isPromise(t)?(u.async=!0,t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}))):(u.async=!1,this.handleTransmuxComplete(t))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let r=t.flush(e);isPromise(r)||t.async?(isPromise(r)||(r=Promise.resolve(r)),r.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}))):this.handleFlushResult(r,e)}}transmuxerError(e,t,r){this.hls&&(this.error=e,this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:r}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}onWorkerMessage(e){const t=e.data,r=this.hls;switch(t.event){case"init":{var i;const e=null==(i=this.workerContext)?void 0:i.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":logger[t.data.logType]&&logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data)}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function subtitleOptionsIdentical(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!mediaAttributesIdentical(e[r].attrs,t[r].attrs))return!1;return!0}function mediaAttributesIdentical(e,t,r){const i=e["STABLE-RENDITION-ID"];return i&&!r?i===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((r=>e[r]!==t[r]))}function subtitleTrackMatchesTextTrack(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}const TICK_INTERVAL$2=100;class AudioStreamController extends BaseStreamController{constructor(e,t,r){super(e,t,r,"[audio-stream-controller]",PlaylistLevelType.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Events.ERROR,this.onError,this),e.on(Events.BUFFER_RESET,this.onBufferReset,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Events.ERROR,this.onError,this),e.off(Events.BUFFER_RESET,this.onBufferReset,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:r,initPTS:i,timescale:s}){if("main"===r){const e=t.cc;this.initPTS[t.cc]={baseTime:i,timescale:s},this.log(`InitPTS for cc: ${e} found from main: ${i}`),this.videoTrackCC=e,this.state===State.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state=State.STOPPED);const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(TICK_INTERVAL$2),t>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=State.IDLE):(this.loadedmetadata=!1,this.state=State.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case State.IDLE:this.doTickIdle();break;case State.WAITING_TRACK:{var e;const{levels:t,trackId:r}=this,i=null==t||null==(e=t[r])?void 0:e.details;if(i){if(this.waitForCdnTuneIn(i))break;this.state=State.WAITING_INIT_PTS}break}case State.FRAG_LOADING_WAITING_RETRY:{var t;const e=performance.now(),r=this.retryDate;if(!r||e>=r||null!=(t=this.media)&&t.seeking){const{levels:e,trackId:t}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==e?void 0:e[t])||null),this.state=State.IDLE}break}case State.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:r,cache:i,complete:s}=e;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=State.FRAG_LOADING;const e={frag:t,part:r,payload:i.flush(),networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const e=this.getLoadPosition(),r=BufferHelper.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);fragmentWithinToleranceTest(r.end,this.config.maxFragLookUpTolerance,t)<0&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${r.end} is needed`),this.clearWaitingFragment())}}else this.state=State.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=State.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:r,trackId:i}=this,s=e.config;if(!r&&(this.startFragRequested||!s.startFragPrefetch)||null==t||!t[i])return;const n=t[i],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=State.WAITING_TRACK);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,ElementaryStreamTypes.AUDIO,PlaylistLevelType.AUDIO));const l=this.getFwdBufferInfo(o,PlaylistLevelType.AUDIO);if(null===l)return;const{bufferedTrack:d,switchingTrack:c}=this;if(!c&&this._streamEnded(l,a))return e.trigger(Events.BUFFER_EOS,{type:"audio"}),void(this.state=State.ENDED);const h=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,PlaylistLevelType.MAIN),u=l.len,f=this.getMaxBufferLength(null==h?void 0:h.len),g=a.fragments,m=g[0].start;let p=this.flushing?this.getLoadPosition():l.end;if(c&&r){const e=this.getLoadPosition();d&&!mediaAttributesIdentical(c.attrs,d.attrs)&&(p=e),a.PTSKnown&&e<m&&(l.end>m||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=m+.05)}if(u>=f&&!c&&p<g[g.length-1].start)return;let y=this.getNextFragment(p,a),E=!1;if(y&&this.isLoopLoading(y,p)&&(E=!!y.gap,y=this.getNextFragmentLoopLoading(y,a,l,PlaylistLevelType.MAIN,f)),!y)return void(this.bufferFlushed=!0);const v=h&&y.start>h.end+a.targetduration;if(v||(null==h||!h.len)&&l.len){const e=this.getAppendedFrag(y.start,PlaylistLevelType.MAIN);if(null===e)return;if(E||(E=!!e.gap||!!v&&0===h.len),v&&!E||E&&l.nextStart&&l.nextStart<e.end)return}this.loadFragment(y,n,p)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((e=>new Level(e)))}onAudioTrackSwitching(e,t){const r=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),r?this.setInterval(TICK_INTERVAL$2):this.resetTransmuxer(),r?(this.switchingTrack=t,this.state=State.IDLE,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=State.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(Events.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var r;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=t);const{levels:i}=this,{details:s,id:n}=t;if(!i)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const a=i[n];let o=0;if(s.live||null!=(r=a.details)&&r.live){this.checkLiveUpdate(s);const e=this.mainDetails;if(s.deltaUpdateFailed||!e)return;var l;if(!a.details&&s.hasProgramDateTime&&e.hasProgramDateTime)alignMediaPlaylistByPDT(s,e),o=s.fragments[0].start;else o=this.alignPlaylists(s,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=s,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(this.mainDetails||s,o),this.state!==State.WAITING_TRACK||this.waitForCdnTuneIn(s)||(this.state=State.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:r,part:i,payload:s}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.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(r.start);const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new TransmuxerInterface(this.hls,PlaylistLevelType.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=i?i.index:-1,n=-1!==t,a=new ChunkMetadata(r.level,r.sn,r.stats.chunkCount,s.byteLength,t,n);h.push(s,f,c,"",r,i,d.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:r,part:i,cache:new ChunkCache,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=State.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:r,part:i}=t;if(r.type===PlaylistLevelType.AUDIO)if(this.fragContextChanged(r))this.warn(`Fragment ${r.sn}${i?" p: "+i.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==r.sn){this.fragPrevious=r;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(Events.AUDIO_TRACK_SWITCHED,_objectSpread2({},e)))}this.fragBufferedComplete(r,i)}else if(!this.loadedmetadata&&r.type===PlaylistLevelType.MAIN){const e=this.videoBuffer||this.media;if(e){BufferHelper.getBuffered(e).length&&(this.loadedmetadata=!0)}}}onError(e,t){var r;if(t.fatal)this.state=State.ERROR;else switch(t.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO,t);break;case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==State.WAITING_TRACK||(null==(r=t.context)?void 0:r.type)!==PlaylistContextType.AUDIO_TRACK||(this.state=State.IDLE);break;case ErrorDetails.BUFFER_APPEND_ERROR:case ErrorDetails.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;if(t.details===ErrorDetails.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==ElementaryStreamTypes.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ElementaryStreamTypes.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===State.ENDED&&(this.state=State.IDLE);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,PlaylistLevelType.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const r="audio",{hls:i}=this,{remuxResult:s,chunkMeta:n}=e,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}=s;if(!this.fragContextChanged(o)&&c){if(this.state=State.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;this._bufferInitSegment(d,g.tracks,e,n),i.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:g.tracks})}if(h){const{startPTS:e,endPTS:t,startDTS:r,endDTS:i}=h;l&&(l.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:e,endPTS:t,startDTS:r,endDTS:i}),o.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,e,t,r,i),this.bufferFragmentData(h,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=_extends({id:r,frag:o,details:c},f);i.trigger(Events.FRAG_PARSING_METADATA,e)}if(u){const e=_extends({id:r,frag:o,details:c},u);i.trigger(Events.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,r,i){if(this.state!==State.PARSING)return;t.video&&delete t.video;const s=t.audio;if(!s)return;s.id="audio";const n=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${n}/${s.codec}]`),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(Events.BUFFER_CODECS,t);const a=s.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:r,part:null,chunkMeta:i,parent:r.type,data:a};this.hls.trigger(Events.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,r){const i=this.fragmentTracker.getState(e);var s;if(this.fragCurrent=e,this.switchingTrack||i===FragmentState.NOT_LOADED||i===FragmentState.PARTIAL)if("initSegment"===e.sn)this._loadInitSegment(e,t);else if(null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=State.WAITING_INIT_PTS;const r=this.mainDetails;r&&r.fragments[0].start!==t.details.fragments[0].start&&alignMediaPlaylistByPDT(t.details,r)}else this.startFragRequested=!0,super.loadFragment(e,t,r);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:t,bufferedTrack:r}=this,i=null==r?void 0:r.attrs,s=e.attrs;t&&i&&(i.CHANNELS!==s.CHANNELS||r.name!==e.name||r.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Events.AUDIO_TRACK_SWITCHED,_objectSpread2({},e))}}class AudioTrackController extends BasePlaylistController{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Events.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:r,groupId:i,details:s}=t,n=this.tracksInGroup[r];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${r} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${r} "${n.name}" lang:${n.lang} group:${i} loaded [${s.startSN}-${s.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const r=t.audioGroups||null,i=this.groupIds;let s=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some((e=>-1===(null==i?void 0:i.indexOf(e))))){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!r||-1!==r.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!s&&t){const r=findMatchingOption(t,e,audioMatchPredicate);if(r>-1)s=e[r];else{const e=findMatchingOption(t,this.tracks);s=this.tracks[e]}}let i=this.findTrackId(s);-1===i&&s&&(i=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==r?void 0:r.join(",")}`),this.hls.trigger(Events.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}else this.shouldReloadPlaylist(s)&&this.setAudioTrack(this.trackId)}onError(e,t){!t.fatal&&t.context&&(t.context.type!==PlaylistContextType.AUDIO_TRACK||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||(this.requestScheduled=-1,this.checkRetry(t)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){const i=this.currentTrack;if(i&&matchesOption(e,i,audioMatchPredicate))return i;const s=findMatchingOption(e,this.tracksInGroup,audioMatchPredicate);if(s>-1){const e=this.tracksInGroup[s];return this.setAudioTrack(s),e}if(i){let i=t.loadLevel;-1===i&&(i=t.firstAutoLevel);const s=findClosestLevelWithAudioGroup(e,t.levels,r,i,audioMatchPredicate);if(-1===s)return null;t.nextLoadLevel=s}if(e.channels||e.audioCodec){const t=findMatchingOption(e,r);if(t>-1)return r[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;const r=this.currentTrack,i=t[e],s=i.details&&!i.details.live;if(e===this.trackId&&i===r&&s)return;if(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(Events.AUDIO_TRACK_SWITCHING,_objectSpread2({},i)),s)return;const n=this.switchParams(i.url,null==r?void 0:r.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const i=t[r];if((!this.selectDefaultTrack||i.default)&&(!e||matchesOption(e,i,audioMatchPredicate)))return r}if(e){const{name:r,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(matchesOption({name:r,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o},t[e],audioMatchPredicate))return e}for(let l=0;l<t.length;l++){const r=t[l];if(mediaAttributesIdentical(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const r=t[l];if(mediaAttributesIdentical(e.attrs,r.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){super.loadPlaylist();const i=t.id,s=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}this.log(`loading audio-track playlist ${i} "${t.name}" lang:${t.lang} group:${s}`),this.clearTimer(),this.hls.trigger(Events.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null})}}}const TICK_INTERVAL$1=500;class SubtitleStreamController extends BaseStreamController{constructor(e,t,r){super(e,t,r,"[subtitle-stream-controller]",PlaylistLevelType.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.ERROR,this.onError,this),e.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.ERROR,this.onError,this),e.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=State.IDLE,this.setInterval(TICK_INTERVAL$1),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:r,success:i}=t;if(this.fragPrevious=r,this.state=State.IDLE,!i)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let n;const a=r.start;for(let l=0;l<s.length;l++)if(a>=s[l].start&&a<=s[l].end){n=s[l];break}const o=r.start+r.duration;n?n.end=o:(n={start:a,end:o},s.push(n)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null)}onBufferFlushing(e,t){const{startOffset:r,endOffset:i}=t;if(0===r&&i!==Number.POSITIVE_INFINITY){const e=i-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let r=0;r<t.length;)if(t[r].end<=e)t.shift();else{if(!(t[r].start<e))break;t[r].start=e,r++}})),this.fragmentTracker.removeFragmentsInRange(r,e,PlaylistLevelType.SUBTITLE)}}onFragBuffered(e,t){var r;this.loadedmetadata||t.frag.type!==PlaylistLevelType.MAIN||null!=(r=this.media)&&r.buffered.length&&(this.loadedmetadata=!0)}onError(e,t){const r=t.frag;(null==r?void 0:r.type)===PlaylistLevelType.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==State.STOPPED&&(this.state=State.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&subtitleOptionsIdentical(this.levels,t)?this.levels=t.map((e=>new Level(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new Level(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,PlaylistLevelType.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var r;if(this.currentTrackId=t.id,null==(r=this.levels)||!r.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(TICK_INTERVAL$1)}onSubtitleTrackLoaded(e,t){var r;const{currentTrackId:i,levels:s}=this,{details:n,id:a}=t;if(!s)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=s[i];if(a>=s.length||a!==i||!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;let l=0;if(n.live||null!=(r=o.details)&&r.live){const e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;const t=e.fragments[0];var d;if(o.details)l=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details),0===l&&t&&(l=t.start,addSliding(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(alignMediaPlaylistByPDT(n,e),l=n.fragments[0].start):t&&(l=t.start,addSliding(n,l))}if(o.details=n,this.levelLastLoaded=o,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===State.IDLE){findFragmentByPTS(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:r}=e,i=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&null!=i&&i.key&&i.iv&&"AES-128"===i.method){const e=performance.now();this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer).catch((e=>{throw s.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((r=>{const i=performance.now();s.trigger(Events.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:e,tdecrypt:i}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=State.IDLE}))}}doTick(){if(this.media){if(this.state===State.IDLE){const{currentTrackId:e,levels:t}=this,r=null==t?void 0:t[e];if(!r||!t.length||!r.details)return;const{config:i}=this,s=this.getLoadPosition(),n=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,i.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,PlaylistLevelType.MAIN),d=r.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+d.levelTargetDuration)return;const c=d.fragments,h=c.length,u=d.edge;let f=null;const g=this.fragPrevious;if(a<u){const e=i.maxFragLookUpTolerance,t=a>u-e?0:e;f=findFragmentByPTS(g,c,Math.max(c[0].start,a),t),!f&&g&&g.start<c[0].start&&(f=c[0])}else f=c[h-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const e=c[f.sn-d.startSN-1];e&&e.cc===f.cc&&this.fragmentTracker.getState(e)===FragmentState.NOT_LOADED&&(f=e)}this.fragmentTracker.getState(f)===FragmentState.NOT_LOADED&&this.loadFragment(f,r,a)}}else this.state=State.IDLE}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,r){this.fragCurrent=e,"initSegment"===e.sn?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,r))}get mediaBufferTimeRanges(){return new BufferableInstance(this.tracksBuffered[this.currentTrackId]||[])}}class BufferableInstance{constructor(e){this.buffered=void 0;const t=(t,r,i)=>{if((r>>>=0)>i-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${i})`);return e[r][t]};this.buffered={get length(){return e.length},end:r=>t("end",r,e.length),start:r=>t("start",r,e.length)}}}class SubtitleTrackController extends BasePlaylistController{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=filterSubtitleTracks(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}const r=this.findTrackForTextTrack(e);this.subtitleTrack!==r&&this.setSubtitleTrack(r)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Events.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);filterSubtitleTracks(this.media.textTracks).forEach((e=>{clearCurrentCues(e)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:r,groupId:i,details:s}=t,n=this.tracksInGroup[r];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${r} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${r} "${n.name}" lang:${n.lang} group:${i} loaded [${s.startSN}-${s.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const r=t.subtitleGroups||null,i=this.groupIds;let s=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some((e=>-1===(null==i?void 0:i.indexOf(e))))){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!r||-1!==r.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!s&&t){this.selectDefaultTrack=!1;const r=findMatchingOption(t,e);if(r>-1)s=e[r];else{const e=findMatchingOption(t,this.tracks);s=this.tracks[e]}}let i=this.findTrackId(s);-1===i&&s&&(i=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==r?void 0:r.join(",")}" group-id`),this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED,n),-1!==i&&-1===this.trackId&&this.setSubtitleTrack(i)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,r=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const s=t[i];if((!r||s.default)&&(r||e)&&(!e||matchesOption(s,e)))return i}if(e){for(let r=0;r<t.length;r++){const i=t[r];if(mediaAttributesIdentical(e.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){const i=t[r];if(mediaAttributesIdentical(e.attrs,i.attrs,["LANGUAGE"]))return r}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){if(subtitleTrackMatchesTextTrack(t[r],e))return r}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==PlaylistContextType.SUBTITLE_TRACK||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const r=this.currentTrack;if(r&&matchesOption(e,r))return r;const i=findMatchingOption(e,this.tracksInGroup);if(i>-1){const e=this.tracksInGroup[i];return this.setSubtitleTrack(i),e}if(r)return null;{const r=findMatchingOption(e,t);if(r>-1)return t[r]}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const i=t.id,s=t.groupId;let n=t.url;if(e)try{n=e.addDirectives(n)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(Events.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=filterSubtitleTracks(e.textTracks),r=this.currentTrack;let i;if(r&&(i=t.filter((e=>subtitleTrackMatchesTextTrack(r,e)))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(t).forEach((e=>{"disabled"!==e.mode&&e!==i&&(e.mode="disabled")})),i){const e=this.subtitleDisplay?"showing":"hidden";i.mode!==e&&(i.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!isFiniteNumber(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;const r=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i)return void this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:e});const s=!!i.details&&!i.details.live;if(e===this.trackId&&i===r&&s)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:d}=i;this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:d});const c=this.switchParams(i.url,null==r?void 0:r.details);this.loadPlaylist(c)}}class BufferOperationQueue{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,r){const i=this.queues[t];i.push(e),1!==i.length||r||this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const r=new Promise((e=>{t=e})),i={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,e),r}executeNext(e){const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(r){logger.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${r}`),i.onError(r);const t=this.buffers[e];null!=t&&t.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const VIDEO_CODEC_PROFILE_REPLACE=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class BufferController{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=e=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:e,mediaSource:t}=this;this.log("Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(Events.MEDIA_ATTACHED,{media:e,mediaSource:t})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&logger.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e;const t="[buffer-controller]";this.appendSource=e.config.preferManagedMediaSource&&"undefined"!=typeof self&&self.ManagedMediaSource,this.log=logger.log.bind(logger,t),this.warn=logger.warn.bind(logger,t),this.error=logger.error.bind(logger,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.BUFFER_RESET,this.onBufferReset,this),e.on(Events.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Events.BUFFER_EOS,this.onBufferEos,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.FRAG_PARSED,this.onFragParsed,this),e.on(Events.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.BUFFER_RESET,this.onBufferReset,this),e.off(Events.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events.BUFFER_EOS,this.onBufferEos,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.FRAG_PARSED,this.onFragParsed,this),e.off(Events.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new BufferOperationQueue(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const r=this.media=t.media,i=getMediaSource(this.appendSource);if(r&&i){var s;const e=this.mediaSource=new i;this.log(`created media source: ${null==(s=e.constructor)?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming));const t=this._objectUrl=self.URL.createObjectURL(e);if(this.appendSource)try{r.removeAttribute("src");const i=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||i&&e instanceof i,removeSourceChildren(r),addSource(r,t),r.load()}catch(n){r.src=t}else r.src=t;r.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:r}=this;if(t){if(this.log("media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(err){this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),r&&self.URL.revokeObjectURL(r),this.mediaSrc===r?(e.removeAttribute("src"),this.appendSource&&removeSourceChildren(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(Events.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((e=>{this.resetBuffer(e)})),this._initSourceBuffer()}resetBuffer(e){const t=this.sourceBuffer[e];try{var r;if(t)this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}catch(err){this.warn(`onBufferReset ${e}`,err)}}onBufferCodecs(e,t){const r=this.getSourceBufferTypes().length,i=Object.keys(t);if(i.forEach((e=>{if(r){const r=this.tracks[e];if(r&&"function"==typeof r.buffer.changeType){var i;const{id:s,codec:n,levelCodec:a,container:o,metadata:l}=t[e],d=pickMostCompleteCodecName(r.codec,r.levelCodec),c=null==d?void 0:d.replace(VIDEO_CODEC_PROFILE_REPLACE,"$1");let h=pickMostCompleteCodecName(n,a);const u=null==(i=h)?void 0:i.replace(VIDEO_CODEC_PROFILE_REPLACE,"$1");if(h&&c!==u){"audio"===e.slice(0,5)&&(h=getCodecCompatibleName(h,this.appendSource));const t=`${o};codecs=${h}`;this.appendChangeType(e,t),this.log(`switching codec ${d} to ${h}`),this.tracks[e]={buffer:r.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:s}}}}else this.pendingTracks[e]=t[e]})),r)return;const s=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==s&&(this.log(`${s} bufferCodec event(s) expected ${i.join(",")}`),this.bufferCodecEventsExpected=s),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:r}=this,i={execute:()=>{const i=this.sourceBuffer[e];i&&(this.log(`changing ${e} sourceBuffer type to ${t}`),i.changeType(t)),r.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};r.append(i,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:r,operationQueue:i,tracks:s}=this,{data:n,type:a,frag:o,part:l,chunkMeta:d}=t,c=d.buffering[a],h=self.performance.now();c.start=h;const u=o.stats.buffering,f=l?l.stats.buffering:null;0===u.start&&(u.start=h),f&&0===f.start&&(f.start=h);const g=s.audio;let m=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===d.id||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const p=o.start,y={execute:()=>{if(c.executeStart=self.performance.now(),m){const e=this.sourceBuffer[a];if(e){const t=p-e.timestampOffset;Math.abs(t)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${p} (delta: ${t}) sn: ${o.sn})`),e.timestampOffset=p)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();c.executeEnd=c.end=e,0===u.first&&(u.first=e),f&&0===f.first&&(f.first=e);const{sourceBuffer:t}=this,r={};for(const i in t)r[i]=BufferHelper.getBuffered(t[i]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Events.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:d,parent:o.type,timeRanges:r})},onError:e=>{const t={type:ErrorTypes.MEDIA_ERROR,parent:o.type,details:ErrorDetails.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:d,error:e,err:e,fatal:!1};if(e.code===DOMException.QUOTA_EXCEEDED_ERR)t.details=ErrorDetails.BUFFER_FULL_ERROR;else{const e=++this.appendErrors[a];t.details=ErrorDetails.BUFFER_APPEND_ERROR,this.warn(`Failed ${e}/${r.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),e>=r.config.appendErrorMaxRetry&&(t.fatal=!0)}r.trigger(Events.ERROR,t)}};i.append(y,a,!!this.pendingTracks[a])}onBufferFlushing(e,t){const{operationQueue:r}=this,i=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(Events.BUFFER_FLUSHED,{type:e})},onError:t=>{this.warn(`Failed to remove from ${e} SourceBuffer`,t)}});t.type?r.append(i(t.type),t.type):this.getSourceBufferTypes().forEach((e=>{r.append(i(e),e)}))}onFragParsed(e,t){const{frag:r,part:i}=t,s=[],n=i?i.elementaryStreams:r.elementaryStreams;n[ElementaryStreamTypes.AUDIOVIDEO]?s.push("audiovideo"):(n[ElementaryStreamTypes.AUDIO]&&s.push("audio"),n[ElementaryStreamTypes.VIDEO]&&s.push("video"));0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers((()=>{const e=self.performance.now();r.stats.buffering.end=e,i&&(i.stats.buffering.end=e);const t=i?i.stats:r.stats;this.hls.trigger(Events.FRAG_BUFFERED,{frag:r,part:i,stats:t,id:r.type})}),s)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce(((e,r)=>{const i=this.sourceBuffer[r];return!i||t.type&&t.type!==r||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${r} sourceBuffer now EOS`))),e&&!(i&&!i.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];t&&(t.ending=!1)}));const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream()):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:r}=this;if(!r||null===t)return;if(!this.getSourceBufferTypes().length)return;const i=e.config,s=r.currentTime,n=t.levelTargetDuration,a=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(isFiniteNumber(a)&&a>0){const e=Math.max(a,n),t=Math.floor(s/n)*n-e;this.flushBackBuffer(s,n,t)}if(isFiniteNumber(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){const e=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),t=Math.max(e,n),r=Math.floor(s/n)*n+t;this.flushFrontBuffer(s,n,r)}}flushBackBuffer(e,t,r){const{details:i,sourceBuffer:s}=this;this.getSourceBufferTypes().forEach((n=>{const a=s[n];if(a){const s=BufferHelper.getBuffered(a);if(s.length>0&&r>s.start(0)){if(this.hls.trigger(Events.BACK_BUFFER_REACHED,{bufferEnd:r}),null!=i&&i.live)this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(a.ended&&s.end(s.length-1)-e<2*t)return void this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);this.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}}))}flushFrontBuffer(e,t,r){const{sourceBuffer:i}=this;this.getSourceBufferTypes().forEach((s=>{const n=i[s];if(n){const i=BufferHelper.getBuffered(n),a=i.length;if(a<2)return;const o=i.start(a-1),l=i.end(a-1);if(r>o||e>=o&&e<=l)return;if(n.ended&&e-l<2*t)return void this.log(`Cannot flush ${s} front buffer while SourceBuffer is in ended state`);this.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:s})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:e,hls:t,media:r,mediaSource:i}=this,s=e.fragments[0].start+e.totalduration,n=r.duration,a=isFiniteNumber(i.duration)?i.duration:0;e.live&&t.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(e)):(s>a&&s>n||!isFiniteNumber(n))&&(this.log(`Updating Media Source duration to ${s.toFixed(3)}`),i.duration=s)}updateSeekableRange(e){const t=this.mediaSource,r=e.fragments;if(r.length&&e.live&&null!=t&&t.setLiveSeekableRange){const i=Math.max(0,r[0].start),s=Math.max(i,i+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${i}-${s}.`),t.setLiveSeekableRange(i,s)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:r}=this,i=Object.keys(r).length;if(i&&(!e||2===i||"audiovideo"in r)){this.createSourceBuffers(r),this.pendingTracks={};const e=this.getSourceBufferTypes();if(e.length)this.hls.trigger(Events.BUFFER_CREATED,{tracks:this.tracks}),e.forEach((e=>{t.executeNext(e)}));else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:r}=this;if(!r)throw Error("createSourceBuffers called when mediaSource was null");for(const i in e)if(!t[i]){const s=e[i];if(!s)throw Error(`source buffer exists for track ${i}, however track does not`);let n=s.levelCodec||s.codec;n&&"audio"===i.slice(0,5)&&(n=getCodecCompatibleName(n,this.appendSource));const a=`${s.container};codecs=${n}`;this.log(`creating sourceBuffer(${a})`);try{const e=t[i]=r.addSourceBuffer(a),o=i;this.addBufferListener(o,"updatestart",this._onSBUpdateStart),this.addBufferListener(o,"updateend",this._onSBUpdateEnd),this.addBufferListener(o,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(o,"bufferedchange",((e,t)=>{const r=t.removedRanges;null!=r&&r.length&&this.hls.trigger(Events.BUFFER_FLUSHED,{type:i})})),this.tracks[i]={buffer:e,codec:n,container:s.container,levelCodec:s.levelCodec,metadata:s.metadata,id:s.id}}catch(err){this.error(`error while trying to add sourceBuffer: ${err.message}`),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:err,sourceBufferName:i,mimeType:a})}}}get mediaSrc(){var e;const t=(null==(e=this.media)?void 0:e.firstChild)||this.media;return null==t?void 0:t.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const{operationQueue:r}=this;r.current(e).onComplete(),r.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var r;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(r=this.mediaSource)?void 0:r.readyState}`);this.error(`${i}`,t),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const s=this.operationQueue.current(e);s&&s.onError(i)}removeExecutor(e,t,r){const{media:i,mediaSource:s,operationQueue:n,sourceBuffer:a}=this,o=a[e];if(!i||!s||!o)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(e);const l=isFiniteNumber(i.duration)?i.duration:1/0,d=isFiniteNumber(s.duration)?s.duration:1/0,c=Math.max(0,t),h=Math.min(r,l,d);h>c&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${c},${h}] from the ${e} SourceBuffer`),o.remove(c,h)):n.shiftAndExecuteNext(e)}appendExecutor(e,t){const r=this.sourceBuffer[t];if(r)r.ended=!1,r.appendBuffer(e);else if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);const{operationQueue:r}=this,i=t.map((e=>r.appendBlocker(e)));Promise.all(i).then((()=>{e(),t.forEach((e=>{const t=this.sourceBuffer[e];null!=t&&t.updating||r.shiftAndExecuteNext(e)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,r){const i=this.sourceBuffer[e];if(!i)return;const s=r.bind(this,e);this.listeners[e].push({event:t,listener:s}),i.addEventListener(t,s)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach((e=>{t.removeEventListener(e.event,e.listener)}))}}function removeSourceChildren(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))}function addSource(e,t){const r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}const specialCea608CharsCodes={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},getCharForByte=function(e){let t=e;return specialCea608CharsCodes.hasOwnProperty(e)&&(t=specialCea608CharsCodes[e]),String.fromCharCode(t)},NR_ROWS=15,NR_COLS=100,rowsLowCh1={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rowsHighCh1={17:2,18:4,21:6,22:8,23:10,19:13,20:15},rowsLowCh2={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},rowsHighCh2={25:2,26:4,29:6,30:8,31:10,27:13,28:15},backgroundColors=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class CaptionsLogger{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r="function"==typeof t?t():t;logger.log(`${this.time} [${e}] ${r}`)}}}const numArrayToHexArray=function(e){const t=[];for(let r=0;r<e.length;r++)t.push(e[r].toString(16));return t};class PenState{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let r=0;r<t.length;r++){const i=t[r];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class StyledUnicodeChar{constructor(){this.uchar=" ",this.penState=new PenState}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class Row{constructor(e){this.chars=[],this.pos=0,this.currPenState=new PenState,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<NR_COLS;t++)this.chars.push(new StyledUnicodeChar);this.logger=e}equals(e){for(let t=0;t<NR_COLS;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<NR_COLS;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<NR_COLS;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>NR_COLS&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=NR_COLS)}moveCursor(e){const t=this.pos+e;if(e>1)for(let r=this.pos+1;r<t+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=getCharForByte(e);this.pos>=NR_COLS?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<NR_COLS;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let r=0;r<NR_COLS;r++){const i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class CaptionScreen{constructor(e){this.rows=[],this.currRow=NR_ROWS-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<NR_ROWS;t++)this.rows.push(new Row(e));this.logger=e}reset(){for(let e=0;e<NR_ROWS;e++)this.rows[e].clear();this.currRow=NR_ROWS-1}equals(e){let t=!0;for(let r=0;r<NR_ROWS;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<NR_ROWS;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<NR_ROWS;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,(()=>"pacData = "+JSON.stringify(e)));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let t=0;t<NR_ROWS;t++)this.rows[t].clear();const e=this.currRow+1-this.nrRollUpRows,r=this.lastOutputScreen;if(r){const i=r.rows[e].cueStartTime,s=this.logger.time;if(null!==i&&null!==s&&i<s)for(let n=0;n<this.nrRollUpRows;n++)this.rows[t-this.nrRollUpRows+n+1].copy(r.rows[e+n])}}this.currRow=t;const r=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,i=Math.max(t-1,0);r.setCursor(e.indent),e.color=r.chars[i].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,(()=>"bkgData = "+JSON.stringify(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let r="",i=-1;for(let s=0;s<NR_ROWS;s++){const r=this.rows[s].getTextString();r&&(i=s+1,e?t.push("Row "+i+": '"+r+"'"):t.push(r.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}getTextAndFormat(){return this.rows}}class Cea608Channel{constructor(e,t,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new CaptionScreen(r),this.nonDisplayedMemory=new CaptionScreen(r),this.lastOutputScreen=new CaptionScreen(r),this.currRollUpRow=this.displayedMemory.rows[NR_ROWS-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[NR_ROWS-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>t+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const r=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[r]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Cea608Parser{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=createCmdHistory(),this.logger=void 0;const i=this.logger=new CaptionsLogger;this.channels=[null,new Cea608Channel(e,t,i),new Cea608Channel(e+1,r,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let r,i,s,n=!1;this.logger.time=e;for(let a=0;a<t.length;a+=2)if(i=127&t[a],s=127&t[a+1],0!==i||0!==s){if(this.logger.log(3,"["+numArrayToHexArray([t[a],t[a+1]])+"] -> ("+numArrayToHexArray([i,s])+")"),r=this.parseCmd(i,s),r||(r=this.parseMidrow(i,s)),r||(r=this.parsePAC(i,s)),r||(r=this.parseBackgroundAttributes(i,s)),!r&&(n=this.parseChars(i,s),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,"Couldn't parse cleaned data "+numArrayToHexArray([i,s])+" orig: "+numArrayToHexArray([t[a],t[a+1]]))}}parseCmd(e,t){const{cmdHistory:r}=this;if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;if(hasCmdRepeated(e,t,r))return setLastCmd(null,null,r),this.logger.log(3,"Repeated command ("+numArrayToHexArray([e,t])+") is dropped"),!0;const i=20===e||21===e||23===e?1:2,s=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),setLastCmd(e,t,r),this.currentChannel=i,!0}parseMidrow(e,t){let r=0;if((17===e||25===e)&&t>=32&&t<=47){if(r=17===e?1:2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[r];return!!i&&(i.ccMIDROW(t),this.logger.log(3,"MIDROW ("+numArrayToHexArray([e,t])+")"),!0)}return!1}parsePAC(e,t){let r;const i=this.cmdHistory;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;if(hasCmdRepeated(e,t,i))return setLastCmd(null,null,i),!0;const s=e<=23?1:2;r=t>=64&&t<=95?1===s?rowsLowCh1[e]:rowsLowCh2[e]:1===s?rowsHighCh1[e]:rowsHighCh2[e];const n=this.channels[s];return!!n&&(n.setPAC(this.interpretPAC(r,t)),setLastCmd(e,t,i),this.currentChannel=s,!0)}interpretPAC(e,t){let r;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i}parseChars(e,t){let r,i=null,s=null;if(e>=25?(r=2,s=e-8):(r=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,"Special char '"+getCharForByte(e)+"' in channel "+r),i=[e]}else e>=32&&e<=127&&(i=0===t?[e]:[e,t]);if(i){const r=numArrayToHexArray(i);this.logger.log(3,"Char codes = "+r.join(",")),setLastCmd(e,t,this.cmdHistory)}return i}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let r;const i={};16===e||24===e?(r=Math.floor((t-32)/2),i.background=backgroundColors[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(i),setLastCmd(e,t,this.cmdHistory),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}this.cmdHistory=createCmdHistory()}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const r=this.channels[t];r&&r.cueSplitAtTime(e)}}}function setLastCmd(e,t,r){r.a=e,r.b=t}function hasCmdRepeated(e,t,r){return r.a===e&&r.b===t}function createCmdHistory(){return{a:null,b:null}}class OutputFilter{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var VTTCue=function(){if(null!=optionalSelf&&optionalSelf.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const r=t.toLowerCase();return!!~e.indexOf(r)&&r}function i(e){return r(t,e)}function s(e,...t){let r=1;for(;r<arguments.length;r++){const t=arguments[r];for(const r in t)e[r]=t[r]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",c=!1,h=t,u=n,f=a,g=null,m="",p=!0,y="auto",E="start",v=50,T="middle",S=50,L="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return d},set:function(e){d=""+e}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return m},set:function(t){const i=function(t){return r(e,t)}(t);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");m=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},l,{get:function(){return y},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",s({},l,{get:function(){return E},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},l,{get:function(){return v},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return T},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return L},set:function(e){const t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");L=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class StringDecoder{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function parseTimeStamp(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}const r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}class Settings{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,r){for(let i=0;i<r.length;++i)if(t===r[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}function parseOptions(e,t,r,i){const s=i?e.split(i):[e];for(const n in s){if("string"!=typeof s[n])continue;const e=s[n].split(r);if(2!==e.length)continue;t(e[0],e[1])}}const defaults=new VTTCue(0,0,""),center="middle"===defaults.align?"middle":"center";function parseCue(e,t,r){const i=e;function s(){const t=parseTimeStamp(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=s(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),n(),t.endTime=s(),n(),function(e,t){const i=new Settings;parseOptions(e,(function(e,t){let s;switch(e){case"region":for(let s=r.length-1;s>=0;s--)if(r[s].id===t){i.set(e,r[s].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),i.integer(e,s[0]),i.percent(e,s[0])&&i.set("snapToLines",!1),i.alt(e,s[0],["auto"]),2===s.length&&i.alt("lineAlign",s[1],["start",center,"end"]);break;case"position":s=t.split(","),i.percent(e,s[0]),2===s.length&&i.alt("positionAlign",s[1],["start",center,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",center,"end","left","right"])}}),/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");let s=i.get("line","auto");"auto"===s&&-1===defaults.line&&(s=-1),t.line=s,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",center);let n=i.get("position","auto");"auto"===n&&50===defaults.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function fixLineBreaks(e){return e.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(e){const t=this;function r(){let e=t.buffer,r=0;for(e=fixLineBreaks(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;const i=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),i}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=r();const i=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let s=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(s?s=!1:e=r(),t.state){case"HEADER":/:/.test(e)?parseOptions(e,(function(e,t){}),/:/):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new VTTCue(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{parseCue(e,t.cue,t.regionList)}catch(i){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const r=-1!==e.indexOf("--\x3e");if(!e||r&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(i){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const LINEBREAKS=/\r\n|\n\r|\n|\r/g,startsWith=function(e,t,r=0){return e.slice(r,r+t.length)===t},cueString2millis=function(e){let t=parseInt(e.slice(-3));const r=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(isFiniteNumber(t)&&isFiniteNumber(r)&&isFiniteNumber(i)&&isFiniteNumber(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*r,t+=6e4*i,t+=36e5*s,t},hash=function(e){let t=5381,r=e.length;for(;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()};function generateCueId(e,t,r){return hash(e.toString())+hash(t.toString())+hash(r)}const calculateOffset=function(e,t,r){let i=e[t],s=e[i.prevCC];if(!s||!s.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;null!=(n=s)&&n.new;){var n;e.ccOffset+=i.start-s.start,i.new=!1,i=s,s=e[i.prevCC]}e.presentationOffset=r};function parseWebVTT(e,t,r,i,s,n,a){const o=new VTTParser,l=utf8ArrayToStr(new Uint8Array(e)).trim().replace(LINEBREAKS,"\n").split("\n"),d=[],c=t?toMpegTsClockFromTimescale(t.baseTime,t.timescale):0;let h,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(e){const n=r[i];let a=r.ccOffset;const o=(f-c)/9e4;if(null!=n&&n.new&&(void 0!==g?a=r.ccOffset=n.start:calculateOffset(r,i,o)),o){if(!t)return void(h=new Error("Missing initPTS for VTT MPEGTS"));a=o-r.presentationOffset}const l=e.endTime-e.startTime,u=normalizePts(9e4*(e.startTime+a-g),9e4*s)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=generateCueId(e.startTime,e.endTime,m)),e.endTime>0&&d.push(e)},o.onparsingerror=function(e){h=e},o.onflush=function(){h?a(h):n(d)},l.forEach((e=>{if(m){if(startsWith(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((e=>{startsWith(e,"LOCAL:")?u=e.slice(6):startsWith(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{g=cueString2millis(u)/1e3}catch(t){h=t}return}""===e&&(m=!1)}o.parse(e+"\n")})),o.flush()}const IMSC1_CODEC="stpp.ttml.im1t",HMSF_REGEX=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,TIME_UNIT_REGEX=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,textAlignToLineAlign={left:"start",center:"center",right:"end",start:"start",end:"end"};function parseIMSC1(e,t,r,i){const s=findBox(new Uint8Array(e),["mdat"]);if(0===s.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=s.map((e=>utf8ArrayToStr(e))),a=toTimescaleFromScale(t.baseTime,1,t.timescale);try{n.forEach((e=>r(parseTTML(e,a))))}catch(o){i(o)}}function parseTTML(e,t){const r=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(i).reduce(((e,t)=>(e[t]=r.getAttribute(`ttp:${t}`)||i[t],e)),{}),n="preserve"!==r.getAttribute("xml:space"),a=collectionToDictionary(getElementCollection(r,"styling","style")),o=collectionToDictionary(getElementCollection(r,"layout","region")),l=getElementCollection(r,"body","[begin]");return[].map.call(l,(e=>{const r=getTextContent(e,n);if(!r||!e.hasAttribute("begin"))return null;const i=parseTtmlTime(e.getAttribute("begin"),s),l=parseTtmlTime(e.getAttribute("dur"),s);let d=parseTtmlTime(e.getAttribute("end"),s);if(null===i)throw timestampParsingError(e);if(null===d){if(null===l)throw timestampParsingError(e);d=i+l}const c=new VTTCue(i-t,d-t,r);c.id=generateCueId(c.startTime,c.endTime,c.text);const h=getTtmlStyles(o[e.getAttribute("region")],a[e.getAttribute("style")],a),{textAlign:u}=h;if(u){const e=textAlignToLineAlign[u];e&&(c.lineAlign=e),c.align=u}return _extends(c,h),c})).filter((e=>null!==e))}function getElementCollection(e,t,r){const i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function collectionToDictionary(e){return e.reduce(((e,t)=>{const r=t.getAttribute("xml:id");return r&&(e[r]=t),e}),{})}function getTextContent(e,t){return[].slice.call(e.childNodes).reduce(((e,r,i)=>{var s;return"br"===r.nodeName&&i?e+"\n":null!=(s=r.childNodes)&&s.length?getTextContent(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent}),"")}function getTtmlStyles(e,t,r){const i="http://www.w3.org/ns/ttml#styling";let s=null;const n=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return n&&r.hasOwnProperty(n)&&(s=r[n]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce(((r,n)=>{const a=getAttributeNS(t,i,n)||getAttributeNS(e,i,n)||getAttributeNS(s,i,n);return a&&(r[n]=a),r}),{})}function getAttributeNS(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function timestampParsingError(e){return new Error(`Could not parse ttml timestamp ${e}`)}function parseTtmlTime(e,t){if(!e)return null;let r=parseTimeStamp(e);return null===r&&(HMSF_REGEX.test(e)?r=parseHoursMinutesSecondsFrames(e,t):TIME_UNIT_REGEX.test(e)&&(r=parseTimeUnits(e,t))),r}function parseHoursMinutesSecondsFrames(e,t){const r=HMSF_REGEX.exec(e),i=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/t.frameRate}function parseTimeUnits(e,t){const r=TIME_UNIT_REGEX.exec(e),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}class TimelineController{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this),e.on(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this),e.off(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new OutputFilter(this,"textTrack1"),t=new OutputFilter(this,"textTrack2"),r=new OutputFilter(this,"textTrack3"),i=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,e,t),this.cea608Parser2=new Cea608Parser(3,r,i)}}addCues(e,t,r,i,s){let n=!1;for(let a=s.length;a--;){const e=s[a],i=intersection(e[0],e[1],t,r);if(i>=0&&(e[0]=Math.min(e[0],t),e[1]=Math.max(e[1],r),n=!0,i/(r-t)>.5))return}if(n||s.push([t,r]),this.config.renderTextTracksNatively){const s=this.captionsTracks[e];this.Cues.newCue(s,t,r,i)}else{const s=this.Cues.newCue(null,t,r,i);this.hls.trigger(Events.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:i,timescale:s}){const{unparsedVttFrags:n}=this;"main"===r&&(this.initPTS[t.cc]={baseTime:i,timescale:s}),n.length&&(this.unparsedVttFrags=[],n.forEach((e=>{this.onFragLoaded(Events.FRAG_LOADED,e)})))}getExistingTrack(e,t){const{media:r}=this;if(r)for(let i=0;i<r.textTracks.length;i++){const s=r.textTracks[i];if(canReuseVttTextTrack(s,{name:e,lang:t,attrs:{}}))return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:r,media:i}=this,{label:s,languageCode:n}=t[e],a=this.getExistingTrack(s,n);if(a)r[e]=a,clearCurrentCues(r[e]),sendAddTrackEvent(r[e],i);else{const t=this.createTextTrack("captions",s,n);t&&(t[e]=!0,r[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,r){const i=this.media;if(i)return i.addTextTrack(e,t,r)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach((t=>{clearCurrentCues(e[t]),delete e[t]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let r=0;r<t.length;r++)clearCurrentCues(t[r])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],i=r.some((e=>e.textCodec===IMSC1_CODEC));if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(subtitleOptionsIdentical(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const e=this.media,t=e?filterSubtitleTracks(e.textTracks):null;if(this.tracks.forEach(((e,r)=>{let i;if(t){let r=null;for(let i=0;i<t.length;i++)if(t[i]&&canReuseVttTextTrack(t[i],e)){r=t[i],t[i]=null;break}r&&(i=r)}if(i)clearCurrentCues(i);else{const t=captionsOrSubtitlesFromCharacteristics(e);i=this.createTextTrack(t,e.name,e.lang),i&&(i.mode="disabled")}i&&this.textTracks.push(i)})),null!=t&&t.length){const e=t.filter((e=>null!==e)).map((e=>e.label));e.length&&logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const r=`textTrack${t[1]}`,i=this.captionsProperties[r];i&&(i.label=e.name,e.lang&&(i.languageCode=e.lang),i.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){this.initCea608Parsers();const{cea608Parser1:r,cea608Parser2:i,lastCc:s,lastSn:n,lastPartIndex:a}=this;if(this.enabled&&r&&i&&t.frag.type===PlaylistLevelType.MAIN){var o,l;const{cc:e,sn:d}=t.frag,c=null!=(o=null==t||null==(l=t.part)?void 0:l.index)?o:-1;d===n+1||d===n&&c===a+1||e===s||(r.reset(),i.reset()),this.lastCc=e,this.lastSn=d,this.lastPartIndex=c}}onFragLoaded(e,t){const{frag:r,payload:i}=t;if(r.type===PlaylistLevelType.SUBTITLE)if(i.byteLength){const e=r.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){const e=this.tracks[r.level],s=this.vttCCs;s[r.cc]||(s[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),e&&e.textCodec===IMSC1_CODEC?this._parseIMSC1(r,i):this._parseVTTs(t)}}else this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;parseIMSC1(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),r.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{logger.log(`Failed to parse IMSC1: ${t}`),r.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:r,payload:i}=e,{initPTS:s,unparsedVttFrags:n}=this,a=s.length-1;if(!s[r.cc]&&-1===a)return void n.push(e);const o=this.hls;parseWebVTT(null!=(t=r.initSegment)&&t.data?appendUint8Array(r.initSegment.data,new Uint8Array(i)):i,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(e=>{this._appendCues(e,r.level),o.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})}),(t=>{const s="Missing initPTS for VTT MPEGTS"===t.message;s?n.push(e):this._fallbackToIMSC1(r,i),logger.log(`Failed to parse VTT cue: ${t}`),s&&a>r.cc||o.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})}))}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||parseIMSC1(t,this.initPTS[e.cc],(()=>{r.textCodec=IMSC1_CODEC,this._parseIMSC1(e,t)}),(()=>{r.textCodec="wvtt"}))}_appendCues(e,t){const r=this.hls;if(this.config.renderTextTracksNatively){const r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach((e=>addCueToTrack(r,e)))}else{const i=this.tracks[t];if(!i)return;const s=i.default?"default":"subtitles"+t;r.trigger(Events.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===PlaylistLevelType.SUBTITLE&&this.onFragLoaded(Events.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:r,cea608Parser2:i}=this;if(!this.enabled||!r||!i)return;const{frag:s,samples:n}=t;if(s.type!==PlaylistLevelType.MAIN||"NONE"!==this.closedCaptionsForLevel(s))for(let a=0;a<n.length;a++){const e=n[a].bytes;if(e){const t=this.extractCea608Data(e);r.addData(n[a].pts,t[0]),i.addData(n[a].pts,t[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:r,endOffsetSubtitles:i,type:s}){const{media:n}=this;if(n&&!(n.currentTime<r)){if(!s||"video"===s){const{captionsTracks:e}=this;Object.keys(e).forEach((i=>removeCuesInRange(e[i],t,r)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==i){const{textTracks:e}=this;Object.keys(e).forEach((r=>removeCuesInRange(e[r],t,i)))}}}extractCea608Data(e){const t=[[],[]],r=31&e[0];let i=2;for(let s=0;s<r;s++){const r=e[i++],s=127&e[i++],n=127&e[i++];if(0===s&&0===n)continue;if(0!=(4&r)){const e=3&r;0!==e&&1!==e||(t[e].push(s),t[e].push(n))}}return t}}function captionsOrSubtitlesFromCharacteristics(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function canReuseVttTextTrack(e,t){return!!e&&e.kind===captionsOrSubtitlesFromCharacteristics(t)&&subtitleTrackMatchesTextTrack(t,e)}function intersection(e,t,r,i){return Math.min(t,i)-Math.max(e,r)}function newVTTCCs(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class CapLevelController{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&isFiniteNumber(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&logger.log(`Setting autoLevelCapping to ${r}: ${e[r].height}p@${e[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=r,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const r=t.filter(((t,r)=>this.isLevelAllowed(t)&&r<=e));return this.clientRect=null,CapLevelController.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(t){}return e}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,r){if(null==e||!e.length)return-1;let i=e.length-1;const s=Math.max(t,r);for(let o=0;o<e.length;o+=1){const t=e[o];if((t.width>=s||t.height>=s)&&(n=t,!(a=e[o+1])||n.width!==a.width||n.height!==a.height)){i=o;break}}var n,a;return i}}class FPSController{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const r=this.hls.config;if(r.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,r){const i=performance.now();if(t){if(this.lastTime){const e=i-this.lastTime,s=r-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*s/e,o=this.hls;if(o.trigger(Events.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:r}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(Events.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const LOGGER_PREFIX="[eme]";class EMEController{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=EMEController.CDMCleanupPromise?[EMEController.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=logger.debug.bind(logger,LOGGER_PREFIX),this.log=logger.log.bind(logger,LOGGER_PREFIX),this.warn=logger.warn.bind(logger,LOGGER_PREFIX),this.error=logger.error.bind(logger,LOGGER_PREFIX),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:r}=this.config,i=t[e];if(i)return i.licenseUrl;if(e===KeySystems.WIDEVINE&&r)return r;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,r=t[e];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,r=(e,t,r)=>!!e&&r.indexOf(e)===t,i=t.map((e=>e.audioCodec)).filter(r),s=t.map((e=>e.videoCodec)).filter(r);return i.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((t,r)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,i,s).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?n(e):r(t instanceof EMEKeyError?t:new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};n(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:r}=this.config;if("function"!=typeof r){let e=`Configured requestMediaKeySystemAccess is not a function ${r}`;return null===requestMediaKeySystemAccess&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return r(e,t)}getMediaKeysPromise(e,t,r){const i=getSupportedMediaKeySystemConfigurations(e,t,r,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let n=null==s?void 0:s.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(i)}`),n=this.requestMediaKeySystemAccess(e,i);const t=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),n.then((r=>{this.log(`Access for key-system "${r.keySystem}" obtained`);const i=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=r.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),i.then((r=>r?this.setMediaKeysServerCertificate(t,e,r):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return n.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:r}){this.log(`Creating key-system session "${t}" keyId: ${Hex.hexDump(e.keyId||[])}`);const i=r.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:r,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const r=this.createMediaKeySessionContext(e),i=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(r,s,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Hex.hexDump(e.keyId)}updateKeySession(e,t){var r;const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${Hex.hexDump((null==(r=e.decryptdata)?void 0:r.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),i.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,r)=>{const i=getKeySystemsForConfig(this.config),s=e.map(keySystemFormatToKeySystemDomain).filter((e=>!!e&&-1!==i.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const i=keySystemDomainToKeySystemFormat(e);i?t(i):r(new Error(`Unable to find format for key-system "${e}"`))})).catch(r)}))}loadKey(e){const t=e.keyInfo.decryptdata,r=this.getKeyIdString(t),i=`(keyId: ${r} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);let s=this.keyIdToKeySessionPromise[r];return s||(s=this.keyIdToKeySessionPromise[r]=this.getKeySystemForKeyPromise(t).then((({keySystem:r,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(r,s).then((()=>{this.throwIfDestroyed();const e=this.createMediaKeySessionContext({keySystem:r,mediaKeys:s,decryptdata:t});return this.generateRequestWithPreferredKeySession(e,"cenc",t.pssh,"playlist-key")}))))),s.catch((e=>this.handleError(e)))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof EMEKeyError?this.hls.trigger(Events.ERROR,e.data):this.hls.trigger(Events.ERROR,{type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),r=this.keyIdToKeySessionPromise[t];if(!r){const t=keySystemFormatToKeySystemDomain(e.keyFormat),r=t?[t]:getKeySystemsForConfig(this.config);return this.attemptKeySystemAccess(r)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=getKeySystemsForConfig(this.config)),0===e.length)throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:r}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),null===r)return;let i,s;if("sinf"===t&&this.config.drmSystems[KeySystems.FAIRPLAY]){const e=bin2str(new Uint8Array(r));try{const t=base64Decode(JSON.parse(e).sinf),r=parseSinf(new Uint8Array(t));if(!r)return;i=r.subarray(8,24),s=KeySystems.FAIRPLAY}catch(d){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const e=parsePssh(r);if(null===e)return;0===e.version&&e.systemId===KeySystemIds.WIDEVINE&&e.data&&(i=e.data.subarray(8,24)),s=keySystemIdToKeySystemDomain(e.systemId)}if(!s||!i)return;const n=Hex.hexDump(i),{keyIdToKeySessionPromise:a,mediaKeySessions:o}=this;let l=a[n];for(let c=0;c<o.length;c++){const e=o[c],s=e.decryptdata;if(s.pssh||!s.keyId)continue;const d=Hex.hexDump(s.keyId);if(n===d||-1!==s.uri.replace(/-/g,"").indexOf(n)){l=a[d],delete a[d],s.pssh=new Uint8Array(r),s.keyId=i,l=a[n]=l.then((()=>this.generateRequestWithPreferredKeySession(e,t,r,"encrypted-event-key-match")));break}}l||(l=a[n]=this.getKeySystemSelectionPromise([s]).then((({keySystem:e,mediaKeys:s})=>{var a;this.throwIfDestroyed();const o=new LevelKey("ISO-23001-7",n,null!=(a=keySystemDomainToKeySystemFormat(e))?a:"");return o.pssh=new Uint8Array(r),o.keyId=i,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const i=this.createMediaKeySessionContext({decryptdata:o,keySystem:e,mediaKeys:s});return this.generateRequestWithPreferredKeySession(i,t,r,"encrypted-event-no-match")}))}))),l.catch((e=>this.handleError(e)))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(r).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(i),i.then((()=>{this.log(`Media-keys set for "${e}"`),r.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===r.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,r,i){var s,n;const a=null==(s=this.config.drmSystems)||null==(n=s[e.keySystem])?void 0:n.generateRequest;if(a)try{const i=a.call(this.hls,t,r,e);if(!i)throw new Error("Invalid response from configured generateRequest filter");t=i.initDataType,r=e.decryptdata.pssh=i.initData?new Uint8Array(i.initData):null}catch(f){var o;if(this.warn(f.message),null!=(o=this.hls)&&o.config.debug)throw f}if(null===r)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${i}": ${l} (init data type: ${t} length: ${r?r.byteLength:null})`);const d=new EventEmitter,c=e._onmessage=t=>{const r=e.mediaKeysSession;if(!r)return void d.emit("error",new Error("invalid state"));const{messageType:i,message:s}=t;this.log(`"${i}" message event for session "${r.sessionId}" message size: ${s.byteLength}`),"license-request"===i||"license-renewal"===i?this.renewLicense(e,s).catch((e=>{this.handleError(e),d.emit("error",e)})):"license-release"===i?e.keySystem===KeySystems.FAIRPLAY&&(this.updateKeySession(e,strToUtf8array("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${i}"`)},h=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void d.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const r=e.keyStatus;d.emit("keyStatus",r),"expired"===r&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",c),e.mediaKeysSession.addEventListener("keystatuseschange",h);const u=new Promise(((e,t)=>{d.on("error",t),d.on("keyStatus",(r=>{r.startsWith("usable")?e():"output-restricted"===r?t(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===r?t(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${r}"`)):"expired"===r?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${r}"`)}))}));return e.mediaKeysSession.generateRequest(t,r).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>u)).catch((t=>{throw d.removeAllListeners(),this.removeSession(e),t})).then((()=>(d.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,r)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Hex.hexDump("buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r))} session keyId: ${Hex.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,r=new(0,t.loader)(t),i=this.getServerCertificateUrl(e);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise(((s,n)=>{const a={responseType:"arraybuffer",url:i},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,r,i)=>{s(e.data)},onError:(t,r,s,o)=>{n(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:_objectSpread2({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${i}). Status: ${t.code} (${t.text})`))},onTimeout:(t,r,s)=>{n(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(e,t,r)=>{n(new Error("aborted"))}};r.load(a,l,d)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,r){return new Promise(((i,s)=>{e.setServerCertificate(r).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==r?void 0:r.byteLength}) on "${t}"`),i(e)})).catch((e=>{s(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}unpackPlayReadyKeyMessage(e,t){const r=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=(new DOMParser).parseFromString(r,"application/xml"),s=i.querySelectorAll("HttpHeader");if(s.length>0){let t;for(let r=0,i=s.length;r<i;r++){var n,a;t=s[r];const i=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;i&&o&&e.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 strToUtf8array(atob(l))}setupLicenseXHR(e,t,r,i){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!r.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,r,i)})).catch((n=>{if(!r.decryptdata)throw n;return e.open("POST",t,!0),s.call(this.hls,e,t,r,i)})).then((r=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:r||i}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const r=this.config.keyLoadPolicy.default;return new Promise(((i,s)=>{const n=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const r=this.config.licenseResponseCallback;if(r)try{t=r.call(this.hls,a,n,e)}catch(o){this.error(o)}i(t)}else{const o=r.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const r=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${r} attempts left`),this.requestLicense(e,t).then(i,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then((({xhr:t,licenseChallenge:r})=>{e.keySystem==KeySystems.PLAYREADY&&(r=this.unpackPlayReadyKeyMessage(t,r)),t.send(r)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const r=t.media;this.media=r,r.addEventListener("encrypted",this.onMediaEncrypted),r.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},LevelKey.clearKeyUriToKeyIdMap();const r=t.length;EMEController.CDMCleanupPromise=Promise.all(t.map((e=>this.removeSession(e))).concat(null==e?void 0:e.setMediaKeys(null).catch((e=>{this.log(`Could not clear media keys: ${e}`)})))).then((()=>{r&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)})).catch((e=>{this.log(`Could not close sessions and clear media keys: ${e}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:r}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);return i>-1&&this.mediaKeySessions.splice(i,1),t.remove().catch((e=>{this.log(`Could not remove session: ${e}`)})).then((()=>t.close())).catch((e=>{this.log(`Could not close session: ${e}`)}))}}}EMEController.CDMCleanupPromise=void 0;class EMEKeyError extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var CmObjectType,CmObjectType2,CmStreamingFormat,CmStreamingFormat2,CmcdHeaderField,CmcdHeaderField2;CmObjectType2=CmObjectType||(CmObjectType={}),CmObjectType2.MANIFEST="m",CmObjectType2.AUDIO="a",CmObjectType2.VIDEO="v",CmObjectType2.MUXED="av",CmObjectType2.INIT="i",CmObjectType2.CAPTION="c",CmObjectType2.TIMED_TEXT="tt",CmObjectType2.KEY="k",CmObjectType2.OTHER="o",CmStreamingFormat2=CmStreamingFormat||(CmStreamingFormat={}),CmStreamingFormat2.DASH="d",CmStreamingFormat2.HLS="h",CmStreamingFormat2.SMOOTH="s",CmStreamingFormat2.OTHER="o",CmcdHeaderField2=CmcdHeaderField||(CmcdHeaderField={}),CmcdHeaderField2.OBJECT="CMCD-Object",CmcdHeaderField2.REQUEST="CMCD-Request",CmcdHeaderField2.SESSION="CMCD-Session",CmcdHeaderField2.STATUS="CMCD-Status";const CmcdHeaderMap={[CmcdHeaderField.OBJECT]:["br","d","ot","tb"],[CmcdHeaderField.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[CmcdHeaderField.SESSION]:["cid","pr","sf","sid","st","v"],[CmcdHeaderField.STATUS]:["bs","rtp"]};class SfItem{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map((e=>e instanceof SfItem?e:new SfItem(e)))),this.value=e,this.params=t}}class SfToken{constructor(e){this.description=void 0,this.description=e}}const DICT="Dict";function format(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":"object"==typeof e?JSON.stringify(e):String(e)}function throwError(e,t,r,i){return new Error(`failed to ${e} "${format(t)}" as ${r}`,{cause:i})}const BARE_ITEM="Bare Item",BOOLEAN="Boolean",BYTES="Byte Sequence",DECIMAL="Decimal",INTEGER="Integer";function isInvalidInt(e){return e<-999999999999999||999999999999999<e}const STRING_REGEX=/[\x00-\x1f\x7f]+/,TOKEN="Token",KEY="Key";function serializeError(e,t,r){return throwError("serialize",e,t,r)}function serializeBoolean(e){if("boolean"!=typeof e)throw serializeError(e,BOOLEAN);return e?"?1":"?0"}function base64encode(e){return btoa(String.fromCharCode(...e))}function serializeByteSequence(e){if(!1===ArrayBuffer.isView(e))throw serializeError(e,BYTES);return`:${base64encode(e)}:`}function serializeInteger(e){if(isInvalidInt(e))throw serializeError(e,INTEGER);return e.toString()}function serializeDate(e){return`@${serializeInteger(e.getTime()/1e3)}`}function roundToEven(e,t){if(e<0)return-roundToEven(-e,t);const r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){const t=Math.floor(e*r);return(t%2==0?t:t+1)/r}return Math.round(e*r)/r}function serializeDecimal(e){const t=roundToEven(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw serializeError(e,DECIMAL);const r=t.toString();return r.includes(".")?r:`${r}.0`}const STRING="String";function serializeString(e){if(STRING_REGEX.test(e))throw serializeError(e,STRING);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function symbolToStr(e){return e.description||e.toString().slice(7,-1)}function serializeToken(e){const t=symbolToStr(e);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw serializeError(t,TOKEN);return t}function serializeBareItem(e){switch(typeof e){case"number":if(!isFiniteNumber(e))throw serializeError(e,BARE_ITEM);return Number.isInteger(e)?serializeInteger(e):serializeDecimal(e);case"string":return serializeString(e);case"symbol":return serializeToken(e);case"boolean":return serializeBoolean(e);case"object":if(e instanceof Date)return serializeDate(e);if(e instanceof Uint8Array)return serializeByteSequence(e);if(e instanceof SfToken)return serializeToken(e);default:throw serializeError(e,BARE_ITEM)}}function serializeKey(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw serializeError(e,KEY);return e}function serializeParams(e){return null==e?"":Object.entries(e).map((([e,t])=>!0===t?`;${serializeKey(e)}`:`;${serializeKey(e)}=${serializeBareItem(t)}`)).join("")}function serializeItem(e){return e instanceof SfItem?`${serializeBareItem(e.value)}${serializeParams(e.params)}`:serializeBareItem(e)}function serializeInnerList(e){return`(${e.value.map(serializeItem).join(" ")})${serializeParams(e.params)}`}function serializeDict(e,t={whitespace:!0}){if("object"!=typeof e)throw serializeError(e,DICT);const r=e instanceof Map?e.entries():Object.entries(e),i=null!=t&&t.whitespace?" ":"";return Array.from(r).map((([e,t])=>{t instanceof SfItem==!1&&(t=new SfItem(t));let r=serializeKey(e);return!0===t.value?r+=serializeParams(t.params):(r+="=",Array.isArray(t.value)?r+=serializeInnerList(t):r+=serializeItem(t)),r})).join(`,${i}`)}function encodeSfDict(e,t){return serializeDict(e,t)}const isTokenField=e=>"ot"===e||"sf"===e||"st"===e,isValid=e=>"number"==typeof e?isFiniteNumber(e):null!=e&&""!==e&&!1!==e;function urlToRelativePath(e,t){const r=new URL(e),i=new URL(t);if(r.origin!==i.origin)return e;const s=r.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}function uuid(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?r:3&r|8).toString(16)}))}}}const toRounded=e=>Math.round(e),toUrlSafe=(e,t)=>(null!=t&&t.baseUrl&&(e=urlToRelativePath(e,t.baseUrl)),encodeURIComponent(e)),toHundred=e=>100*toRounded(e/100),CmcdFormatters={br:toRounded,d:toRounded,bl:toHundred,dl:toHundred,mtp:toHundred,nor:toUrlSafe,rtp:toHundred,tb:toRounded};function processCmcd(e,t){const r={};if(null==e||"object"!=typeof e)return r;const i=Object.keys(e).sort(),s=_extends({},CmcdFormatters,null==t?void 0:t.formatters),n=null==t?void 0:t.filter;return i.forEach((i=>{if(null!=n&&n(i))return;let a=e[i];const o=s[i];o&&(a=o(a,t)),"v"===i&&1===a||"pr"==i&&1===a||isValid(a)&&(isTokenField(i)&&"string"==typeof a&&(a=new SfToken(a)),r[i]=a)})),r}function encodeCmcd(e,t={}){return e?encodeSfDict(processCmcd(e,t),_extends({whitespace:!1},t)):""}function toCmcdHeaders(e,t={}){if(!e)return{};const r=Object.entries(e),i=Object.entries(CmcdHeaderMap).concat(Object.entries((null==t?void 0:t.customHeaderMap)||{})),s=r.reduce(((e,t)=>{var r;const[s,n]=t,a=(null==(r=i.find((e=>e[1].includes(s))))?void 0:r[0])||CmcdHeaderField.REQUEST;return null!=e[a]||(e[a]={}),e[a][s]=n,e}),{});return Object.entries(s).reduce(((e,[r,i])=>(e[r]=encodeCmcd(i,t),e)),{})}function appendCmcdHeaders(e,t,r){return _extends(e,toCmcdHeaders(t,r))}const CMCD_PARAM="CMCD";function toCmcdQuery(e,t={}){if(!e)return"";const r=encodeCmcd(e,t);return`${CMCD_PARAM}=${encodeURIComponent(r)}`}const REGEX=/CMCD=[^&#]+/;function appendCmcdQuery(e,t,r){const i=toCmcdQuery(t,r);if(!i)return e;if(REGEX.test(e))return e.replace(REGEX,i);const s=e.includes("?")?"&":"?";return`${e}${s}${i}`}class CMCDController{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:CmObjectType.MANIFEST,su:!this.initialized})}catch(t){logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=e=>{try{const t=e.frag,r=this.hls.levels[t.level],i=this.getObjectType(t),s={d:1e3*t.duration,ot:i};i!==CmObjectType.VIDEO&&i!==CmObjectType.AUDIO&&i!=CmObjectType.MUXED||(s.br=r.bitrate/1e3,s.tb=this.getTopBandwidth(i)/1e3,s.bl=this.getBufferLength(i)),this.apply(e,s)}catch(t){logger.warn("Could not generate segment CMCD data.",t)}},this.hls=e;const t=this.config=e.config,{cmcd:r}=t;null!=r&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||uuid(),this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.includeKeys=r.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var r,i;this.audioBuffer=null==(r=t.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(i=t.tracks.video)?void 0:i.buffer}createData(){var e;return{v:1,sf:CmStreamingFormat.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){_extends(t,this.createData());const r=t.ot===CmObjectType.INIT||t.ot===CmObjectType.VIDEO||t.ot===CmObjectType.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce(((e,r)=>(i.includes(r)&&(e[r]=t[r]),e)),{})),this.useHeaders?(e.headers||(e.headers={}),appendCmcdHeaders(e.headers,t)):e.url=appendCmcdQuery(e.url,t)}getObjectType(e){const{type:t}=e;return"subtitle"===t?CmObjectType.TIMED_TEXT:"initSegment"===e.sn?CmObjectType.INIT:"audio"===t?CmObjectType.AUDIO:"main"===t?this.hls.audioTracks.length?CmObjectType.VIDEO:CmObjectType.MUXED:void 0}getTopBandwidth(e){let t,r=0;const i=this.hls;if(e===CmObjectType.AUDIO)t=i.audioTracks;else{const e=i.maxAutoLevel,r=e>-1?e+1:i.levels.length;t=i.levels.slice(0,r)}for(const s of t)s.bitrate>r&&(r=s.bitrate);return r>0?r:NaN}getBufferLength(e){const t=this.hls.media,r=e===CmObjectType.AUDIO?this.audioBuffer:this.videoBuffer;if(!r||!t)return NaN;return 1e3*BufferHelper.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,i){t(e),this.loader.load(e,r,i)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,i){t(e),this.loader.load(e,r,i)}}}}const PATHWAY_PENALTY_DURATION_MS=3e5;class ContentSteeringController{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=logger.log.bind(logger,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:r}=t;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:r}=t;if((null==r?void 0:r.action)===NetworkErrorAction.SendAlternateToPenaltyBox&&r.flags===ErrorActionFlags.MoveAllAlternatesMatchingHost){const e=this.levels;let i=this.pathwayPriority,s=this.pathwayId;if(t.context){const{groupId:r,pathwayId:i,type:n}=t.context;r&&e?s=this.getPathwayForGroupId(r,n,s):i&&(s=i)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!i&&e&&(i=e.reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==s),r.resolved||logger.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${s} levels: ${e?e.length:e} priorities: ${JSON.stringify(i)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this.pathwayPriority=e;const r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach((e=>{i-r[e]>PATHWAY_PENALTY_DURATION_MS&&delete r[e]}));for(let s=0;s<e.length;s++){const i=e[s];if(i in r)continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,reassignFragmentLevelIndexes(t),this.hls.trigger(Events.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,r){const i=this.getLevelsForPathway(r).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(t===PlaylistContextType.AUDIO_TRACK&&i[s].hasAudioGroup(e)||t===PlaylistContextType.SUBTITLE_TRACK&&i[s].hasSubtitleGroup(e))return i[s].pathwayId;return r}clonePathways(e){const t=this.levels;if(!t)return;const r={},i={};e.forEach((e=>{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===s)))return;const o=this.getLevelsForPathway(n).map((e=>{const t=new AttrList(e.attrs);t["PATHWAY-ID"]=s;const n=t.AUDIO&&`${t.AUDIO}_clone_${s}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${s}`;n&&(r[t.AUDIO]=n,t.AUDIO=n),o&&(i[t.SUBTITLES]=o,t.SUBTITLES=o);const l=performUriReplacement(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Level({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let r=1;r<e.audioGroups.length;r++)d.addGroupId("audio",`${e.audioGroups[r]}_clone_${s}`);if(e.subtitleGroups)for(let r=1;r<e.subtitleGroups.length;r++)d.addGroupId("text",`${e.subtitleGroups[r]}_clone_${s}`);return d}));t.push(...o),cloneRenditionGroups(this.audioTracks,r,a,s),cloneRenditionGroups(this.subtitleTracks,i,a,s)}))}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;let i;this.loader&&this.loader.destroy(),this.loader=new r(t);try{i=new self.URL(e)}catch(d){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==i.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+e)}const s={responseType:"json",url:i.href},n=t.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:(e,t,r,s)=>{this.log(`Loaded steering manifest: "${i}"`);const n=e.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(d){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||r.url),o&&this.clonePathways(o);const c={steeringManifest:n,url:i.toString()};this.hls.trigger(Events.STEERING_MANIFEST_LOADED,c),l&&this.updatePathwayPriority(l)},onError:(e,t,r,i)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,s);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,r)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(s,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;const r=null==(t=this.hls)?void 0:t.media;!r||r.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}}function cloneRenditionGroups(e,t,r,i){e&&Object.keys(t).forEach((s=>{const n=e.filter((e=>e.groupId===s)).map((e=>{const n=_extends({},e);return n.details=void 0,n.attrs=new AttrList(n.attrs),n.url=n.attrs.URI=performUriReplacement(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),n.groupId=n.attrs["GROUP-ID"]=t[s],n.attrs["PATHWAY-ID"]=i,n}));e.push(...n)}))}function performUriReplacement(e,t,r,i){const{HOST:s,PARAMS:n,[r]:a}=i;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach((e=>{e&&l.searchParams.set(e,n[e])})),l.href}const AGE_HEADER_LINE_REGEX=/^age:\s*[\d.]+\s*$/im;class XhrLoader{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new LoadStats,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(!this.stats.aborted)return s(r,t.url)})).catch((e=>(r.open("GET",t.url,!0),s(r,t.url)))).then((()=>{this.stats.aborted||this.openAndSendXhr(r,t,e)})).catch((e=>{this.callbacks.onError({code:r.status,text:e.message},t,r,i)})):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=r.loadPolicy;if(i)for(const a in i)e.setRequestHeader(a,i[a]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=s&&isFiniteNumber(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const i=t.readyState,s=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,n="text"!==t.responseType;if(i>=200&&i<300&&(n&&t.response||null!==t.responseText)){r.loading.end=Math.max(self.performance.now(),r.loading.first);const s=n?t.response:t.responseText,a="arraybuffer"===t.responseType?s.byteLength:s.length;if(r.loaded=r.total=a,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(r,e,s,t),!this.callbacks)return;const l={url:t.responseURL,data:s,code:i};this.callbacks.onSuccess(l,r,e,t)}else{const n=s.loadPolicy.errorRetry;shouldRetry(n,r.retry,!1,{url:e.url,data:void 0,code:i})?this.retry(n):(logger.error(`${i} while loading ${e.url}`),this.callbacks.onError({code:i,text:t.statusText},e,t,r))}}}loadtimeout(){var e;const t=null==(e=this.config)?void 0:e.loadPolicy.timeoutRetry;if(shouldRetry(t,this.stats.retry,!0))this.retry(t);else{var r;logger.warn(`timeout while loading ${null==(r=this.context)?void 0:r.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=getRetryDelay(e,r.retry),r.retry++,logger.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${r.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function fetchSupported(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}const BYTERANGE=/(\d+)-(\d+)\/(\d+)/;class FetchLoader{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||getRequest,this.controller=new self.AbortController,this.stats=new LoadStats}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const s=getRequestParameters(e,this.controller.signal),n=r.onProgress,a="arraybuffer"===e.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=l&&isFiniteNumber(l)?l:d,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),r.onTimeout(i,e,this.response)}),t.timeout),self.fetch(this.request).then((s=>{this.response=this.loader=s;const o=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),r.onTimeout(i,e,this.response)}),d-(o-i.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new FetchError(t||"fetch, bad network response",e,s)}return i.loading.first=o,i.total=getContentLength(s.headers)||i.total,n&&isFiniteNumber(t.highWaterMark)?this.loadProgressively(s,i,e,t.highWaterMark,n):a?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=s[o];l&&(i.loaded=i.total=l);const d={url:a.url,data:s,code:a.status};n&&!isFiniteNumber(t.highWaterMark)&&n(i,e,s,a),r.onSuccess(d,i,e,a)})).catch((t=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const s=t&&t.code||0,n=t?t.message:null;r.onError({code:s,text:n},e,t?t.details:null,i)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,r,i=0,s){const n=new ChunkCache,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&s(t,r,n.flush(),e),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return t.loaded+=d,d<i||n.dataLength?(n.push(l),n.dataLength>=i&&s(t,r,n.flush(),e)):s(t,r,l,e),o()})).catch((()=>Promise.reject()));return o()}}function getRequestParameters(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(_extends({},e.headers))};return e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),r}function getByteRangeLength(e){const t=BYTERANGE.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function getContentLength(e){const t=e.get("Content-Range");if(t){const e=getByteRangeLength(t);if(isFiniteNumber(e))return e}const r=e.get("Content-Length");if(r)return parseInt(r)}function getRequest(e,t){return new self.Request(e.url,t)}class FetchError extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}}const WHITESPACE_CHAR=/\s/,Cues={newCue(e,t,r,i){const s=[];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 e=0;e<n.chars.length;e++)WHITESPACE_CHAR.test(n.chars[e].uchar)&&o?l++:(d+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===r&&(r+=1e-4),l>=16?l--:l++;const i=fixLineBreaks(d.trim()),f=generateCueId(t,r,i);null!=e&&null!=(h=e.cues)&&h.getCueById(f)||(a=new c(t,r,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return e&&s.length&&(s.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),s.forEach((t=>addCueToTrack(e,t)))),s}},defaultLoadPolicy={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},hlsDefaultConfig=_objectSpread2(_objectSpread2({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:AbrController,bufferController:BufferController,capLevelController:CapLevelController,errorController:ErrorController,fpsController:FPSController,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:requestMediaKeySystemAccess,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:defaultLoadPolicy},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},timelineConfig()),{},{subtitleStreamController:SubtitleStreamController,subtitleTrackController:SubtitleTrackController,timelineController:TimelineController,audioStreamController:AudioStreamController,audioTrackController:AudioTrackController,emeController:EMEController,cmcdController:CMCDController,contentSteeringController:ContentSteeringController});function timelineConfig(){return{cueHandler:Cues,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function mergeConfig(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=deepCpy(e),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,n=void 0===t[s],a=[];i.forEach((i=>{const o=`${e}Loading${i}`,l=t[o];if(void 0!==l&&n){a.push(o);const e=r[s].default;switch(t[s]={default:e},i){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&logger.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),_objectSpread2(_objectSpread2({},r),t)}function deepCpy(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(deepCpy):Object.keys(e).reduce(((t,r)=>(t[r]=deepCpy(e[r]),t)),{}):e}function enableStreamingMode(e){const t=e.loader;if(t!==FetchLoader&&t!==XhrLoader)logger.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{fetchSupported()&&(e.loader=FetchLoader,e.progressive=!0,e.enableSoftwareAES=!0,logger.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let chromeOrFirefox;class LevelController extends BasePlaylistController{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const r=this.hls.config.preferManagedMediaSource,i=[],s={},n={};let a=!1,o=!1,l=!1;t.levels.forEach((e=>{var t,d;const c=e.attrs;let{audioCodec:h,videoCodec:u}=e;-1!==(null==(t=h)?void 0:t.indexOf("mp4a.40.34"))&&(chromeOrFirefox||(chromeOrFirefox=/chrome|firefox/i.test(navigator.userAgent)),chromeOrFirefox&&(e.audioCodec=h=void 0)),h&&(e.audioCodec=h=getCodecCompatibleName(h,r)),0===(null==(d=u)?void 0:d.indexOf("avc1"))&&(u=e.videoCodec=convertAVC1ToAVCOTI(u));const{width:f,height:g,unknownCodecs:m}=e;if(a||(a=!(!f||!g)),o||(o=!!u),l||(l=!!h),null!=m&&m.length||h&&!areCodecsMediaSourceSupported(h,"audio",r)||u&&!areCodecsMediaSourceSupported(u,"video",r))return;const{CODECS:p,"FRAME-RATE":y,"HDCP-LEVEL":E,"PATHWAY-ID":v,RESOLUTION:T,"VIDEO-RANGE":S}=c,L=`${`${v||"."}-`}${e.bitrate}-${T}-${y}-${p}-${S}-${E}`;if(s[L])if(s[L].uri===e.url||e.attrs["PATHWAY-ID"])s[L].addGroupId("audio",c.AUDIO),s[L].addGroupId("text",c.SUBTITLES);else{const t=n[L]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const r=new Level(e);s[L]=r,i.push(r)}else{const t=new Level(e);s[L]=t,n[L]=1,i.push(t)}})),this.filterAndSortMediaOptions(i,t,a,o,l)}filterAndSortMediaOptions(e,t,r,i,s){let n=[],a=[],o=e;if((r||i)&&s&&(o=o.filter((({videoCodec:e,videoRange:t,width:r,height:i})=>(!!e||!(!r||!i))&&isVideoRange(t)))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));if(t.audioTracks){const{preferManagedMediaSource:e}=this.hls.config;n=t.audioTracks.filter((t=>!t.audioCodec||areCodecsMediaSourceSupported(t.audioCodec,"audio",e))),assignTrackIdsByGroup(n)}t.subtitles&&(a=t.subtitles,assignTrackIdsByGroup(a));const l=o.slice(0);o.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return VideoRangeValues.indexOf(e.videoRange)-VideoRangeValues.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const r=videoCodecPreferenceValue(e.videoCodec),i=videoCodecPreferenceValue(t.videoCodec);if(r!==i)return i-r}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const r=codecsSetSelectionPreferenceValue(e.codecSet),i=codecsSetSelectionPreferenceValue(t.codecSet);if(r!==i)return i-r}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let d=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let f=0;f<l.length;f++)if(l[f].pathwayId===o[0].pathwayId){d=l[f];break}this._levels=o;for(let f=0;f<o.length;f++)if(o[f]===d){var c;this._firstLevel=f;const e=d.bitrate,t=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${e}`),void 0===(null==(c=this.hls.userConfig)?void 0:c.abrEwmaDefaultEstimate)){const r=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);r>t&&t===hlsDefaultConfig.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=r)}break}const h=s&&!i,u={levels:o,audioTracks:n,subtitleTracks:a,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:i,altAudio:!h&&n.some((e=>!!e.url))};this.hls.trigger(Events.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,i=this.currentLevel,s=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,r===e&&n.details&&i&&s===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${r}${s?" with Pathway "+s:""}`);const o={level:e,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(Events.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==i?void 0:i.details);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){!t.fatal&&t.context&&t.context.type===PlaylistContextType.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===PlaylistLevelType.MAIN){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;const r=this._levels[t.level];null!=r&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var r;const{level:i,details:s}=t,n=this._levels[i];var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));i===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(i,t,n.details)):null!=(r=t.deliveryDirectives)&&r.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,r=this.currentLevel;if(r&&this.shouldLoadPlaylist(r)){let s=r.uri;if(e)try{s=e.addDirectives(s)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}const n=r.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""} with${n?" Pathway "+n:""} ${s}`),this.clearTimer(),this.hls.trigger(Events.LEVEL_LOADING,{url:s,level:t,pathwayId:r.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const r=this._levels.filter(((t,r)=>r!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));reassignFragmentLevelIndexes(r),this._levels=r,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(Events.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function assignTrackIdsByGroup(e){const t={};e.forEach((e=>{const r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}class KeyLoader{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const r in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[r].loader;if(i){var t;if(e&&e!==(null==(t=i.context)?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=ErrorDetails.KEY_LOAD_ERROR,r,i,s){return new LoadError({type:ErrorTypes.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:r,networkDetails:i})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:r,cc:i}=e;for(let e=0;e<t.length;e++){const s=t[e];if(i<=s.cc&&("initSegment"===r||"initSegment"===s.sn||r<s.sn)){this.emeController.selectKeySystemFormat(s).then((e=>{s.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var r,i;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const r=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,r))}const n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(r=a)&&r.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(i=a)&&i.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(r);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,r)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,i=new(0,r.loader)(r);return t.keyLoader=e.loader=i,e.keyLoadPromise=new Promise(((s,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=r.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,r,i)=>{const{frag:a,keyInfo:o,url:l}=r;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,ErrorDetails.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(e,r,i,s)=>{this.resetLoader(r),n(this.createKeyLoadError(t,ErrorDetails.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),i,_objectSpread2({url:a.url,data:void 0},e)))},onTimeout:(e,r,i)=>{this.resetLoader(r),n(this.createKeyLoadError(t,ErrorDetails.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(e,r,i)=>{this.resetLoader(r),n(this.createKeyLoadError(t,ErrorDetails.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,l,d)}))}resetLoader(e){const{frag:t,keyInfo:r,url:i}=e,s=r.loader;t.keyLoader===s&&(t.keyLoader=null,r.loader=null),delete this.keyUriToKeyInfo[i],s&&s.destroy()}}function getSourceBuffer(){return self.SourceBuffer||self.WebKitSourceBuffer}function isMSESupported(){if(!getMediaSource())return!1;const e=getSourceBuffer();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function isSupported(){if(!isMSESupported())return!1;const e=getMediaSource();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(mimeTypeForCodec(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(mimeTypeForCodec(t,"audio")))))}function changeTypeSupported(){var e;const t=getSourceBuffer();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}const STALL_MINIMUM_DURATION_MS=250,MAX_START_GAP_JUMP=2,SKIP_BUFFER_HOLE_STEP_SECONDS=.1,SKIP_BUFFER_RANGE_START=.05;class GapController{constructor(e,t,r,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=r,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:r,media:i,stalled:s}=this;if(null===i)return;const{currentTime:n,seeking:a}=i,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==e){if(this.moved=!0,a||(this.nudgeRetry=0),null!==s){if(this.stallReported){const e=self.performance.now()-s;logger.warn(`playback not stuck anymore @${n}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(i.paused&&!a||i.ended||0===i.playbackRate||!BufferHelper.getBuffered(i).length)return void(this.nudgeRetry=0);const d=BufferHelper.bufferInfo(i,n,0),c=d.nextStart||0;if(a){const e=d.len>MAX_START_GAP_JUMP,r=!c||t&&t.start<=n||c-n>MAX_START_GAP_JUMP&&!this.fragmentTracker.getPartialFragment(n);if(e||r)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var h;if(!(d.len>0)&&!c)return;const e=Math.max(c,d.start||0)-n,t=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,r=(null==t||null==(h=t.details)?void 0:h.live)?2*t.details.targetduration:MAX_START_GAP_JUMP,s=this.fragmentTracker.getPartialFragment(n);if(e>0&&(e<=r||s))return void(i.paused||this._trySkipBufferHole(s))}const u=self.performance.now();if(null===s)return void(this.stalled=u);const f=u-s;if(!a&&f>=STALL_MINIMUM_DURATION_MS&&(this._reportStall(d),!this.media))return;const g=BufferHelper.bufferInfo(i,n,r.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(e,t){const{config:r,fragmentTracker:i,media:s}=this;if(null===s)return;const n=s.currentTime,a=i.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(e.len>r.maxBufferHole||e.nextStart&&e.nextStart-n<r.maxBufferHole)&&t>1e3*r.highBufferWatchdogPeriod&&(logger.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:r,stallReported:i}=this;if(!i&&r){this.stallReported=!0;const i=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${JSON.stringify(e)})`);logger.warn(i.message),t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:r,media:i}=this;if(null===i)return 0;const s=i.currentTime,n=BufferHelper.bufferInfo(i,s,0),a=s<n.start?n.start:n.nextStart;if(a){const o=n.len<=t.maxBufferHole,l=n.len>0&&n.len<1&&i.readyState<3,d=a-s;if(d>0&&(o||l)){if(d>t.maxBufferHole){const{fragmentTracker:t}=this;let r=!1;if(0===s){const e=t.getAppendedFrag(0,PlaylistLevelType.MAIN);e&&a<e.end&&(r=!0)}if(!r){const r=e||t.getAppendedFrag(s,PlaylistLevelType.MAIN);if(r){let e=!1,i=r.end;for(;i<a;){const r=t.getPartialFragment(i);if(!r){e=!0;break}i+=r.duration}if(e)return 0}}}const n=Math.max(a+SKIP_BUFFER_RANGE_START,s+SKIP_BUFFER_HOLE_STEP_SECONDS);if(logger.warn(`skipping hole, adjusting currentTime from ${s} to ${n}`),this.moved=!0,this.stalled=null,i.currentTime=n,e&&!e.gap){const t=new Error(`fragment loaded with buffer holes, seeking from ${s} to ${n}`);r.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:t,reason:t.message,frag:e})}return n}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:r,nudgeRetry:i}=this;if(null===r)return;const s=r.currentTime;if(this.nudgeRetry++,i<e.nudgeMaxRetry){const n=s+(i+1)*e.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${s} to ${n}`);logger.warn(a.message),r.currentTime=n,t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const r=new Error(`Playhead still not moving while enough data buffered @${s} after ${e.nudgeMaxRetry} nudges`);logger.error(r.message),t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,error:r,fatal:!0})}}}const TICK_INTERVAL=100;class StreamController extends BaseStreamController{constructor(e,t,r){super(e,t,r,"[stream-controller]",PlaylistLevelType.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Events.ERROR,this.onError,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Events.ERROR,this.onError,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:r}=this;if(this.stopLoad(),this.setInterval(TICK_INTERVAL),this.level=-1,!this.startFragRequested){let e=r.startLevel;-1===e&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this.loadedmetadata=!1}t>0&&-1===e&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=State.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=State.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case State.WAITING_LEVEL:{const{levels:e,level:t}=this,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(i))break;this.state=State.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=State.IDLE;break}break}case State.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),r=this.retryDate;if(!r||t>=r||null!=(e=this.media)&&e.seeking){const{levels:e,level:t}=this,r=null==e?void 0:e[t];this.resetStartWhenNotLoaded(r||null),this.state=State.IDLE}}}this.state===State.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:i}=this;if(null===t||!i&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=e.nextLoadLevel;if(null==r||!r[s])return;const n=r[s],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return this.altAudio&&(e.type="video"),this.hls.trigger(Events.BUFFER_EOS,e),void(this.state=State.ENDED)}e.loadLevel!==s&&-1===e.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const l=n.details;if(!l||this.state===State.WAITING_LEVEL||l.live&&this.levelLastLoaded!==n)return this.level=s,void(this.state=State.WAITING_LEVEL);const d=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&"initSegment"!==u.sn&&this.fragmentTracker.getState(u)!==FragmentState.OK){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,h)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?ElementaryStreamTypes.AUDIO:ElementaryStreamTypes.VIDEO,t=(e===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,PlaylistLevelType.MAIN)}u=this.getNextFragmentLoopLoading(u,l,a,PlaylistLevelType.MAIN,c)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,h))}loadFragment(e,t,r){const i=this.fragmentTracker.getState(e);this.fragCurrent=e,i===FragmentState.NOT_LOADED||i===FragmentState.PARTIAL?"initSegment"===e.sn?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,r)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,PlaylistLevelType.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let r;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],i=this.fragLastKbps;r=i&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*i)+1:0}else r=0;const n=this.getBufferedFrag(t.currentTime+r);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,r=e.duration,i=Math.max(n.end,t+Math.min(Math.max(r-this.config.maxFragLookUpTolerance,r*(this.couldBacktrack?.5:.125)),r*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case State.KEY_LOADING:case State.FRAG_LOADING:case State.FRAG_LOADING_WAITING_RETRY:case State.PARSING:case State.PARSED:this.state=State.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),r.addEventListener("playing",this.onvplaying),r.addEventListener("seeked",this.onvseeked),this.gapController=new GapController(this.config,r,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;isFiniteNumber(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const r=this.getMainFwdBufferInfo();null!==r&&0!==r.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${r?r.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(Events.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let r=!1,i=!1;t.levels.forEach((e=>{const t=e.audioCodec;t&&(r=r||-1!==t.indexOf("mp4a.40.2"),i=i||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=r&&i&&!changeTypeSupported(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:r}=this;if(!r||this.state!==State.IDLE)return;const i=r[t.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=State.WAITING_LEVEL)}onLevelLoaded(e,t){var r;const{levels:i}=this,s=t.level,n=t.details,a=n.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${a}`);const o=i[s],l=this.fragCurrent;!l||this.state!==State.FRAG_LOADING&&this.state!==State.FRAG_LOADING_WAITING_RETRY||l.level!==t.level&&l.loader&&this.abortCurrentFrag();let d=0;if(n.live||null!=(r=o.details)&&r.live){var c;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;d=this.alignPlaylists(n,o.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(Events.LEVEL_UPDATED,{details:n,level:s}),this.state===State.WAITING_LEVEL){if(this.waitForCdnTuneIn(n))return;this.state=State.IDLE}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,d),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:r,part:i,payload:s}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const a=n[r.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),void this.fragmentTracker.removeFragment(r);const l=a.videoCodec,d=o.PTSKnown||!o.live,c=null==(t=r.initSegment)?void 0:t.data,h=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,m=new ChunkMetadata(r.level,r.sn,r.stats.chunkCount,s.byteLength,f,g),p=this.initPTS[r.cc];u.push(s,c,h,l,r,i,o.totalduration,d,m,p)}onAudioTrackSwitching(e,t){const r=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const e=this.hls;r&&(e.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(Events.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=t.id,i=!!this.hls.audioTracks[r].url;if(i){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=i,this.tick()}onBufferCreated(e,t){const r=t.tracks;let i,s,n=!1;for(const a in r){const e=r[a];if("main"===e.id){if(s=a,i=e,"video"===a){const e=r[a];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:i}=t;if(r&&r.type!==PlaylistLevelType.MAIN)return;if(this.fragContextChanged(r))return this.warn(`Fragment ${r.sn}${i?" p: "+i.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===State.PARSED&&(this.state=State.IDLE));const s=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}onError(e,t){var r;if(t.fatal)this.state=State.ERROR;else switch(t.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN,t);break;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==State.WAITING_LEVEL||(null==(r=t.context)?void 0:r.type)!==PlaylistContextType.LEVEL||(this.state=State.IDLE);break;case ErrorDetails.BUFFER_APPEND_ERROR:case ErrorDetails.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;if(t.details===ErrorDetails.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!BufferHelper.getBuffered(e).length){const e=this.state!==State.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=State.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ElementaryStreamTypes.AUDIO||this.audioOnly&&!this.altAudio){const e=(t===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,PlaylistLevelType.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log(`could not seek to ${r}, already seeking at ${t}`);const i=BufferHelper.getBuffered(e),s=(i.length?i.start(0):0)-r;s>0&&(s<this.config.maxBufferHole||s<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${s} to match buffer start`),r+=s,this.startPosition=r),this.log(`seek to target start position ${r} from current time ${t}`),e.currentTime=r}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((r=>{const{hls:i}=this;if(!r||this.fragContextChanged(e))return;t.fragmentError=0,this.state=State.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),i.trigger(Events.FRAG_LOADED,r),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const r="main",{hls:i}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{video:c,text:h,id3:u,initSegment:f}=s,{details:g}=d,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=State.PARSING,f){if(null!=f&&f.tracks){const e=o.initSegment||o;this._bufferInitSegment(d,f.tracks,e,n),i.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;isFiniteNumber(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},i.trigger(Events.INIT_PTS_FOUND,{frag:o,id:r,initPTS:e,timescale:t}))}if(c&&g&&"initSegment"!==o.sn){const e=g.fragments[o.sn-1-g.startSN],t=o.sn===g.startSN,r=!e||o.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:i,startDTS:s,endDTS:a}=c;if(l)l.elementaryStreams[c.type]={startPTS:e,endPTS:i,startDTS:s,endDTS:a};else if(c.firstKeyFrame&&c.independent&&1===n.id&&!r&&(this.couldBacktrack=!0),c.dropped&&c.independent){const s=this.getMainFwdBufferInfo(),n=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=c.firstKeyFramePTS?c.firstKeyFramePTS:e;if(!t&&n<l-this.config.maxBufferHole&&!r)return void this.backtrack(o);r&&(o.gap=!0),o.setElementaryStreamInfo(c.type,o.start,i,o.start,a,!0)}else t&&e>MAX_START_GAP_JUMP&&(o.gap=!0);o.setElementaryStreamInfo(c.type,e,i,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,l,n,t||r)}else{if(!t&&!r)return void this.backtrack(o);o.gap=!0}}if(m){const{startPTS:e,endPTS:t,startDTS:r,endDTS:i}=m;l&&(l.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:e,endPTS:t,startDTS:r,endDTS:i}),o.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,e,t,r,i),this.bufferFragmentData(m,o,l,n)}if(g&&null!=u&&null!=(t=u.samples)&&t.length){const e={id:r,frag:o,details:g,samples:u.samples};i.trigger(Events.FRAG_PARSING_METADATA,e)}if(g&&h){const e={id:r,frag:o,details:g,samples:h.samples};i.trigger(Events.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,r,i){if(this.state!==State.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:s,video:n,audiovideo:a}=t;if(s){let t=e.audioCodec;const r=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==s.metadata.channelCount&&-1===r.indexOf("firefox")&&(t="mp4a.40.5")),t&&-1!==t.indexOf("mp4a.40.5")&&-1!==r.indexOf("android")&&"audio/mpeg"!==s.container&&(t="mp4a.40.2",this.log(`Android: force audio codec to ${t}`)),e.audioCodec&&e.audioCodec!==t&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${t}"`),s.levelCodec=t,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${t||""}/${e.audioCodec||""}/${s.codec}]`)}n&&(n.levelCodec=e.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),this.hls.trigger(Events.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(Events.BUFFER_APPENDING,{type:e,data:s,frag:r,part:null,chunkMeta:i,parent:r.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,PlaylistLevelType.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=State.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const r=e.currentTime;if(BufferHelper.isBuffered(e,r)?t=this.getAppendedFrag(r):BufferHelper.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,r=t.level;e&&t.sn===e.sn&&e.level===r||(this.fragPlaying=t,this.hls.trigger(Events.FRAG_CHANGED,{frag:t}),e&&e.level===r||this.hls.trigger(Events.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,r=this.currentFrag;if(r&&isFiniteNumber(t)&&isFiniteNumber(r.programDateTime)){const e=r.programDateTime+1e3*(t-r.start);return new Date(e)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Hls{static get version(){return"1.5.7"}static isMSESupported(){return isMSESupported()}static isSupported(){return isSupported()}static getMediaSource(){return getMediaSource()}static get Events(){return Events}static get ErrorTypes(){return ErrorTypes}static get ErrorDetails(){return ErrorDetails}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:hlsDefaultConfig}static set DefaultConfig(e){Hls.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new EventEmitter,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,enableLogs(e.debug||!1,"Hls instance");const t=this.config=mergeConfig(Hls.DefaultConfig,e);this.userConfig=e,t.progressive&&enableStreamingMode(t);const{abrController:r,bufferController:i,capLevelController:s,errorController:n,fpsController:a}=t,o=new n(this),l=this.abrController=new r(this),d=this.bufferController=new i(this),c=this.capLevelController=new s(this),h=new a(this),u=new PlaylistLoader(this),f=new ID3TrackController(this),g=t.contentSteeringController,m=g?new g(this):null,p=this.levelController=new LevelController(this,m),y=new FragmentTracker(this),E=new KeyLoader(this.config),v=this.streamController=new StreamController(this,y,E);c.setStreamController(v),h.setStreamController(v);const T=[u,p,v];m&&T.splice(1,0,m),this.networkControllers=T;const S=[l,d,c,h,f,y];this.audioTrackController=this.createController(t.audioTrackController,T);const L=t.audioStreamController;L&&T.push(new L(this,y,E)),this.subtitleTrackController=this.createController(t.subtitleTrackController,T);const A=t.subtitleStreamController;A&&T.push(new A(this,y,E)),this.createController(t.timelineController,S),E.emeController=this.emeController=this.createController(t.emeController,S),this.cmcdController=this.createController(t.cmcdController,S),this.latencyController=this.createController(LatencyController,S),this.coreComponents=S,T.push(o);const b=o.onErrorOut;"function"==typeof b&&this.on(Events.ERROR,b,o)}createController(e,t){if(e){const r=new e(this);return t&&t.push(r),r}return null}on(e,t,r=this){this._emitter.on(e,t,r)}once(e,t,r=this){this._emitter.once(e,t,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,r=this,i){this._emitter.off(e,t,r,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,r){return this._emitter.emit(e,t,r)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(r){if(logger.error("An internal error happened while handling event "+e+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const t=e===Events.ERROR;this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:t,event:e,error:r}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){logger.log("destroy"),this.trigger(Events.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){logger.log("attachMedia"),this._media=e,this.trigger(Events.MEDIA_ATTACHING,{media:e})}detachMedia(){logger.log("detachMedia"),this.trigger(Events.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,r=this.url,i=this.url=urlToolkitExports.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,logger.log(`loadSource:${i}`),t&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Events.MANIFEST_LOADING,{url:e})}startLoad(e=-1){logger.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){logger.log("stopLoad"),this.started=!1,this.networkControllers.forEach((e=>{e.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((e=>{"fragmentLoader"in e&&e.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((e=>{"fragmentLoader"in e&&e.stopLoad()}))}swapAudioCodec(){logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){logger.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){isHdcpLevel(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const r=e.length;for(let i=0;i<r;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:r}=this;let i;if(i=-1===t&&null!=e&&e.length?e.length-1:t,r)for(let s=i;s--;){const t=e[s].attrs["HDCP-LEVEL"];if(t&&t<=r)return s}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return null==(t=this.audioTrackController)?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return null==(t=this.subtitleTrackController)||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Hls.defaultConfig=void 0;const _hoisted_1={style:{"text-align":"center","font-size":"2em","padding-top":"20px"}},_hoisted_2={style:{"text-align":"center"}},_hoisted_3=createBaseVNode("div",{style:{"text-align":"center",margin:"30px"}},[createBaseVNode("div",{id:"mui-player",style:{margin:"auto"}})],-1);var _sfc_main=defineComponent({setup(e){const t=useRouter(),r=useMessage(),i=ref(),s=ref({});onMounted((()=>{i.value=t.currentRoute.value.query.id,n()}));const n=()=>{broadcastInfo({id:i.value}).then((e=>{var t,i;200==e.code?(console.log(e),s.value=e.data,t=e.data.live_address,i=e.data.type,new MuiPlayer(1==i?{container:"#mui-player",src:t,width:"50%",height:"500px",autoFit:!1,autoplay:!0,live:!0,parse:{type:"hls",loader:Hls,config:{debug:!1}}}:{container:"#mui-player",src:t,width:"50%",height:"500px",autoFit:!1,live:!1,autoplay:!0})):r.error(e.msg)}))};return(e,t)=>(openBlock(),createElementBlock(Fragment$1,null,[createVNode(_sfc_main$1),createBaseVNode("div",_hoisted_1,toDisplayString(s.value.title),1),createBaseVNode("div",_hoisted_2,toDisplayString(s.value.title_short),1),_hoisted_3,createVNode(Footer)],64))}});export{_sfc_main as default};