Autoría | Ultima modificación | Ver Log |
/**
* @license
* Video.js 8.10.0 <http://videojs.com/>
* Copyright Brightcove, Inc. <https://www.brightcove.com/>
* Available under Apache License Version 2.0
* <https://github.com/videojs/video.js/blob/main/LICENSE>
*
* Includes vtt.js <https://github.com/mozilla/vtt.js>
* Available under Apache License Version 2.0
* <https://github.com/mozilla/vtt.js/blob/main/LICENSE>
*/
!function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define("media_videojs/video-lazy",factory):(global="undefined"!=typeof globalThis?globalThis:global||self).videojs=factory()}(window,(function(){const hooks_={},hooks=function(type,fn){return hooks_[type]=hooks_[type]||[],fn&&(hooks_[type]=hooks_[type].concat(fn)),hooks_[type]},removeHook=function(type,fn){const index=hooks(type).indexOf(fn);return!(index<=-1)&&(hooks_[type]=hooks_[type].slice(),hooks_[type].splice(index,1),!0)},FullscreenApi={prefixed:!0},apiMap=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror","fullscreen"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"]],specApi=apiMap[0];let browserApi;for(let i=0;i<apiMap.length;i++)if(apiMap[i][1]in document){browserApi=apiM
ap[i];break}if(browserApi){for(let i=0;i<browserApi.length;i++)FullscreenApi[specApi[i]]=browserApi[i];FullscreenApi.prefixed=browserApi[0]!==specApi[0]}let history=[];const LogByTypeFactory=(name,log,styles)=>(type,level,args)=>{const lvl=log.levels[level],lvlRegExp=new RegExp("^(".concat(lvl,")$"));let resultName=name;if("log"!==type&&args.unshift(type.toUpperCase()+":"),styles&&(resultName="%c".concat(name),args.unshift(styles)),args.unshift(resultName+":"),history){history.push([].concat(args));const splice=history.length-1e3;history.splice(0,splice>0?splice:0)}if(!window.console)return;let fn=window.console[type];fn||"debug"!==type||(fn=window.console.info||window.console.log),fn&&lvl&&lvlRegExp.test(type)&&fn[Array.isArray(args)?"apply":"call"](window.console,args)};const log$1=function createLogger$1(name){let logByType,delimiter=arguments.length>1&&void 0!==arguments[1]?arguments[1]:":",styles=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",level="info";const log=function(){for(var _len2=ar
guments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++)args[_key2]=arguments[_key2];logByType("log",level,args)};return logByType=LogByTypeFactory(name,log,styles),log.createLogger=(subName,subDelimiter,subStyles)=>{const resultDelimiter=void 0!==subDelimiter?subDelimiter:delimiter,resultStyles=void 0!==subStyles?subStyles:styles;return createLogger$1("".concat(name," ").concat(resultDelimiter," ").concat(subName),resultDelimiter,resultStyles)},log.createNewLogger=(newName,newDelimiter,newStyles)=>createLogger$1(newName,newDelimiter,newStyles),log.levels={all:"debug|log|warn|error",off:"",debug:"debug|log|warn|error",info:"log|warn|error",warn:"warn|error",error:"error",DEFAULT:level},log.level=lvl=>{if("string"==typeof lvl){if(!log.levels.hasOwnProperty(lvl))throw new Error('"'.concat(lvl,'" in not a valid log level'));level=lvl}return level},log.history=()=>history?[].concat(history):[],log.history.filter=fname=>(history||[]).filter((historyItem=>new RegExp(".*".concat(fname,".*")).test(historyIt
em[0]))),log.history.clear=()=>{history&&(history.length=0)},log.history.disable=()=>{null!==history&&(history.length=0,history=null)},log.history.enable=()=>{null===history&&(history=[])},log.error=function(){for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++)args[_key3]=arguments[_key3];return logByType("error",level,args)},log.warn=function(){for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++)args[_key4]=arguments[_key4];return logByType("warn",level,args)},log.debug=function(){for(var _len5=arguments.length,args=new Array(_len5),_key5=0;_key5<_len5;_key5++)args[_key5]=arguments[_key5];return logByType("debug",level,args)},log}("VIDEOJS"),createLogger=log$1.createLogger,toString$1=Object.prototype.toString,keys=function(object){return isObject$1(object)?Object.keys(object):[]};function each(object,fn){keys(object).forEach((key=>fn(object[key],key)))}function reduce(object,fn){let initial=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;re
turn keys(object).reduce(((accum,key)=>fn(accum,object[key],key)),initial)}function isObject$1(value){return!!value&&"object"==typeof value}function isPlain(value){return isObject$1(value)&&"[object Object]"===toString$1.call(value)&&value.constructor===Object}function merge$2(){const result={};for(var _len6=arguments.length,sources=new Array(_len6),_key6=0;_key6<_len6;_key6++)sources[_key6]=arguments[_key6];return sources.forEach((source=>{source&&each(source,((value,key)=>{isPlain(value)?(isPlain(result[key])||(result[key]={}),result[key]=merge$2(result[key],value)):result[key]=value}))})),result}function values$1(){let source=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const result=[];for(const key in source)if(source.hasOwnProperty(key)){const value=source[key];result.push(value)}return result}function defineLazyProperty(obj,key,getValue){let setter=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];const set=value=>Object.defineProperty(obj,key,{value:value,enumerable:!0,writable:!
0}),options={configurable:!0,enumerable:!0,get(){const value=getValue();return set(value),value}};return setter&&(options.set=set),Object.defineProperty(obj,key,options)}var Obj=Object.freeze({__proto__:null,each:each,reduce:reduce,isObject:isObject$1,isPlain:isPlain,merge:merge$2,values:values$1,defineLazyProperty:defineLazyProperty});let ANDROID_VERSION,IS_IPOD=!1,IOS_VERSION=null,IS_ANDROID=!1,IS_FIREFOX=!1,IS_EDGE=!1,IS_CHROMIUM=!1,IS_CHROME=!1,CHROMIUM_VERSION=null,CHROME_VERSION=null,IE_VERSION=null,IS_SAFARI=!1,IS_WINDOWS=!1,IS_IPAD=!1,IS_IPHONE=!1;const TOUCH_ENABLED=Boolean(isReal()&&("ontouchstart"in window||window.navigator.maxTouchPoints||window.DocumentTouch&&window.document instanceof window.DocumentTouch)),UAD=window.navigator&&window.navigator.userAgentData;if(UAD&&UAD.platform&&UAD.brands&&(IS_ANDROID="Android"===UAD.platform,IS_EDGE=Boolean(UAD.brands.find((b=>"Microsoft Edge"===b.brand))),IS_CHROMIUM=Boolean(UAD.brands.find((b=>"Chromium"===b.brand))),IS_CHROME=!IS_EDGE&&IS_CHROMIUM,CHROMI
UM_VERSION=CHROME_VERSION=(UAD.brands.find((b=>"Chromium"===b.brand))||{}).version||null,IS_WINDOWS="Windows"===UAD.platform),!IS_CHROMIUM){const USER_AGENT=window.navigator&&window.navigator.userAgent||"";IS_IPOD=/iPod/i.test(USER_AGENT),IOS_VERSION=function(){const match=USER_AGENT.match(/OS (\d+)_/i);return match&&match[1]?match[1]:null}(),IS_ANDROID=/Android/i.test(USER_AGENT),ANDROID_VERSION=function(){const match=USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!match)return null;const major=match[1]&&parseFloat(match[1]),minor=match[2]&&parseFloat(match[2]);return major&&minor?parseFloat(match[1]+"."+match[2]):major||null}(),IS_FIREFOX=/Firefox/i.test(USER_AGENT),IS_EDGE=/Edg/i.test(USER_AGENT),IS_CHROMIUM=/Chrome/i.test(USER_AGENT)||/CriOS/i.test(USER_AGENT),IS_CHROME=!IS_EDGE&&IS_CHROMIUM,CHROMIUM_VERSION=CHROME_VERSION=function(){const match=USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);return match&&match[2]?parseFloat(match[2]):null}(),IE_VERSION=function(){const result=/MSIE\s(\d+)\.\d/
.exec(USER_AGENT);let version=result&&parseFloat(result[1]);return!version&&/Trident\/7.0/i.test(USER_AGENT)&&/rv:11.0/.test(USER_AGENT)&&(version=11),version}(),IS_SAFARI=/Safari/i.test(USER_AGENT)&&!IS_CHROME&&!IS_ANDROID&&!IS_EDGE,IS_WINDOWS=/Windows/i.test(USER_AGENT),IS_IPAD=/iPad/i.test(USER_AGENT)||IS_SAFARI&&TOUCH_ENABLED&&!/iPhone/i.test(USER_AGENT),IS_IPHONE=/iPhone/i.test(USER_AGENT)&&!IS_IPAD}const IS_IOS=IS_IPHONE||IS_IPAD||IS_IPOD,IS_ANY_SAFARI=(IS_SAFARI||IS_IOS)&&!IS_CHROME;var browser=Object.freeze({__proto__:null,get IS_IPOD(){return IS_IPOD},get IOS_VERSION(){return IOS_VERSION},get IS_ANDROID(){return IS_ANDROID},get ANDROID_VERSION(){return ANDROID_VERSION},get IS_FIREFOX(){return IS_FIREFOX},get IS_EDGE(){return IS_EDGE},get IS_CHROMIUM(){return IS_CHROMIUM},get IS_CHROME(){return IS_CHROME},get CHROMIUM_VERSION(){return CHROMIUM_VERSION},get CHROME_VERSION(){return CHROME_VERSION},get IE_VERSION(){return IE_VERSION},get IS_SAFARI(){return IS_SAFARI},get IS_WINDOWS(){return IS_WINDOWS},
get IS_IPAD(){return IS_IPAD},get IS_IPHONE(){return IS_IPHONE},TOUCH_ENABLED:TOUCH_ENABLED,IS_IOS:IS_IOS,IS_ANY_SAFARI:IS_ANY_SAFARI});function isNonBlankString(str){return"string"==typeof str&&Boolean(str.trim())}function isReal(){return document===window.document}function isEl(value){return isObject$1(value)&&1===value.nodeType}function isInFrame(){try{return window.parent!==window.self}catch(x){return!0}}function createQuerier(method){return function(selector,context){if(!isNonBlankString(selector))return document[method](null);isNonBlankString(context)&&(context=document.querySelector(context));const ctx=isEl(context)?context:document;return ctx[method]&&ctx[method](selector)}}function createEl(){let tagName=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"div",properties=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},attributes=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},content=arguments.length>3?arguments[3]:void 0;const el=document.createElement(tagName);return Object
.getOwnPropertyNames(properties).forEach((function(propName){const val=properties[propName];"textContent"===propName?textContent(el,val):el[propName]===val&&"tabIndex"!==propName||(el[propName]=val)})),Object.getOwnPropertyNames(attributes).forEach((function(attrName){el.setAttribute(attrName,attributes[attrName])})),content&&appendContent(el,content),el}function textContent(el,text){return void 0===el.textContent?el.innerText=text:el.textContent=text,el}function prependTo(child,parent){parent.firstChild?parent.insertBefore(child,parent.firstChild):parent.appendChild(child)}function hasClass(element,classToCheck){return function(str){if(str.indexOf(" ")>=0)throw new Error("class has illegal whitespace characters")}(classToCheck),element.classList.contains(classToCheck)}function addClass(element){for(var _len7=arguments.length,classesToAdd=new Array(_len7>1?_len7-1:0),_key7=1;_key7<_len7;_key7++)classesToAdd[_key7-1]=arguments[_key7];return element.classList.add(...classesToAdd.reduce(((prev,current)=>prev.co
ncat(current.split(/\s+/))),[])),element}function removeClass(element){if(!element)return log$1.warn("removeClass was called with an element that doesn't exist"),null;for(var _len8=arguments.length,classesToRemove=new Array(_len8>1?_len8-1:0),_key8=1;_key8<_len8;_key8++)classesToRemove[_key8-1]=arguments[_key8];return element.classList.remove(...classesToRemove.reduce(((prev,current)=>prev.concat(current.split(/\s+/))),[])),element}function toggleClass(element,classToToggle,predicate){return"function"==typeof predicate&&(predicate=predicate(element,classToToggle)),"boolean"!=typeof predicate&&(predicate=void 0),classToToggle.split(/\s+/).forEach((className=>element.classList.toggle(className,predicate))),element}function setAttributes(el,attributes){Object.getOwnPropertyNames(attributes).forEach((function(attrName){const attrValue=attributes[attrName];null==attrValue||!1===attrValue?el.removeAttribute(attrName):el.setAttribute(attrName,!0===attrValue?"":attrValue)}))}function getAttributes(tag){const obj={},
knownBooleans=["autoplay","controls","playsinline","loop","muted","default","defaultMuted"];if(tag&&tag.attributes&&tag.attributes.length>0){const attrs=tag.attributes;for(let i=attrs.length-1;i>=0;i--){const attrName=attrs[i].name;let attrVal=attrs[i].value;knownBooleans.includes(attrName)&&(attrVal=null!==attrVal),obj[attrName]=attrVal}}return obj}function getAttribute(el,attribute){return el.getAttribute(attribute)}function setAttribute(el,attribute,value){el.setAttribute(attribute,value)}function removeAttribute(el,attribute){el.removeAttribute(attribute)}function blockTextSelection(){document.body.focus(),document.onselectstart=function(){return!1}}function unblockTextSelection(){document.onselectstart=function(){return!0}}function getBoundingClientRect(el){if(el&&el.getBoundingClientRect&&el.parentNode){const rect=el.getBoundingClientRect(),result={};return["bottom","height","left","right","top","width"].forEach((k=>{void 0!==rect[k]&&(result[k]=rect[k])})),result.height||(result.height=parseFloat(comp
utedStyle(el,"height"))),result.width||(result.width=parseFloat(computedStyle(el,"width"))),result}}function findPosition(el){if(!el||el&&!el.offsetParent)return{left:0,top:0,width:0,height:0};const width=el.offsetWidth,height=el.offsetHeight;let left=0,top=0;for(;el.offsetParent&&el!==document[FullscreenApi.fullscreenElement];)left+=el.offsetLeft,top+=el.offsetTop,el=el.offsetParent;return{left:left,top:top,width:width,height:height}}function getPointerPosition(el,event){const translated={x:0,y:0};if(IS_IOS){let item=el;for(;item&&"html"!==item.nodeName.toLowerCase();){const transform=computedStyle(item,"transform");if(/^matrix/.test(transform)){const values=transform.slice(7,-1).split(/,\s/).map(Number);translated.x+=values[4],translated.y+=values[5]}else if(/^matrix3d/.test(transform)){const values=transform.slice(9,-1).split(/,\s/).map(Number);translated.x+=values[12],translated.y+=values[13]}item=item.parentNode}}const position={},boxTarget=findPosition(event.target),box=findPosition(el),boxW=box.width,
boxH=box.height;let offsetY=event.offsetY-(box.top-boxTarget.top),offsetX=event.offsetX-(box.left-boxTarget.left);return event.changedTouches&&(offsetX=event.changedTouches[0].pageX-box.left,offsetY=event.changedTouches[0].pageY+box.top,IS_IOS&&(offsetX-=translated.x,offsetY-=translated.y)),position.y=1-Math.max(0,Math.min(1,offsetY/boxH)),position.x=Math.max(0,Math.min(1,offsetX/boxW)),position}function isTextNode$1(value){return isObject$1(value)&&3===value.nodeType}function emptyEl(el){for(;el.firstChild;)el.removeChild(el.firstChild);return el}function normalizeContent(content){return"function"==typeof content&&(content=content()),(Array.isArray(content)?content:[content]).map((value=>("function"==typeof value&&(value=value()),isEl(value)||isTextNode$1(value)?value:"string"==typeof value&&/\S/.test(value)?document.createTextNode(value):void 0))).filter((value=>value))}function appendContent(el,content){return normalizeContent(content).forEach((node=>el.appendChild(node))),el}function insertContent(el,con
tent){return appendContent(emptyEl(el),content)}function isSingleLeftClick(event){return void 0===event.button&&void 0===event.buttons||(0===event.button&&void 0===event.buttons||("mouseup"===event.type&&0===event.button&&0===event.buttons||0===event.button&&1===event.buttons))}const $=createQuerier("querySelector"),$$=createQuerier("querySelectorAll");function computedStyle(el,prop){if(!el||!prop)return"";if("function"==typeof window.getComputedStyle){let computedStyleValue;try{computedStyleValue=window.getComputedStyle(el)}catch(e){return""}return computedStyleValue?computedStyleValue.getPropertyValue(prop)||computedStyleValue[prop]:""}return""}function copyStyleSheetsToWindow(win){[...document.styleSheets].forEach((styleSheet=>{try{const cssRules=[...styleSheet.cssRules].map((rule=>rule.cssText)).join(""),style=document.createElement("style");style.textContent=cssRules,win.document.head.appendChild(style)}catch(e){const link=document.createElement("link");link.rel="stylesheet",link.type=styleSheet.type,li
nk.media=styleSheet.media.mediaText,link.href=styleSheet.href,win.document.head.appendChild(link)}}))}var Dom=Object.freeze({__proto__:null,isReal:isReal,isEl:isEl,isInFrame:isInFrame,createEl:createEl,textContent:textContent,prependTo:prependTo,hasClass:hasClass,addClass:addClass,removeClass:removeClass,toggleClass:toggleClass,setAttributes:setAttributes,getAttributes:getAttributes,getAttribute:getAttribute,setAttribute:setAttribute,removeAttribute:removeAttribute,blockTextSelection:blockTextSelection,unblockTextSelection:unblockTextSelection,getBoundingClientRect:getBoundingClientRect,findPosition:findPosition,getPointerPosition:getPointerPosition,isTextNode:isTextNode$1,emptyEl:emptyEl,normalizeContent:normalizeContent,appendContent:appendContent,insertContent:insertContent,isSingleLeftClick:isSingleLeftClick,$:$,$$:$$,computedStyle:computedStyle,copyStyleSheetsToWindow:copyStyleSheetsToWindow});let videojs$1,_windowLoaded=!1;const autoSetup=function(){if(!1===videojs$1.options.autoSetup)return;const vids
=Array.prototype.slice.call(document.getElementsByTagName("video")),audios=Array.prototype.slice.call(document.getElementsByTagName("audio")),divs=Array.prototype.slice.call(document.getElementsByTagName("video-js")),mediaEls=vids.concat(audios,divs);if(mediaEls&&mediaEls.length>0)for(let i=0,e=mediaEls.length;i<e;i++){const mediaEl=mediaEls[i];if(!mediaEl||!mediaEl.getAttribute){autoSetupTimeout(1);break}if(void 0===mediaEl.player){null!==mediaEl.getAttribute("data-setup")&&videojs$1(mediaEl)}}else _windowLoaded||autoSetupTimeout(1)};function autoSetupTimeout(wait,vjs){isReal()&&(vjs&&(videojs$1=vjs),window.setTimeout(autoSetup,wait))}function setWindowLoaded(){_windowLoaded=!0,window.removeEventListener("load",setWindowLoaded)}isReal()&&("complete"===document.readyState?setWindowLoaded():window.addEventListener("load",setWindowLoaded));const createStyleElement=function(className){const style=document.createElement("style");return style.className=className,style},setTextContent=function(el,content){el.style
Sheet?el.styleSheet.cssText=content:el.textContent=content};var DomData=new WeakMap;let _supportsPassive,_guid=3;function newGUID(){return _guid++}function _cleanUpEvents(elem,type){if(!DomData.has(elem))return;const data=DomData.get(elem);0===data.handlers[type].length&&(delete data.handlers[type],elem.removeEventListener?elem.removeEventListener(type,data.dispatcher,!1):elem.detachEvent&&elem.detachEvent("on"+type,data.dispatcher)),Object.getOwnPropertyNames(data.handlers).length<=0&&(delete data.handlers,delete data.dispatcher,delete data.disabled),0===Object.getOwnPropertyNames(data).length&&DomData.delete(elem)}function _handleMultipleEvents(fn,elem,types,callback){types.forEach((function(type){fn(elem,type,callback)}))}function fixEvent(event){if(event.fixed_)return event;function returnTrue(){return!0}function returnFalse(){return!1}if(!event||!event.isPropagationStopped||!event.isImmediatePropagationStopped){const old=event||window.event;event={};for(const key in old)"layerX"!==key&&"layerY"!==key&&"
keyLocation"!==key&&"webkitMovementX"!==key&&"webkitMovementY"!==key&&"path"!==key&&("returnValue"===key&&old.preventDefault||(event[key]=old[key]));if(event.target||(event.target=event.srcElement||document),event.relatedTarget||(event.relatedTarget=event.fromElement===event.target?event.toElement:event.fromElement),event.preventDefault=function(){old.preventDefault&&old.preventDefault(),event.returnValue=!1,old.returnValue=!1,event.defaultPrevented=!0},event.defaultPrevented=!1,event.stopPropagation=function(){old.stopPropagation&&old.stopPropagation(),event.cancelBubble=!0,old.cancelBubble=!0,event.isPropagationStopped=returnTrue},event.isPropagationStopped=returnFalse,event.stopImmediatePropagation=function(){old.stopImmediatePropagation&&old.stopImmediatePropagation(),event.isImmediatePropagationStopped=returnTrue,event.stopPropagation()},event.isImmediatePropagationStopped=returnFalse,null!==event.clientX&&void 0!==event.clientX){const doc=document.documentElement,body=document.body;event.pageX=event.cl
ientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc&&doc.clientLeft||body&&body.clientLeft||0),event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc&&doc.clientTop||body&&body.clientTop||0)}event.which=event.charCode||event.keyCode,null!==event.button&&void 0!==event.button&&(event.button=1&event.button?0:4&event.button?1:2&event.button?2:0)}return event.fixed_=!0,event}const passiveEvents=["touchstart","touchmove"];function on(elem,type,fn){if(Array.isArray(type))return _handleMultipleEvents(on,elem,type,fn);DomData.has(elem)||DomData.set(elem,{});const data=DomData.get(elem);if(data.handlers||(data.handlers={}),data.handlers[type]||(data.handlers[type]=[]),fn.guid||(fn.guid=newGUID()),data.handlers[type].push(fn),data.dispatcher||(data.disabled=!1,data.dispatcher=function(event,hash){if(data.disabled)return;event=fixEvent(event);const handlers=data.handlers[event.type];if(handlers){const handlersCopy=handlers.slice(0);for(let m=0,n=handlersCopy.length;m<n&&!event.isImmediatePr
opagationStopped();m++)try{handlersCopy[m].call(elem,event,hash)}catch(e){log$1.error(e)}}}),1===data.handlers[type].length)if(elem.addEventListener){let options=!1;(function(){if("boolean"!=typeof _supportsPassive){_supportsPassive=!1;try{const opts=Object.defineProperty({},"passive",{get(){_supportsPassive=!0}});window.addEventListener("test",null,opts),window.removeEventListener("test",null,opts)}catch(e){}}return _supportsPassive})()&&passiveEvents.indexOf(type)>-1&&(options={passive:!0}),elem.addEventListener(type,data.dispatcher,options)}else elem.attachEvent&&elem.attachEvent("on"+type,data.dispatcher)}function off(elem,type,fn){if(!DomData.has(elem))return;const data=DomData.get(elem);if(!data.handlers)return;if(Array.isArray(type))return _handleMultipleEvents(off,elem,type,fn);const removeType=function(el,t){data.handlers[t]=[],_cleanUpEvents(el,t)};if(void 0===type){for(const t in data.handlers)Object.prototype.hasOwnProperty.call(data.handlers||{},t)&&removeType(elem,t);return}const handlers=data.
handlers[type];if(handlers)if(fn){if(fn.guid)for(let n=0;n<handlers.length;n++)handlers[n].guid===fn.guid&&handlers.splice(n--,1);_cleanUpEvents(elem,type)}else removeType(elem,type)}function trigger(elem,event,hash){const elemData=DomData.has(elem)?DomData.get(elem):{},parent=elem.parentNode||elem.ownerDocument;if("string"==typeof event?event={type:event,target:elem}:event.target||(event.target=elem),event=fixEvent(event),elemData.dispatcher&&elemData.dispatcher.call(elem,event,hash),parent&&!event.isPropagationStopped()&&!0===event.bubbles)trigger.call(null,parent,event,hash);else if(!parent&&!event.defaultPrevented&&event.target&&event.target[event.type]){DomData.has(event.target)||DomData.set(event.target,{});const targetData=DomData.get(event.target);event.target[event.type]&&(targetData.disabled=!0,"function"==typeof event.target[event.type]&&event.target[event.type](),targetData.disabled=!1)}return!event.defaultPrevented}function one(elem,type,fn){if(Array.isArray(type))return _handleMultipleEvents(on
e,elem,type,fn);const func=function(){off(elem,type,func),fn.apply(this,arguments)};func.guid=fn.guid=fn.guid||newGUID(),on(elem,type,func)}function any(elem,type,fn){const func=function(){off(elem,type,func),fn.apply(this,arguments)};func.guid=fn.guid=fn.guid||newGUID(),on(elem,type,func)}var Events=Object.freeze({__proto__:null,fixEvent:fixEvent,on:on,off:off,trigger:trigger,one:one,any:any});const bind_=function(context,fn,uid){fn.guid||(fn.guid=newGUID());const bound=fn.bind(context);return bound.guid=uid?uid+"_"+fn.guid:fn.guid,bound},throttle=function(fn,wait){let last=window.performance.now();return function(){const now=window.performance.now();now-last>=wait&&(fn(...arguments),last=now)}},debounce=function(func,wait,immediate){let timeout,context=arguments.length>3&&void 0!==arguments[3]?arguments[3]:window;const cancel=()=>{context.clearTimeout(timeout),timeout=null},debounced=function(){const self=this,args=arguments;let later=function(){timeout=null,later=null,immediate||func.apply(self,args)};!ti
meout&&immediate&&func.apply(self,args),context.clearTimeout(timeout),timeout=context.setTimeout(later,wait)};return debounced.cancel=cancel,debounced};var Fn=Object.freeze({__proto__:null,UPDATE_REFRESH_INTERVAL:30,bind_:bind_,throttle:throttle,debounce:debounce});let EVENT_MAP;class EventTarget$2{on(type,fn){const ael=this.addEventListener;this.addEventListener=()=>{},on(this,type,fn),this.addEventListener=ael}off(type,fn){off(this,type,fn)}one(type,fn){const ael=this.addEventListener;this.addEventListener=()=>{},one(this,type,fn),this.addEventListener=ael}any(type,fn){const ael=this.addEventListener;this.addEventListener=()=>{},any(this,type,fn),this.addEventListener=ael}trigger(event){const type=event.type||event;"string"==typeof event&&(event={type:type}),event=fixEvent(event),this.allowedEvents_[type]&&this["on"+type]&&this["on"+type](event),trigger(this,event)}queueTrigger(event){EVENT_MAP||(EVENT_MAP=new Map);const type=event.type||event;let map=EVENT_MAP.get(this);map||(map=new Map,EVENT_MAP.set(thi
s,map));const oldTimeout=map.get(type);map.delete(type),window.clearTimeout(oldTimeout);const timeout=window.setTimeout((()=>{map.delete(type),0===map.size&&(map=null,EVENT_MAP.delete(this)),this.trigger(event)}),0);map.set(type,timeout)}}EventTarget$2.prototype.allowedEvents_={},EventTarget$2.prototype.addEventListener=EventTarget$2.prototype.on,EventTarget$2.prototype.removeEventListener=EventTarget$2.prototype.off,EventTarget$2.prototype.dispatchEvent=EventTarget$2.prototype.trigger;const objName=obj=>"function"==typeof obj.name?obj.name():"string"==typeof obj.name?obj.name:obj.name_?obj.name_:obj.constructor&&obj.constructor.name?obj.constructor.name:typeof obj,isEvented=object=>object instanceof EventTarget$2||!!object.eventBusEl_&&["on","one","off","trigger"].every((k=>"function"==typeof object[k])),isValidEventType=type=>"string"==typeof type&&/\S/.test(type)||Array.isArray(type)&&!!type.length,validateTarget=(target,obj,fnName)=>{if(!target||!target.nodeName&&!isEvented(target))throw new Error("Inval
id target for ".concat(objName(obj),"#").concat(fnName,"; must be a DOM node or evented object."))},validateEventType=(type,obj,fnName)=>{if(!isValidEventType(type))throw new Error("Invalid event type for ".concat(objName(obj),"#").concat(fnName,"; must be a non-empty string or array."))},validateListener=(listener,obj,fnName)=>{if("function"!=typeof listener)throw new Error("Invalid listener for ".concat(objName(obj),"#").concat(fnName,"; must be a function."))},normalizeListenArgs=(self,args,fnName)=>{const isTargetingSelf=args.length<3||args[0]===self||args[0]===self.eventBusEl_;let target,type,listener;return isTargetingSelf?(target=self.eventBusEl_,args.length>=3&&args.shift(),[type,listener]=args):[target,type,listener]=args,validateTarget(target,self,fnName),validateEventType(type,self,fnName),validateListener(listener,self,fnName),listener=bind_(self,listener),{isTargetingSelf:isTargetingSelf,target:target,type:type,listener:listener}},listen=(target,method,type,listener)=>{validateTarget(target,targ
et,method),target.nodeName?Events[method](target,type,listener):target[method](type,listener)},EventedMixin={on(){for(var _len9=arguments.length,args=new Array(_len9),_key9=0;_key9<_len9;_key9++)args[_key9]=arguments[_key9];const{isTargetingSelf:isTargetingSelf,target:target,type:type,listener:listener}=normalizeListenArgs(this,args,"on");if(listen(target,"on",type,listener),!isTargetingSelf){const removeListenerOnDispose=()=>this.off(target,type,listener);removeListenerOnDispose.guid=listener.guid;const removeRemoverOnTargetDispose=()=>this.off("dispose",removeListenerOnDispose);removeRemoverOnTargetDispose.guid=listener.guid,listen(this,"on","dispose",removeListenerOnDispose),listen(target,"on","dispose",removeRemoverOnTargetDispose)}},one(){for(var _this=this,_len10=arguments.length,args=new Array(_len10),_key10=0;_key10<_len10;_key10++)args[_key10]=arguments[_key10];const{isTargetingSelf:isTargetingSelf,target:target,type:type,listener:listener}=normalizeListenArgs(this,args,"one");if(isTargetingSelf)lis
ten(target,"one",type,listener);else{const wrapper=function(){_this.off(target,type,wrapper);for(var _len11=arguments.length,largs=new Array(_len11),_key11=0;_key11<_len11;_key11++)largs[_key11]=arguments[_key11];listener.apply(null,largs)};wrapper.guid=listener.guid,listen(target,"one",type,wrapper)}},any(){for(var _this2=this,_len12=arguments.length,args=new Array(_len12),_key12=0;_key12<_len12;_key12++)args[_key12]=arguments[_key12];const{isTargetingSelf:isTargetingSelf,target:target,type:type,listener:listener}=normalizeListenArgs(this,args,"any");if(isTargetingSelf)listen(target,"any",type,listener);else{const wrapper=function(){_this2.off(target,type,wrapper);for(var _len13=arguments.length,largs=new Array(_len13),_key13=0;_key13<_len13;_key13++)largs[_key13]=arguments[_key13];listener.apply(null,largs)};wrapper.guid=listener.guid,listen(target,"any",type,wrapper)}},off(targetOrType,typeOrListener,listener){if(!targetOrType||isValidEventType(targetOrType))off(this.eventBusEl_,targetOrType,typeOrListene
r);else{const target=targetOrType,type=typeOrListener;validateTarget(target,this,"off"),validateEventType(type,this,"off"),validateListener(listener,this,"off"),listener=bind_(this,listener),this.off("dispose",listener),target.nodeName?(off(target,type,listener),off(target,"dispose",listener)):isEvented(target)&&(target.off(type,listener),target.off("dispose",listener))}},trigger(event,hash){validateTarget(this.eventBusEl_,this,"trigger");const type=event&&"string"!=typeof event?event.type:event;if(!isValidEventType(type))throw new Error("Invalid event type for ".concat(objName(this),"#trigger; ")+"must be a non-empty string or object with a type key that has a non-empty value.");return trigger(this.eventBusEl_,event,hash)}};function evented(target){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{eventBusKey:eventBusKey}=options;if(eventBusKey){if(!target[eventBusKey].nodeName)throw new Error('The eventBusKey "'.concat(eventBusKey,'" does not refer to an element.'));target.eventBu
sEl_=target[eventBusKey]}else target.eventBusEl_=createEl("span",{className:"vjs-event-bus"});return Object.assign(target,EventedMixin),target.eventedCallbacks&&target.eventedCallbacks.forEach((callback=>{callback()})),target.on("dispose",(()=>{target.off(),[target,target.el_,target.eventBusEl_].forEach((function(val){val&&DomData.has(val)&&DomData.delete(val)})),window.setTimeout((()=>{target.eventBusEl_=null}),0)})),target}const StatefulMixin={state:{},setState(stateUpdates){let changes;return"function"==typeof stateUpdates&&(stateUpdates=stateUpdates()),each(stateUpdates,((value,key)=>{this.state[key]!==value&&(changes=changes||{},changes[key]={from:this.state[key],to:value}),this.state[key]=value})),changes&&isEvented(this)&&this.trigger({changes:changes,type:"statechanged"}),changes}};function stateful(target,defaultState){return Object.assign(target,StatefulMixin),target.state=Object.assign({},target.state,defaultState),"function"==typeof target.handleStateChanged&&isEvented(target)&&target.on("statech
anged",target.handleStateChanged),target}const toLowerCase=function(string){return"string"!=typeof string?string:string.replace(/./,(w=>w.toLowerCase()))},toTitleCase$1=function(string){return"string"!=typeof string?string:string.replace(/./,(w=>w.toUpperCase()))},titleCaseEquals=function(str1,str2){return toTitleCase$1(str1)===toTitleCase$1(str2)};var Str=Object.freeze({__proto__:null,toLowerCase:toLowerCase,toTitleCase:toTitleCase$1,titleCaseEquals:titleCaseEquals}),commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(fn,module){return fn(module={exports:{}},module.exports),module.exports}var keycode=createCommonjsModule((function(module,exports){function keyCode(searchInput){if(searchInput&&"object"==typeof searchInput){var hasKeyCode=searchInput.which||searchInput.keyCode||searchInput.charCode;hasKeyCode&&(searchInput=hasKeyCode)}if("number"==typeof searchInput)return nam
es[searchInput];var foundNamedKey,search=String(searchInput);return(foundNamedKey=codes[search.toLowerCase()])?foundNamedKey:(foundNamedKey=aliases[search.toLowerCase()])||(1===search.length?search.charCodeAt(0):void 0)}keyCode.isEventKey=function(event,nameOrCode){if(event&&"object"==typeof event){var keyCode=event.which||event.keyCode||event.charCode;if(null==keyCode)return!1;if("string"==typeof nameOrCode){var foundNamedKey;if(foundNamedKey=codes[nameOrCode.toLowerCase()])return foundNamedKey===keyCode;if(foundNamedKey=aliases[nameOrCode.toLowerCase()])return foundNamedKey===keyCode}else if("number"==typeof nameOrCode)return nameOrCode===keyCode;return!1}};var codes=(exports=module.exports=keyCode).code=exports.codes={backspace:8,tab:9,enter:13,shift:16,ctrl:17,alt:18,"pause/break":19,"caps lock":20,esc:27,space:32,"page up":33,"page down":34,end:35,home:36,left:37,up:38,right:39,down:40,insert:45,delete:46,command:91,"left command":91,"right command":93,"numpad *":106,"numpad +":107,"numpad -":109,"numpa
d .":110,"numpad /":111,"num lock":144,"scroll lock":145,"my computer":182,"my calculator":183,";":186,"=":187,",":188,"-":189,".":190,"/":191,"`":192,"[":219,"\\":220,"]":221,"'":222},aliases=exports.aliases={windows:91,"⇧":16,"⌥":18,"⌃":17,"⌘":91,ctl:17,control:17,option:18,pause:19,break:19,caps:20,return:13,escape:27,spc:32,spacebar:32,pgup:33,pgdn:34,ins:45,del:46,cmd:91};for(i=97;i<123;i++)codes[String.fromCharCode(i)]=i-32;for(var i=48;i<58;i++)codes[i-48]=i;for(i=1;i<13;i++)codes["f"+i]=i+111;for(i=0;i<10;i++)codes["numpad "+i]=i+96;var names=exports.names=exports.title={};for(i in codes)names[codes[i]]=i;for(var alias in aliases)codes[alias]=aliases[alias]}));keycode.code,keycode.codes,keycode.aliases,keycode.names,keycode.title;class Component$1{constructor(player,options,ready){if(!player&&this.play?this.player_=player=this:this.player_=player,this.isDisposed_=!1,this.parentComponent_=null,this.options_=merge$2({},this.options_),options=this.options_=merge$2(this.options_,options),this.id_
=options.id||options.el&&options.el.id,!this.id_){const id=player&&player.id&&player.id()||"no_player";this.id_="".concat(id,"_component_").concat(newGUID())}this.name_=options.name||null,options.el?this.el_=options.el:!1!==options.createEl&&(this.el_=this.createEl()),options.className&&this.el_&&options.className.split(" ").forEach((c=>this.addClass(c))),["on","off","one","any","trigger"].forEach((fn=>{this[fn]=void 0})),!1!==options.evented&&(evented(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),stateful(this,this.constructor.defaultState),this.children_=[],this.childIndex_={},this.childNameIndex_={},this.setTimeoutIds_=new Set,this.setIntervalIds_=new Set,this.rafIds_=new Set,this.namedRafs_=new Map,this.clearingTimersOnDispose_=!1,!1!==options.initChildren&&this.initChildren(),this.ready(ready),!1!==options.reportTouchActivity&&this.enableTouchActivity()}on(type,fn){}off(type,fn){}on
e(type,fn){}any(type,fn){}trigger(event,hash){}dispose(){let options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this.isDisposed_){if(this.readyQueue_&&(this.readyQueue_.length=0),this.trigger({type:"dispose",bubbles:!1}),this.isDisposed_=!0,this.children_)for(let i=this.children_.length-1;i>=0;i--)this.children_[i].dispose&&this.children_[i].dispose();this.children_=null,this.childIndex_=null,this.childNameIndex_=null,this.parentComponent_=null,this.el_&&(this.el_.parentNode&&(options.restoreEl?this.el_.parentNode.replaceChild(options.restoreEl,this.el_):this.el_.parentNode.removeChild(this.el_)),this.el_=null),this.player_=null}}isDisposed(){return Boolean(this.isDisposed_)}player(){return this.player_}options(obj){return obj?(this.options_=merge$2(this.options_,obj),this.options_):this.options_}el(){return this.el_}createEl(tagName,properties,attributes){return createEl(tagName,properties,attributes)}localize(string,tokens){let defaultValue=arguments.length>2&&void 0!==arguments[2]?argum
ents[2]:string;const code=this.player_.language&&this.player_.language(),languages=this.player_.languages&&this.player_.languages(),language=languages&&languages[code],primaryCode=code&&code.split("-")[0],primaryLang=languages&&languages[primaryCode];let localizedString=defaultValue;return language&&language[string]?localizedString=language[string]:primaryLang&&primaryLang[string]&&(localizedString=primaryLang[string]),tokens&&(localizedString=localizedString.replace(/\{(\d+)\}/g,(function(match,index){const value=tokens[index-1];let ret=value;return void 0===value&&(ret=match),ret}))),localizedString}handleLanguagechange(){}contentEl(){return this.contentEl_||this.el_}id(){return this.id_}name(){return this.name_}children(){return this.children_}getChildById(id){return this.childIndex_[id]}getChild(name){if(name)return this.childNameIndex_[name]}getDescendant(){for(var _len14=arguments.length,names=new Array(_len14),_key14=0;_key14<_len14;_key14++)names[_key14]=arguments[_key14];names=names.reduce(((acc,n)=
>acc.concat(n)),[]);let currentChild=this;for(let i=0;i<names.length;i++)if(currentChild=currentChild.getChild(names[i]),!currentChild||!currentChild.getChild)return;return currentChild}setIcon(iconName){let el=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.el();if(!this.player_.options_.experimentalSvgIcons)return;const xmlnsURL="http://www.w3.org/2000/svg",iconContainer=createEl("span",{className:"vjs-icon-placeholder vjs-svg-icon"},{"aria-hidden":"true"}),svgEl=document.createElementNS(xmlnsURL,"svg");svgEl.setAttributeNS(null,"viewBox","0 0 512 512");const useEl=document.createElementNS(xmlnsURL,"use");return svgEl.appendChild(useEl),useEl.setAttributeNS(null,"href","#vjs-icon-".concat(iconName)),iconContainer.appendChild(svgEl),this.iconIsSet_?el.replaceChild(iconContainer,el.querySelector(".vjs-icon-placeholder")):el.appendChild(iconContainer),this.iconIsSet_=!0,iconContainer}addChild(child){let component,componentName,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},index
=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.children_.length;if("string"==typeof child){componentName=toTitleCase$1(child);const componentClassName=options.componentClass||componentName;options.name=componentName;const ComponentClass=Component$1.getComponent(componentClassName);if(!ComponentClass)throw new Error("Component ".concat(componentClassName," does not exist"));if("function"!=typeof ComponentClass)return null;component=new ComponentClass(this.player_||this,options)}else component=child;if(component.parentComponent_&&component.parentComponent_.removeChild(component),this.children_.splice(index,0,component),component.parentComponent_=this,"function"==typeof component.id&&(this.childIndex_[component.id()]=component),componentName=componentName||component.name&&toTitleCase$1(component.name()),componentName&&(this.childNameIndex_[componentName]=component,this.childNameIndex_[toLowerCase(componentName)]=component),"function"==typeof component.el&&component.el()){let refNode=null;this.chil
dren_[index+1]&&(this.children_[index+1].el_?refNode=this.children_[index+1].el_:isEl(this.children_[index+1])&&(refNode=this.children_[index+1])),this.contentEl().insertBefore(component.el(),refNode)}return component}removeChild(component){if("string"==typeof component&&(component=this.getChild(component)),!component||!this.children_)return;let childFound=!1;for(let i=this.children_.length-1;i>=0;i--)if(this.children_[i]===component){childFound=!0,this.children_.splice(i,1);break}if(!childFound)return;component.parentComponent_=null,this.childIndex_[component.id()]=null,this.childNameIndex_[toTitleCase$1(component.name())]=null,this.childNameIndex_[toLowerCase(component.name())]=null;const compEl=component.el();compEl&&compEl.parentNode===this.contentEl()&&this.contentEl().removeChild(component.el())}initChildren(){const children=this.options_.children;if(children){const parentOptions=this.options_,handleAdd=child=>{const name=child.name;let opts=child.opts;if(void 0!==parentOptions[name]&&(opts=parentOptio
ns[name]),!1===opts)return;!0===opts&&(opts={}),opts.playerOptions=this.options_.playerOptions;const newChild=this.addChild(name,opts);newChild&&(this[name]=newChild)};let workingChildren;const Tech=Component$1.getComponent("Tech");workingChildren=Array.isArray(children)?children:Object.keys(children),workingChildren.concat(Object.keys(this.options_).filter((function(child){return!workingChildren.some((function(wchild){return"string"==typeof wchild?child===wchild:child===wchild.name}))}))).map((child=>{let name,opts;return"string"==typeof child?(name=child,opts=children[name]||this.options_[name]||{}):(name=child.name,opts=child),{name:name,opts:opts}})).filter((child=>{const c=Component$1.getComponent(child.opts.componentClass||toTitleCase$1(child.name));return c&&!Tech.isTech(c)})).forEach(handleAdd)}}buildCSSClass(){return""}ready(fn){let sync=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(fn)return this.isReady_?void(sync?fn.call(this):this.setTimeout(fn,1)):(this.readyQueue_=this.readyQueue_
||[],void this.readyQueue_.push(fn))}triggerReady(){this.isReady_=!0,this.setTimeout((function(){const readyQueue=this.readyQueue_;this.readyQueue_=[],readyQueue&&readyQueue.length>0&&readyQueue.forEach((function(fn){fn.call(this)}),this),this.trigger("ready")}),1)}$(selector,context){return $(selector,context||this.contentEl())}$$(selector,context){return $$(selector,context||this.contentEl())}hasClass(classToCheck){return hasClass(this.el_,classToCheck)}addClass(){for(var _len15=arguments.length,classesToAdd=new Array(_len15),_key15=0;_key15<_len15;_key15++)classesToAdd[_key15]=arguments[_key15];addClass(this.el_,...classesToAdd)}removeClass(){for(var _len16=arguments.length,classesToRemove=new Array(_len16),_key16=0;_key16<_len16;_key16++)classesToRemove[_key16]=arguments[_key16];removeClass(this.el_,...classesToRemove)}toggleClass(classToToggle,predicate){toggleClass(this.el_,classToToggle,predicate)}show(){this.removeClass("vjs-hidden")}hide(){this.addClass("vjs-hidden")}lockShowing(){this.addClass("vjs
-lock-showing")}unlockShowing(){this.removeClass("vjs-lock-showing")}getAttribute(attribute){return getAttribute(this.el_,attribute)}setAttribute(attribute,value){setAttribute(this.el_,attribute,value)}removeAttribute(attribute){removeAttribute(this.el_,attribute)}width(num,skipListeners){return this.dimension("width",num,skipListeners)}height(num,skipListeners){return this.dimension("height",num,skipListeners)}dimensions(width,height){this.width(width,!0),this.height(height)}dimension(widthOrHeight,num,skipListeners){if(void 0!==num)return null!==num&&num==num||(num=0),-1!==(""+num).indexOf("%")||-1!==(""+num).indexOf("px")?this.el_.style[widthOrHeight]=num:this.el_.style[widthOrHeight]="auto"===num?"":num+"px",void(skipListeners||this.trigger("componentresize"));if(!this.el_)return 0;const val=this.el_.style[widthOrHeight],pxIndex=val.indexOf("px");return-1!==pxIndex?parseInt(val.slice(0,pxIndex),10):parseInt(this.el_["offset"+toTitleCase$1(widthOrHeight)],10)}currentDimension(widthOrHeight){let computedWi
dthOrHeight=0;if("width"!==widthOrHeight&&"height"!==widthOrHeight)throw new Error("currentDimension only accepts width or height value");if(computedWidthOrHeight=computedStyle(this.el_,widthOrHeight),computedWidthOrHeight=parseFloat(computedWidthOrHeight),0===computedWidthOrHeight||isNaN(computedWidthOrHeight)){const rule="offset".concat(toTitleCase$1(widthOrHeight));computedWidthOrHeight=this.el_[rule]}return computedWidthOrHeight}currentDimensions(){return{width:this.currentDimension("width"),height:this.currentDimension("height")}}currentWidth(){return this.currentDimension("width")}currentHeight(){return this.currentDimension("height")}focus(){this.el_.focus()}blur(){this.el_.blur()}handleKeyDown(event){this.player_&&(keycode.isEventKey(event,"Tab")||event.stopPropagation(),this.player_.handleKeyDown(event))}handleKeyPress(event){this.handleKeyDown(event)}emitTapEvents(){let touchStart=0,firstTouch=null;let couldBeTap;this.on("touchstart",(function(event){1===event.touches.length&&(firstTouch={pageX:eve
nt.touches[0].pageX,pageY:event.touches[0].pageY},touchStart=window.performance.now(),couldBeTap=!0)})),this.on("touchmove",(function(event){if(event.touches.length>1)couldBeTap=!1;else if(firstTouch){const xdiff=event.touches[0].pageX-firstTouch.pageX,ydiff=event.touches[0].pageY-firstTouch.pageY;Math.sqrt(xdiff*xdiff+ydiff*ydiff)>10&&(couldBeTap=!1)}}));const noTap=function(){couldBeTap=!1};this.on("touchleave",noTap),this.on("touchcancel",noTap),this.on("touchend",(function(event){if(firstTouch=null,!0===couldBeTap){window.performance.now()-touchStart<200&&(event.preventDefault(),this.trigger("tap"))}}))}enableTouchActivity(){if(!this.player()||!this.player().reportUserActivity)return;const report=bind_(this.player(),this.player().reportUserActivity);let touchHolding;this.on("touchstart",(function(){report(),this.clearInterval(touchHolding),touchHolding=this.setInterval(report,250)}));const touchEnd=function(event){report(),this.clearInterval(touchHolding)};this.on("touchmove",report),this.on("touchend",t
ouchEnd),this.on("touchcancel",touchEnd)}setTimeout(fn,timeout){var timeoutId;return fn=bind_(this,fn),this.clearTimersOnDispose_(),timeoutId=window.setTimeout((()=>{this.setTimeoutIds_.has(timeoutId)&&this.setTimeoutIds_.delete(timeoutId),fn()}),timeout),this.setTimeoutIds_.add(timeoutId),timeoutId}clearTimeout(timeoutId){return this.setTimeoutIds_.has(timeoutId)&&(this.setTimeoutIds_.delete(timeoutId),window.clearTimeout(timeoutId)),timeoutId}setInterval(fn,interval){fn=bind_(this,fn),this.clearTimersOnDispose_();const intervalId=window.setInterval(fn,interval);return this.setIntervalIds_.add(intervalId),intervalId}clearInterval(intervalId){return this.setIntervalIds_.has(intervalId)&&(this.setIntervalIds_.delete(intervalId),window.clearInterval(intervalId)),intervalId}requestAnimationFrame(fn){var id;return this.clearTimersOnDispose_(),fn=bind_(this,fn),id=window.requestAnimationFrame((()=>{this.rafIds_.has(id)&&this.rafIds_.delete(id),fn()})),this.rafIds_.add(id),id}requestNamedAnimationFrame(name,fn){if
(this.namedRafs_.has(name))return;this.clearTimersOnDispose_(),fn=bind_(this,fn);const id=this.requestAnimationFrame((()=>{fn(),this.namedRafs_.has(name)&&this.namedRafs_.delete(name)}));return this.namedRafs_.set(name,id),name}cancelNamedAnimationFrame(name){this.namedRafs_.has(name)&&(this.cancelAnimationFrame(this.namedRafs_.get(name)),this.namedRafs_.delete(name))}cancelAnimationFrame(id){return this.rafIds_.has(id)&&(this.rafIds_.delete(id),window.cancelAnimationFrame(id)),id}clearTimersOnDispose_(){this.clearingTimersOnDispose_||(this.clearingTimersOnDispose_=!0,this.one("dispose",(()=>{[["namedRafs_","cancelNamedAnimationFrame"],["rafIds_","cancelAnimationFrame"],["setTimeoutIds_","clearTimeout"],["setIntervalIds_","clearInterval"]].forEach((_ref4=>{let[idName,cancelName]=_ref4;this[idName].forEach(((val,key)=>this[cancelName](key)))})),this.clearingTimersOnDispose_=!1})))}static registerComponent(name,ComponentToRegister){if("string"!=typeof name||!name)throw new Error('Illegal component name, "'.con
cat(name,'"; must be a non-empty string.'));const Tech=Component$1.getComponent("Tech"),isTech=Tech&&Tech.isTech(ComponentToRegister),isComp=Component$1===ComponentToRegister||Component$1.prototype.isPrototypeOf(ComponentToRegister.prototype);if(isTech||!isComp){let reason;throw reason=isTech?"techs must be registered using Tech.registerTech()":"must be a Component subclass",new Error('Illegal component, "'.concat(name,'"; ').concat(reason,"."))}name=toTitleCase$1(name),Component$1.components_||(Component$1.components_={});const Player=Component$1.getComponent("Player");if("Player"===name&&Player&&Player.players){const players=Player.players,playerNames=Object.keys(players);if(players&&playerNames.length>0&&playerNames.map((pname=>players[pname])).every(Boolean))throw new Error("Can not register Player component after player has been created.")}return Component$1.components_[name]=ComponentToRegister,Component$1.components_[toLowerCase(name)]=ComponentToRegister,ComponentToRegister}static getComponent(name){
if(name&&Component$1.components_)return Component$1.components_[name]}}function getRange(fnName,valueIndex,ranges,rangeIndex){return function(fnName,index,maxIndex){if("number"!=typeof index||index<0||index>maxIndex)throw new Error("Failed to execute '".concat(fnName,"' on 'TimeRanges': The index provided (").concat(index,") is non-numeric or out of bounds (0-").concat(maxIndex,")."))}(fnName,rangeIndex,ranges.length-1),ranges[rangeIndex][valueIndex]}function createTimeRangesObj(ranges){let timeRangesObj;return timeRangesObj=void 0===ranges||0===ranges.length?{length:0,start(){throw new Error("This TimeRanges object is empty")},end(){throw new Error("This TimeRanges object is empty")}}:{length:ranges.length,start:getRange.bind(null,"start",0,ranges),end:getRange.bind(null,"end",1,ranges)},window.Symbol&&window.Symbol.iterator&&(timeRangesObj[window.Symbol.iterator]=()=>(ranges||[]).values()),timeRangesObj}function createTimeRanges$1(start,end){return Array.isArray(start)?createTimeRangesObj(start):void 0===s
tart||void 0===end?createTimeRangesObj():createTimeRangesObj([[start,end]])}Component$1.registerComponent("Component",Component$1);const defaultImplementation=function(seconds,guide){seconds=seconds<0?0:seconds;let s=Math.floor(seconds%60),m=Math.floor(seconds/60%60),h=Math.floor(seconds/3600);const gm=Math.floor(guide/60%60),gh=Math.floor(guide/3600);return(isNaN(seconds)||seconds===1/0)&&(h=m=s="-"),h=h>0||gh>0?h+":":"",m=((h||gm>=10)&&m<10?"0"+m:m)+":",s=s<10?"0"+s:s,h+m+s};let implementation=defaultImplementation;function setFormatTime(customImplementation){implementation=customImplementation}function resetFormatTime(){implementation=defaultImplementation}function formatTime(seconds){let guide=arguments.length>1&&void 0!==arguments[1]?arguments[1]:seconds;return implementation(seconds,guide)}var Time=Object.freeze({__proto__:null,createTimeRanges:createTimeRanges$1,createTimeRange:createTimeRanges$1,setFormatTime:setFormatTime,resetFormatTime:resetFormatTime,formatTime:formatTime});function bufferedPerce
nt(buffered,duration){let start,end,bufferedDuration=0;if(!duration)return 0;buffered&&buffered.length||(buffered=createTimeRanges$1(0,0));for(let i=0;i<buffered.length;i++)start=buffered.start(i),end=buffered.end(i),end>duration&&(end=duration),bufferedDuration+=end-start;return bufferedDuration/duration}function MediaError(value){if(value instanceof MediaError)return value;"number"==typeof value?this.code=value:"string"==typeof value?this.message=value:isObject$1(value)&&("number"==typeof value.code&&(this.code=value.code),Object.assign(this,value)),this.message||(this.message=MediaError.defaultMessages[this.code]||"")}MediaError.prototype.code=0,MediaError.prototype.message="",MediaError.prototype.status=null,MediaError.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"],MediaError.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail part-way.",3:"The media playbac
k was aborted due to a corruption problem or because the media used features your browser did not support.",4:"The media could not be loaded, either because the server or network failed or because the format is not supported.",5:"The media is encrypted and we do not have the keys to decrypt it."};for(let errNum=0;errNum<MediaError.errorTypes.length;errNum++)MediaError[MediaError.errorTypes[errNum]]=errNum,MediaError.prototype[MediaError.errorTypes[errNum]]=errNum;var tuple=function(obj,reviver){var json,error=null;try{json=JSON.parse(obj,reviver)}catch(err){error=err}return[error,json]};function isPromise(value){return null!=value&&"function"==typeof value.then}function silencePromise(value){isPromise(value)&&value.then(null,(e=>{}))}const trackToJson_=function(track){return["kind","label","language","id","inBandMetadataTrackDispatchType","mode","src"].reduce(((acc,prop,i)=>(track[prop]&&(acc[prop]=track[prop]),acc)),{cues:track.cues&&Array.prototype.map.call(track.cues,(function(cue){return{startTime:cue.st
artTime,endTime:cue.endTime,text:cue.text,id:cue.id}}))})};var textTrackConverter_textTracksToJson=function(tech){const trackEls=tech.$$("track"),trackObjs=Array.prototype.map.call(trackEls,(t=>t.track));return Array.prototype.map.call(trackEls,(function(trackEl){const json=trackToJson_(trackEl.track);return trackEl.src&&(json.src=trackEl.src),json})).concat(Array.prototype.filter.call(tech.textTracks(),(function(track){return-1===trackObjs.indexOf(track)})).map(trackToJson_))},textTrackConverter_jsonToTextTracks=function(json,tech){return json.forEach((function(track){const addedTrack=tech.addRemoteTextTrack(track).track;!track.src&&track.cues&&track.cues.forEach((cue=>addedTrack.addCue(cue)))})),tech.textTracks()};class ModalDialog extends Component$1{constructor(player,options){super(player,options),this.handleKeyDown_=e=>this.handleKeyDown(e),this.close_=e=>this.close(e),this.opened_=this.hasBeenOpened_=this.hasBeenFilled_=!1,this.closeable(!this.options_.uncloseable),this.content(this.options_.content),
this.contentEl_=createEl("div",{className:"".concat("vjs-modal-dialog","-content")},{role:"document"}),this.descEl_=createEl("p",{className:"".concat("vjs-modal-dialog","-description vjs-control-text"),id:this.el().getAttribute("aria-describedby")}),textContent(this.descEl_,this.description()),this.el_.appendChild(this.descEl_),this.el_.appendChild(this.contentEl_)}createEl(){return super.createEl("div",{className:this.buildCSSClass(),tabIndex:-1},{"aria-describedby":"".concat(this.id(),"_description"),"aria-hidden":"true","aria-label":this.label(),role:"dialog"})}dispose(){this.contentEl_=null,this.descEl_=null,this.previouslyActiveEl_=null,super.dispose()}buildCSSClass(){return"".concat("vjs-modal-dialog"," vjs-hidden ").concat(super.buildCSSClass())}label(){return this.localize(this.options_.label||"Modal Window")}description(){let desc=this.options_.description||this.localize("This is a modal window.");return this.closeable()&&(desc+=" "+this.localize("This modal can be closed by pressing the Escape key
or activating the close button.")),desc}open(){if(!this.opened_){const player=this.player();this.trigger("beforemodalopen"),this.opened_=!0,(this.options_.fillAlways||!this.hasBeenOpened_&&!this.hasBeenFilled_)&&this.fill(),this.wasPlaying_=!player.paused(),this.options_.pauseOnOpen&&this.wasPlaying_&&player.pause(),this.on("keydown",this.handleKeyDown_),this.hadControls_=player.controls(),player.controls(!1),this.show(),this.conditionalFocus_(),this.el().setAttribute("aria-hidden","false"),this.trigger("modalopen"),this.hasBeenOpened_=!0}}opened(value){return"boolean"==typeof value&&this[value?"open":"close"](),this.opened_}close(){if(!this.opened_)return;const player=this.player();this.trigger("beforemodalclose"),this.opened_=!1,this.wasPlaying_&&this.options_.pauseOnOpen&&player.play(),this.off("keydown",this.handleKeyDown_),this.hadControls_&&player.controls(!0),this.hide(),this.el().setAttribute("aria-hidden","true"),this.trigger("modalclose"),this.conditionalBlur_(),this.options_.temporary&&this.dispos
e()}closeable(value){if("boolean"==typeof value){const closeable=this.closeable_=!!value;let close=this.getChild("closeButton");if(closeable&&!close){const temp=this.contentEl_;this.contentEl_=this.el_,close=this.addChild("closeButton",{controlText:"Close Modal Dialog"}),this.contentEl_=temp,this.on(close,"close",this.close_)}!closeable&&close&&(this.off(close,"close",this.close_),this.removeChild(close),close.dispose())}return this.closeable_}fill(){this.fillWith(this.content())}fillWith(content){const contentEl=this.contentEl(),parentEl=contentEl.parentNode,nextSiblingEl=contentEl.nextSibling;this.trigger("beforemodalfill"),this.hasBeenFilled_=!0,parentEl.removeChild(contentEl),this.empty(),insertContent(contentEl,content),this.trigger("modalfill"),nextSiblingEl?parentEl.insertBefore(contentEl,nextSiblingEl):parentEl.appendChild(contentEl);const closeButton=this.getChild("closeButton");closeButton&&parentEl.appendChild(closeButton.el_)}empty(){this.trigger("beforemodalempty"),emptyEl(this.contentEl()),this
.trigger("modalempty")}content(value){return void 0!==value&&(this.content_=value),this.content_}conditionalFocus_(){const activeEl=document.activeElement,playerEl=this.player_.el_;this.previouslyActiveEl_=null,(playerEl.contains(activeEl)||playerEl===activeEl)&&(this.previouslyActiveEl_=activeEl,this.focus())}conditionalBlur_(){this.previouslyActiveEl_&&(this.previouslyActiveEl_.focus(),this.previouslyActiveEl_=null)}handleKeyDown(event){if(event.stopPropagation(),keycode.isEventKey(event,"Escape")&&this.closeable())return event.preventDefault(),void this.close();if(!keycode.isEventKey(event,"Tab"))return;const focusableEls=this.focusableEls_(),activeEl=this.el_.querySelector(":focus");let focusIndex;for(let i=0;i<focusableEls.length;i++)if(activeEl===focusableEls[i]){focusIndex=i;break}document.activeElement===this.el_&&(focusIndex=0),event.shiftKey&&0===focusIndex?(focusableEls[focusableEls.length-1].focus(),event.preventDefault()):event.shiftKey||focusIndex!==focusableEls.length-1||(focusableEls[0].focus
(),event.preventDefault())}focusableEls_(){const allChildren=this.el_.querySelectorAll("*");return Array.prototype.filter.call(allChildren,(child=>(child instanceof window.HTMLAnchorElement||child instanceof window.HTMLAreaElement)&&child.hasAttribute("href")||(child instanceof window.HTMLInputElement||child instanceof window.HTMLSelectElement||child instanceof window.HTMLTextAreaElement||child instanceof window.HTMLButtonElement)&&!child.hasAttribute("disabled")||child instanceof window.HTMLIFrameElement||child instanceof window.HTMLObjectElement||child instanceof window.HTMLEmbedElement||child.hasAttribute("tabindex")&&-1!==child.getAttribute("tabindex")||child.hasAttribute("contenteditable")))}}ModalDialog.prototype.options_={pauseOnOpen:!0,temporary:!0},Component$1.registerComponent("ModalDialog",ModalDialog);class TrackList extends EventTarget$2{constructor(){let tracks=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];super(),this.tracks_=[],Object.defineProperty(this,"length",{get(){return thi
s.tracks_.length}});for(let i=0;i<tracks.length;i++)this.addTrack(tracks[i])}addTrack(track){const index=this.tracks_.length;""+index in this||Object.defineProperty(this,index,{get(){return this.tracks_[index]}}),-1===this.tracks_.indexOf(track)&&(this.tracks_.push(track),this.trigger({track:track,type:"addtrack",target:this})),track.labelchange_=()=>{this.trigger({track:track,type:"labelchange",target:this})},isEvented(track)&&track.addEventListener("labelchange",track.labelchange_)}removeTrack(rtrack){let track;for(let i=0,l=this.length;i<l;i++)if(this[i]===rtrack){track=this[i],track.off&&track.off(),this.tracks_.splice(i,1);break}track&&this.trigger({track:track,type:"removetrack",target:this})}getTrackById(id){let result=null;for(let i=0,l=this.length;i<l;i++){const track=this[i];if(track.id===id){result=track;break}}return result}}TrackList.prototype.allowedEvents_={change:"change",addtrack:"addtrack",removetrack:"removetrack",labelchange:"labelchange"};for(const event in TrackList.prototype.allowedEve
nts_)TrackList.prototype["on"+event]=null;const disableOthers$1=function(list,track){for(let i=0;i<list.length;i++)Object.keys(list[i]).length&&track.id!==list[i].id&&(list[i].enabled=!1)};const disableOthers=function(list,track){for(let i=0;i<list.length;i++)Object.keys(list[i]).length&&track.id!==list[i].id&&(list[i].selected=!1)};class TextTrackList extends TrackList{addTrack(track){super.addTrack(track),this.queueChange_||(this.queueChange_=()=>this.queueTrigger("change")),this.triggerSelectedlanguagechange||(this.triggerSelectedlanguagechange_=()=>this.trigger("selectedlanguagechange")),track.addEventListener("modechange",this.queueChange_);-1===["metadata","chapters"].indexOf(track.kind)&&track.addEventListener("modechange",this.triggerSelectedlanguagechange_)}removeTrack(rtrack){super.removeTrack(rtrack),rtrack.removeEventListener&&(this.queueChange_&&rtrack.removeEventListener("modechange",this.queueChange_),this.selectedlanguagechange_&&rtrack.removeEventListener("modechange",this.triggerSelectedlan
guagechange_))}}class TextTrackCueList{constructor(cues){TextTrackCueList.prototype.setCues_.call(this,cues),Object.defineProperty(this,"length",{get(){return this.length_}})}setCues_(cues){const oldLength=this.length||0;let i=0;const l=cues.length;this.cues_=cues,this.length_=cues.length;const defineProp=function(index){""+index in this||Object.defineProperty(this,""+index,{get(){return this.cues_[index]}})};if(oldLength<l)for(i=oldLength;i<l;i++)defineProp.call(this,i)}getCueById(id){let result=null;for(let i=0,l=this.length;i<l;i++){const cue=this[i];if(cue.id===id){result=cue;break}}return result}}const VideoTrackKind={alternative:"alternative",captions:"captions",main:"main",sign:"sign",subtitles:"subtitles",commentary:"commentary"},AudioTrackKind={alternative:"alternative",descriptions:"descriptions",main:"main","main-desc":"main-desc",translation:"translation",commentary:"commentary"},TextTrackKind={subtitles:"subtitles",captions:"captions",descriptions:"descriptions",chapters:"chapters",metadata:"met
adata"},TextTrackMode={disabled:"disabled",hidden:"hidden",showing:"showing"};class Track extends EventTarget$2{constructor(){let options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super();const trackProps={id:options.id||"vjs_track_"+newGUID(),kind:options.kind||"",language:options.language||""};let label=options.label||"";for(const key in trackProps)Object.defineProperty(this,key,{get:()=>trackProps[key],set(){}});Object.defineProperty(this,"label",{get:()=>label,set(newLabel){newLabel!==label&&(label=newLabel,this.trigger("labelchange"))}})}}const parseUrl=function(url){const props=["protocol","hostname","port","pathname","search","hash","host"],a=document.createElement("a");a.href=url;const details={};for(let i=0;i<props.length;i++)details[props[i]]=a[props[i]];return"http:"===details.protocol&&(details.host=details.host.replace(/:80$/,"")),"https:"===details.protocol&&(details.host=details.host.replace(/:443$/,"")),details.protocol||(details.protocol=window.location.protocol),details.host
||(details.host=window.location.host),details},getAbsoluteURL=function(url){if(!url.match(/^https?:\/\//)){const a=document.createElement("a");a.href=url,url=a.href}return url},getFileExtension=function(path){if("string"==typeof path){const pathParts=/^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/.exec(path);if(pathParts)return pathParts.pop().toLowerCase()}return""},isCrossOrigin=function(url){let winLoc=arguments.length>1&&void 0!==arguments[1]?arguments[1]:window.location;const urlInfo=parseUrl(url),srcProtocol=":"===urlInfo.protocol?winLoc.protocol:urlInfo.protocol,crossOrigin=srcProtocol+urlInfo.host!==winLoc.protocol+winLoc.host;return crossOrigin};var x,Url=Object.freeze({__proto__:null,parseUrl:parseUrl,getAbsoluteURL:getAbsoluteURL,getFileExtension:getFileExtension,isCrossOrigin:isCrossOrigin}),window_1="undefined"!=typeof window?window:void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:{},_extends_1=createCommonjsModule((function(module){function _extends(
){return module.exports=_extends=Object.assign?Object.assign.bind():function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},module.exports.__esModule=!0,module.exports.default=module.exports,_extends.apply(this,arguments)}module.exports=_extends,module.exports.__esModule=!0,module.exports.default=module.exports})),_extends$1=(x=_extends_1)&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x,isFunction_1=function(fn){if(!fn)return!1;var string=toString.call(fn);return"[object Function]"===string||"function"==typeof fn&&"[object RegExp]"!==string||"undefined"!=typeof window&&(fn===window.setTimeout||fn===window.alert||fn===window.confirm||fn===window.prompt)},toString=Object.prototype.toString;var httpHandler=function(callback,decodeResponseBody){return void 0===decodeResponseBody&&(decodeResponseBody=!1),function(err,response,responseBody){if(err)callba
ck(err);else if(response.statusCode>=400&&response.statusCode<=599){var cause=responseBody;if(decodeResponseBody)if(window_1.TextDecoder){var charset=function(contentTypeHeader){void 0===contentTypeHeader&&(contentTypeHeader="");return contentTypeHeader.toLowerCase().split(";").reduce((function(charset,contentType){var _contentType$split=contentType.split("="),type=_contentType$split[0],value=_contentType$split[1];return"charset"===type.trim()?value.trim():charset}),"utf-8")}(response.headers&&response.headers["content-type"]);try{cause=new TextDecoder(charset).decode(responseBody)}catch(e){}}else cause=String.fromCharCode.apply(null,new Uint8Array(responseBody));callback({cause:cause})}else callback(null,responseBody)}};createXHR.httpHandler=httpHandler;
/**
* @license
* slighly modified parse-headers 2.0.2 <https://github.com/kesla/parse-headers/>
* Copyright (c) 2014 David Björklund
* Available under the MIT license
* <https://github.com/kesla/parse-headers/blob/master/LICENCE>
*/
var lib=createXHR,default_1=createXHR;function initParams(uri,options,callback){var params=uri;return isFunction_1(options)?(callback=options,"string"==typeof uri&&(params={uri:uri})):params=_extends_1({},options,{uri:uri}),params.callback=callback,params}function createXHR(uri,options,callback){return _createXHR(options=initParams(uri,options,callback))}function _createXHR(options){if(void 0===options.callback)throw new Error("callback argument missing");var called=!1,callback=function(err,response,body){called||(called=!0,options.callback(err,response,body))};function getBody(){var body=void 0;if(body=xhr.response?xhr.response:xhr.responseText||function(xhr){try{if("document"===xhr.responseType)return xhr.responseXML;var firefoxBugTakenEffect=xhr.responseXML&&"parsererror"===xhr.responseXML.documentElement.nodeName;if(""===xhr.responseType&&!firefoxBugTakenEffect)return xhr.responseXML}catch(e){}return null}(xhr),isJson)try{body=JSON.parse(body)}catch(e){}return body}function errorFunc(evt){return clearTim
eout(timeoutTimer),evt instanceof Error||(evt=new Error(""+(evt||"Unknown XMLHttpRequest Error"))),evt.statusCode=0,callback(evt,failureResponse)}function loadFunc(){if(!aborted){var status;clearTimeout(timeoutTimer),status=options.useXDR&&void 0===xhr.status?200:1223===xhr.status?204:xhr.status;var response=failureResponse,err=null;return 0!==status?(response={body:getBody(),statusCode:status,method:method,headers:{},url:uri,rawRequest:xhr},xhr.getAllResponseHeaders&&(response.headers=function(headers){var result={};return headers?(headers.trim().split("\n").forEach((function(row){var index=row.indexOf(":"),key=row.slice(0,index).trim().toLowerCase(),value=row.slice(index+1).trim();void 0===result[key]?result[key]=value:Array.isArray(result[key])?result[key].push(value):result[key]=[result[key],value]})),result):result}(xhr.getAllResponseHeaders()))):err=new Error("Internal XMLHttpRequest Error"),callback(err,response,response.body)}}var key,aborted,xhr=options.xhr||null;xhr||(xhr=options.cors||options.useX
DR?new createXHR.XDomainRequest:new createXHR.XMLHttpRequest);var timeoutTimer,uri=xhr.url=options.uri||options.url,method=xhr.method=options.method||"GET",body=options.body||options.data,headers=xhr.headers=options.headers||{},sync=!!options.sync,isJson=!1,failureResponse={body:void 0,headers:{},statusCode:0,method:method,url:uri,rawRequest:xhr};if("json"in options&&!1!==options.json&&(isJson=!0,headers.accept||headers.Accept||(headers.Accept="application/json"),"GET"!==method&&"HEAD"!==method&&(headers["content-type"]||headers["Content-Type"]||(headers["Content-Type"]="application/json"),body=JSON.stringify(!0===options.json?body:options.json))),xhr.onreadystatechange=function(){4===xhr.readyState&&setTimeout(loadFunc,0)},xhr.onload=loadFunc,xhr.onerror=errorFunc,xhr.onprogress=function(){},xhr.onabort=function(){aborted=!0},xhr.ontimeout=errorFunc,xhr.open(method,uri,!sync,options.username,options.password),sync||(xhr.withCredentials=!!options.withCredentials),!sync&&options.timeout>0&&(timeoutTimer=setTi
meout((function(){if(!aborted){aborted=!0,xhr.abort("timeout");var e=new Error("XMLHttpRequest timeout");e.code="ETIMEDOUT",errorFunc(e)}}),options.timeout)),xhr.setRequestHeader)for(key in headers)headers.hasOwnProperty(key)&&xhr.setRequestHeader(key,headers[key]);else if(options.headers&&!function(obj){for(var i in obj)if(obj.hasOwnProperty(i))return!1;return!0}(options.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in options&&(xhr.responseType=options.responseType),"beforeSend"in options&&"function"==typeof options.beforeSend&&options.beforeSend(xhr),xhr.send(body||null),xhr}createXHR.XMLHttpRequest=window_1.XMLHttpRequest||function(){},createXHR.XDomainRequest="withCredentials"in new createXHR.XMLHttpRequest?createXHR.XMLHttpRequest:window_1.XDomainRequest,function(array,iterator){for(var i=0;i<array.length;i++)iterator(array[i])}(["get","put","post","patch","head","delete"],(function(method){createXHR["delete"===method?"del":method]=function(uri,option
s,callback){return(options=initParams(uri,options,callback)).method=method.toUpperCase(),_createXHR(options)}})),lib.default=default_1;const parseCues=function(srcContent,track){const parser=new window.WebVTT.Parser(window,window.vttjs,window.WebVTT.StringDecoder()),errors=[];parser.oncue=function(cue){track.addCue(cue)},parser.onparsingerror=function(error){errors.push(error)},parser.onflush=function(){track.trigger({type:"loadeddata",target:track})},parser.parse(srcContent),errors.length>0&&(window.console&&window.console.groupCollapsed&&window.console.groupCollapsed("Text Track parsing errors for ".concat(track.src)),errors.forEach((error=>log$1.error(error))),window.console&&window.console.groupEnd&&window.console.groupEnd()),parser.flush()},loadTrack=function(src,track){const opts={uri:src},crossOrigin=isCrossOrigin(src);crossOrigin&&(opts.cors=crossOrigin);const withCredentials="use-credentials"===track.tech_.crossOrigin();withCredentials&&(opts.withCredentials=withCredentials),lib(opts,bind_(this,(fun
ction(err,response,responseBody){if(err)return log$1.error(err,response);track.loaded_=!0,"function"!=typeof window.WebVTT?track.tech_&&track.tech_.any(["vttjsloaded","vttjserror"],(event=>{if("vttjserror"!==event.type)return parseCues(responseBody,track);log$1.error("vttjs failed to load, stopping trying to process ".concat(track.src))})):parseCues(responseBody,track)})))};class TextTrack extends Track{constructor(){let options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!options.tech)throw new Error("A tech was not provided.");const settings=merge$2(options,{kind:TextTrackKind[options.kind]||"subtitles",language:options.language||options.srclang||""});let mode=TextTrackMode[settings.mode]||"disabled";const default_=settings.default;"metadata"!==settings.kind&&"chapters"!==settings.kind||(mode="hidden"),super(settings),this.tech_=settings.tech,this.cues_=[],this.activeCues_=[],this.preload_=!1!==this.tech_.preloadTextTracks;const cues=new TextTrackCueList(this.cues_),activeCues=new TextTrac
kCueList(this.activeCues_);let changed=!1;this.timeupdateHandler=bind_(this,(function(){let event=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.tech_.isDisposed()||(this.tech_.isReady_?(this.activeCues=this.activeCues,changed&&(this.trigger("cuechange"),changed=!1),"timeupdate"!==event.type&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler))):"timeupdate"!==event.type&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler)))}));this.tech_.one("dispose",(()=>{this.stopTracking()})),"disabled"!==mode&&this.startTracking(),Object.defineProperties(this,{default:{get:()=>default_,set(){}},mode:{get:()=>mode,set(newMode){TextTrackMode[newMode]&&mode!==newMode&&(mode=newMode,this.preload_||"disabled"===mode||0!==this.cues.length||loadTrack(this.src,this),this.stopTracking(),"disabled"!==mode&&this.startTracking(),this.trigger("modechange"))}},cues:{get(){return this.loaded_?cues:null},set(){}},activeCues:{get(){if(!this.loaded_)return null;if(0===this.cues.len
gth)return activeCues;const ct=this.tech_.currentTime(),active=[];for(let i=0,l=this.cues.length;i<l;i++){const cue=this.cues[i];cue.startTime<=ct&&cue.endTime>=ct&&active.push(cue)}if(changed=!1,active.length!==this.activeCues_.length)changed=!0;else for(let i=0;i<active.length;i++)-1===this.activeCues_.indexOf(active[i])&&(changed=!0);return this.activeCues_=active,activeCues.setCues_(this.activeCues_),activeCues},set(){}}}),settings.src?(this.src=settings.src,this.preload_||(this.loaded_=!0),(this.preload_||"subtitles"!==settings.kind&&"captions"!==settings.kind)&&loadTrack(this.src,this)):this.loaded_=!0}startTracking(){this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler),this.tech_.on("timeupdate",this.timeupdateHandler)}stopTracking(){this.rvf_&&(this.tech_.cancelVideoFrameCallback(this.rvf_),this.rvf_=void 0),this.tech_.off("timeupdate",this.timeupdateHandler)}addCue(originalCue){let cue=originalCue;if(!("getCueAsHTML"in cue)){cue=new window.vttjs.VTTCue(originalCue.startTime,origina
lCue.endTime,originalCue.text);for(const prop in originalCue)prop in cue||(cue[prop]=originalCue[prop]);cue.id=originalCue.id,cue.originalCue_=originalCue}const tracks=this.tech_.textTracks();for(let i=0;i<tracks.length;i++)tracks[i]!==this&&tracks[i].removeCue(cue);this.cues_.push(cue),this.cues.setCues_(this.cues_)}removeCue(removeCue){let i=this.cues_.length;for(;i--;){const cue=this.cues_[i];if(cue===removeCue||cue.originalCue_&&cue.originalCue_===removeCue){this.cues_.splice(i,1),this.cues.setCues_(this.cues_);break}}}}TextTrack.prototype.allowedEvents_={cuechange:"cuechange"};class AudioTrack extends Track{constructor(){let options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const settings=merge$2(options,{kind:AudioTrackKind[options.kind]||""});super(settings);let enabled=!1;Object.defineProperty(this,"enabled",{get:()=>enabled,set(newEnabled){"boolean"==typeof newEnabled&&newEnabled!==enabled&&(enabled=newEnabled,this.trigger("enabledchange"))}}),settings.enabled&&(this.enabled=settings
.enabled),this.loaded_=!0}}class VideoTrack extends Track{constructor(){let options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const settings=merge$2(options,{kind:VideoTrackKind[options.kind]||""});super(settings);let selected=!1;Object.defineProperty(this,"selected",{get:()=>selected,set(newSelected){"boolean"==typeof newSelected&&newSelected!==selected&&(selected=newSelected,this.trigger("selectedchange"))}}),settings.selected&&(this.selected=settings.selected)}}class HTMLTrackElement extends EventTarget$2{constructor(){let readyState,options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super();const track=new TextTrack(options);this.kind=track.kind,this.src=track.src,this.srclang=track.language,this.label=track.label,this.default=track.default,Object.defineProperties(this,{readyState:{get:()=>readyState},track:{get:()=>track}}),readyState=HTMLTrackElement.NONE,track.addEventListener("loadeddata",(()=>{readyState=HTMLTrackElement.LOADED,this.trigger({type:"load",target:this})})
)}}HTMLTrackElement.prototype.allowedEvents_={load:"load"},HTMLTrackElement.NONE=0,HTMLTrackElement.LOADING=1,HTMLTrackElement.LOADED=2,HTMLTrackElement.ERROR=3;const NORMAL={audio:{ListClass:class extends TrackList{constructor(){let tracks=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];for(let i=tracks.length-1;i>=0;i--)if(tracks[i].enabled){disableOthers$1(tracks,tracks[i]);break}super(tracks),this.changing_=!1}addTrack(track){track.enabled&&disableOthers$1(this,track),super.addTrack(track),track.addEventListener&&(track.enabledChange_=()=>{this.changing_||(this.changing_=!0,disableOthers$1(this,track),this.changing_=!1,this.trigger("change"))},track.addEventListener("enabledchange",track.enabledChange_))}removeTrack(rtrack){super.removeTrack(rtrack),rtrack.removeEventListener&&rtrack.enabledChange_&&(rtrack.removeEventListener("enabledchange",rtrack.enabledChange_),rtrack.enabledChange_=null)}},TrackClass:AudioTrack,capitalName:"Audio"},video:{ListClass:class extends TrackList{constructor(){let
tracks=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];for(let i=tracks.length-1;i>=0;i--)if(tracks[i].selected){disableOthers(tracks,tracks[i]);break}super(tracks),this.changing_=!1,Object.defineProperty(this,"selectedIndex",{get(){for(let i=0;i<this.length;i++)if(this[i].selected)return i;return-1},set(){}})}addTrack(track){track.selected&&disableOthers(this,track),super.addTrack(track),track.addEventListener&&(track.selectedChange_=()=>{this.changing_||(this.changing_=!0,disableOthers(this,track),this.changing_=!1,this.trigger("change"))},track.addEventListener("selectedchange",track.selectedChange_))}removeTrack(rtrack){super.removeTrack(rtrack),rtrack.removeEventListener&&rtrack.selectedChange_&&(rtrack.removeEventListener("selectedchange",rtrack.selectedChange_),rtrack.selectedChange_=null)}},TrackClass:VideoTrack,capitalName:"Video"},text:{ListClass:TextTrackList,TrackClass:TextTrack,capitalName:"Text"}};Object.keys(NORMAL).forEach((function(type){NORMAL[type].getterName="".concat(type,"Tra
cks"),NORMAL[type].privateName="".concat(type,"Tracks_")}));const REMOTE={remoteText:{ListClass:TextTrackList,TrackClass:TextTrack,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:class{constructor(){let trackElements=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];this.trackElements_=[],Object.defineProperty(this,"length",{get(){return this.trackElements_.length}});for(let i=0,length=trackElements.length;i<length;i++)this.addTrackElement_(trackElements[i])}addTrackElement_(trackElement){const index=this.trackElements_.length;""+index in this||Object.defineProperty(this,index,{get(){return this.trackElements_[index]}}),-1===this.trackElements_.indexOf(trackElement)&&this.trackElements_.push(trackElement)}getTrackElementByTrack_(track){let trackElement_;for(let i=0,length=this.trackElements_.length;i<length;i++)if(track===this.trackElements_[i].track){trackElement_=this.trackElements_[i];break}return trackElement_}removeTrackElement_(tra
ckElement){for(let i=0,length=this.trackElements_.length;i<length;i++)if(trackElement===this.trackElements_[i]){this.trackElements_[i].track&&"function"==typeof this.trackElements_[i].track.off&&this.trackElements_[i].track.off(),"function"==typeof this.trackElements_[i].off&&this.trackElements_[i].off(),this.trackElements_.splice(i,1);break}}},TrackClass:HTMLTrackElement,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},ALL=Object.assign({},NORMAL,REMOTE);REMOTE.names=Object.keys(REMOTE),NORMAL.names=Object.keys(NORMAL),ALL.names=[].concat(REMOTE.names).concat(NORMAL.names);var doccy,topLevel=void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof window?window:{};"undefined"!=typeof document?doccy=document:(doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"])||(doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"]={});var document_1=doccy,_objCreate=Object.create||function(){function F(){}return function(o){if(1!==arguments.length)throw new Error("Object.create shim only
accepts one parameter.");return F.prototype=o,new F}}();function ParsingError(errorData,message){this.name="ParsingError",this.code=errorData.code,this.message=message||errorData.message}function parseTimeStamp(input){function computeSeconds(h,m,s,f){return 3600*(0|h)+60*(0|m)+(0|s)+(0|f)/1e3}var m=input.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return m?m[3]?computeSeconds(m[1],m[2],m[3].replace(":",""),m[4]):m[1]>59?computeSeconds(m[1],m[2],0,m[4]):computeSeconds(0,m[1],m[2],m[4]):null}function Settings(){this.values=_objCreate(null)}function parseOptions(input,callback,keyValueDelim,groupDelim){var groups=groupDelim?input.split(groupDelim):[input];for(var i in groups)if("string"==typeof groups[i]){var kv=groups[i].split(keyValueDelim);if(2===kv.length)callback(kv[0].trim(),kv[1].trim())}}function parseCue(input,cue,regionList){var oInput=input;function consumeTimeStamp(){var ts=parseTimeStamp(input);if(null===ts)throw new ParsingError(ParsingError.Errors.BadTimeStamp,"Malformed timestamp: "+oInput);r
eturn input=input.replace(/^[^\sa-zA-Z-]+/,""),ts}function skipWhitespace(){input=input.replace(/^\s+/,"")}if(skipWhitespace(),cue.startTime=consumeTimeStamp(),skipWhitespace(),"--\x3e"!==input.substr(0,3))throw new ParsingError(ParsingError.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '--\x3e'): "+oInput);input=input.substr(3),skipWhitespace(),cue.endTime=consumeTimeStamp(),skipWhitespace(),function(input,cue){var settings=new Settings;parseOptions(input,(function(k,v){switch(k){case"region":for(var i=regionList.length-1;i>=0;i--)if(regionList[i].id===v){settings.set(k,regionList[i].region);break}break;case"vertical":settings.alt(k,v,["rl","lr"]);break;case"line":var vals=v.split(","),vals0=vals[0];settings.integer(k,vals0),settings.percent(k,vals0)&&settings.set("snapToLines",!1),settings.alt(k,vals0,["auto"]),2===vals.length&&settings.alt("lineAlign",vals[1],["start","center","end"]);break;case"position":vals=v.split(","),settings.percent(k,vals[0]),2===vals.length&&settings
.alt("positionAlign",vals[1],["start","center","end"]);break;case"size":settings.percent(k,v);break;case"align":settings.alt(k,v,["start","center","end","left","right"])}}),/:/,/\s/),cue.region=settings.get("region",null),cue.vertical=settings.get("vertical","");try{cue.line=settings.get("line","auto")}catch(e){}cue.lineAlign=settings.get("lineAlign","start"),cue.snapToLines=settings.get("snapToLines",!0),cue.size=settings.get("size",100);try{cue.align=settings.get("align","center")}catch(e){cue.align=settings.get("align","middle")}try{cue.position=settings.get("position","auto")}catch(e){cue.position=settings.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},cue.align)}cue.positionAlign=settings.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},cue.align)}(input,cue)}ParsingError.prototype=_objCreate(Error.prototype),ParsingError.prototype.constructor=ParsingError,ParsingError.Errors={BadSignature:{code:0,message:"Malformed WebVTT sign
ature."},BadTimeStamp:{code:1,message:"Malformed time stamp."}},Settings.prototype={set:function(k,v){this.get(k)||""===v||(this.values[k]=v)},get:function(k,dflt,defaultKey){return defaultKey?this.has(k)?this.values[k]:dflt[defaultKey]:this.has(k)?this.values[k]:dflt},has:function(k){return k in this.values},alt:function(k,v,a){for(var n=0;n<a.length;++n)if(v===a[n]){this.set(k,v);break}},integer:function(k,v){/^-?\d+$/.test(v)&&this.set(k,parseInt(v,10))},percent:function(k,v){return!!(v.match(/^([\d]{1,3})(\.[\d]*)?%$/)&&(v=parseFloat(v))>=0&&v<=100)&&(this.set(k,v),!0)}};var TEXTAREA_ELEMENT=document_1.createElement&&document_1.createElement("textarea"),TAG_NAME={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span"},DEFAULT_COLOR_CLASS={white:"rgba(255,255,255,1)",lime:"rgba(0,255,0,1)",cyan:"rgba(0,255,255,1)",red:"rgba(255,0,0,1)",yellow:"rgba(255,255,0,1)",magenta:"rgba(255,0,255,1)",blue:"rgba(0,0,255,1)",black:"rgba(0,0,0,1)"},TAG_ANNOTATION={v:"title",lang:"lang"},NEEDS_PARENT={rt:"r
uby"};function parseContent(window,input){function nextToken(){if(!input)return null;var result,m=input.match(/^([^<]*)(<[^>]*>?)?/);return result=m[1]?m[1]:m[2],input=input.substr(result.length),result}function shouldAdd(current,element){return!NEEDS_PARENT[element.localName]||NEEDS_PARENT[element.localName]===current.localName}function createElement(type,annotation){var tagName=TAG_NAME[type];if(!tagName)return null;var element=window.document.createElement(tagName),name=TAG_ANNOTATION[type];return name&&annotation&&(element[name]=annotation.trim()),element}for(var t,s,rootDiv=window.document.createElement("div"),current=rootDiv,tagStack=[];null!==(t=nextToken());)if("<"!==t[0])current.appendChild(window.document.createTextNode((s=t,TEXTAREA_ELEMENT.innerHTML=s,s=TEXTAREA_ELEMENT.textContent,TEXTAREA_ELEMENT.textContent="",s)));else{if("/"===t[1]){tagStack.length&&tagStack[tagStack.length-1]===t.substr(2).replace(">","")&&(tagStack.pop(),current=current.parentNode);continue}var node,ts=parseTimeStamp(t.sub
str(1,t.length-2));if(ts){node=window.document.createProcessingInstruction("timestamp",ts),current.appendChild(node);continue}var m=t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!m)continue;if(!(node=createElement(m[1],m[3])))continue;if(!shouldAdd(current,node))continue;if(m[2]){var classes=m[2].split(".");classes.forEach((function(cl){var bgColor=/^bg_/.test(cl),colorName=bgColor?cl.slice(3):cl;if(DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)){var propName=bgColor?"background-color":"color",propValue=DEFAULT_COLOR_CLASS[colorName];node.style[propName]=propValue}})),node.className=classes.join(" ")}tagStack.push(m[1]),current.appendChild(node),current=node}return rootDiv}var strongRTLRanges=[[1470,1470],[1472,1472],[1475,1475],[1478,1478],[1488,1514],[1520,1524],[1544,1544],[1547,1547],[1549,1549],[1563,1563],[1566,1610],[1645,1647],[1649,1749],[1765,1766],[1774,1775],[1786,1805],[1807,1808],[1810,1839],[1869,1957],[1969,1969],[1984,2026],[2036,2037],[2042,2042],[2048,2069],[2074,2074],[208
4,2084],[2088,2088],[2096,2110],[2112,2136],[2142,2142],[2208,2208],[2210,2220],[8207,8207],[64285,64285],[64287,64296],[64298,64310],[64312,64316],[64318,64318],[64320,64321],[64323,64324],[64326,64449],[64467,64829],[64848,64911],[64914,64967],[65008,65020],[65136,65140],[65142,65276],[67584,67589],[67592,67592],[67594,67637],[67639,67640],[67644,67644],[67647,67669],[67671,67679],[67840,67867],[67872,67897],[67903,67903],[67968,68023],[68030,68031],[68096,68096],[68112,68115],[68117,68119],[68121,68147],[68160,68167],[68176,68184],[68192,68223],[68352,68405],[68416,68437],[68440,68466],[68472,68479],[68608,68680],[126464,126467],[126469,126495],[126497,126498],[126500,126500],[126503,126503],[126505,126514],[126516,126519],[126521,126521],[126523,126523],[126530,126530],[126535,126535],[126537,126537],[126539,126539],[126541,126543],[126545,126546],[126548,126548],[126551,126551],[126553,126553],[126555,126555],[126557,126557],[126559,126559],[126561,126562],[126564,126564],[126567,126570],[126572,126578]
,[126580,126583],[126585,126588],[126590,126590],[126592,126601],[126603,126619],[126625,126627],[126629,126633],[126635,126651],[1114109,1114109]];function isStrongRTLChar(charCode){for(var i=0;i<strongRTLRanges.length;i++){var currentRange=strongRTLRanges[i];if(charCode>=currentRange[0]&&charCode<=currentRange[1])return!0}return!1}function determineBidi(cueDiv){var nodeStack=[],text="";if(!cueDiv||!cueDiv.childNodes)return"ltr";function pushNodes(nodeStack,node){for(var i=node.childNodes.length-1;i>=0;i--)nodeStack.push(node.childNodes[i])}function nextTextNode(nodeStack){if(!nodeStack||!nodeStack.length)return null;var node=nodeStack.pop(),text=node.textContent||node.innerText;if(text){var m=text.match(/^.*(\n|\r)/);return m?(nodeStack.length=0,m[0]):text}return"ruby"===node.tagName?nextTextNode(nodeStack):node.childNodes?(pushNodes(nodeStack,node),nextTextNode(nodeStack)):void 0}for(pushNodes(nodeStack,cueDiv);text=nextTextNode(nodeStack);)for(var i=0;i<text.length;i++)if(isStrongRTLChar(text.charCodeAt(
i)))return"rtl";return"ltr"}function StyleBox(){}function CueStyleBox(window,cue,styleOptions){StyleBox.call(this),this.cue=cue,this.cueDiv=parseContent(window,cue.text);var styles={color:"rgba(255, 255, 255, 1)",backgroundColor:"rgba(0, 0, 0, 0.8)",position:"relative",left:0,right:0,top:0,bottom:0,display:"inline",writingMode:""===cue.vertical?"horizontal-tb":"lr"===cue.vertical?"vertical-lr":"vertical-rl",unicodeBidi:"plaintext"};this.applyStyles(styles,this.cueDiv),this.div=window.document.createElement("div"),styles={direction:determineBidi(this.cueDiv),writingMode:""===cue.vertical?"horizontal-tb":"lr"===cue.vertical?"vertical-lr":"vertical-rl",unicodeBidi:"plaintext",textAlign:"middle"===cue.align?"center":cue.align,font:styleOptions.font,whiteSpace:"pre-line",position:"absolute"},this.applyStyles(styles),this.div.appendChild(this.cueDiv);var textPos=0;switch(cue.positionAlign){case"start":case"line-left":textPos=cue.position;break;case"center":textPos=cue.position-cue.size/2;break;case"end":case"line-
right":textPos=cue.position-cue.size}""===cue.vertical?this.applyStyles({left:this.formatStyle(textPos,"%"),width:this.formatStyle(cue.size,"%")}):this.applyStyles({top:this.formatStyle(textPos,"%"),height:this.formatStyle(cue.size,"%")}),this.move=function(box){this.applyStyles({top:this.formatStyle(box.top,"px"),bottom:this.formatStyle(box.bottom,"px"),left:this.formatStyle(box.left,"px"),right:this.formatStyle(box.right,"px"),height:this.formatStyle(box.height,"px"),width:this.formatStyle(box.width,"px")})}}function BoxPosition(obj){var lh,height,width,top;if(obj.div){height=obj.div.offsetHeight,width=obj.div.offsetWidth,top=obj.div.offsetTop;var rects=(rects=obj.div.childNodes)&&(rects=rects[0])&&rects.getClientRects&&rects.getClientRects();obj=obj.div.getBoundingClientRect(),lh=rects?Math.max(rects[0]&&rects[0].height||0,obj.height/rects.length):0}this.left=obj.left,this.right=obj.right,this.top=obj.top||top,this.height=obj.height||height,this.bottom=obj.bottom||top+(obj.height||height),this.width=obj.w
idth||width,this.lineHeight=void 0!==lh?lh:obj.lineHeight}function moveBoxToLinePosition(window,styleBox,containerBox,boxPositions){var boxPosition=new BoxPosition(styleBox),cue=styleBox.cue,linePos=function(cue){if("number"==typeof cue.line&&(cue.snapToLines||cue.line>=0&&cue.line<=100))return cue.line;if(!cue.track||!cue.track.textTrackList||!cue.track.textTrackList.mediaElement)return-1;for(var track=cue.track,trackList=track.textTrackList,count=0,i=0;i<trackList.length&&trackList[i]!==track;i++)"showing"===trackList[i].mode&&count++;return-1*++count}(cue),axis=[];if(cue.snapToLines){var size;switch(cue.vertical){case"":axis=["+y","-y"],size="height";break;case"rl":axis=["+x","-x"],size="width";break;case"lr":axis=["-x","+x"],size="width"}var step=boxPosition.lineHeight,position=step*Math.round(linePos),maxPosition=containerBox[size]+step,initialAxis=axis[0];Math.abs(position)>maxPosition&&(position=position<0?-1:1,position*=Math.ceil(maxPosition/step)*step),linePos<0&&(position+=""===cue.vertical?contain
erBox.height:containerBox.width,axis=axis.reverse()),boxPosition.move(initialAxis,position)}else{var calculatedPercentage=boxPosition.lineHeight/containerBox.height*100;switch(cue.lineAlign){case"center":linePos-=calculatedPercentage/2;break;case"end":linePos-=calculatedPercentage}switch(cue.vertical){case"":styleBox.applyStyles({top:styleBox.formatStyle(linePos,"%")});break;case"rl":styleBox.applyStyles({left:styleBox.formatStyle(linePos,"%")});break;case"lr":styleBox.applyStyles({right:styleBox.formatStyle(linePos,"%")})}axis=["+y","-x","+x","-y"],boxPosition=new BoxPosition(styleBox)}var bestPosition=function(b,axis){for(var bestPosition,specifiedPosition=new BoxPosition(b),percentage=1,i=0;i<axis.length;i++){for(;b.overlapsOppositeAxis(containerBox,axis[i])||b.within(containerBox)&&b.overlapsAny(boxPositions);)b.move(axis[i]);if(b.within(containerBox))return b;var p=b.intersectPercentage(containerBox);percentage>p&&(bestPosition=new BoxPosition(b),percentage=p),b=new BoxPosition(specifiedPosition)}return
bestPosition||specifiedPosition}(boxPosition,axis);styleBox.move(bestPosition.toCSSCompatValues(containerBox))}function WebVTT$1(){}StyleBox.prototype.applyStyles=function(styles,div){for(var prop in div=div||this.div,styles)styles.hasOwnProperty(prop)&&(div.style[prop]=styles[prop])},StyleBox.prototype.formatStyle=function(val,unit){return 0===val?0:val+unit},CueStyleBox.prototype=_objCreate(StyleBox.prototype),CueStyleBox.prototype.constructor=CueStyleBox,BoxPosition.prototype.move=function(axis,toMove){switch(toMove=void 0!==toMove?toMove:this.lineHeight,axis){case"+x":this.left+=toMove,this.right+=toMove;break;case"-x":this.left-=toMove,this.right-=toMove;break;case"+y":this.top+=toMove,this.bottom+=toMove;break;case"-y":this.top-=toMove,this.bottom-=toMove}},BoxPosition.prototype.overlaps=function(b2){return this.left<b2.right&&this.right>b2.left&&this.top<b2.bottom&&this.bottom>b2.top},BoxPosition.prototype.overlapsAny=function(boxes){for(var i=0;i<boxes.length;i++)if(this.overlaps(boxes[i]))return!0;
return!1},BoxPosition.prototype.within=function(container){return this.top>=container.top&&this.bottom<=container.bottom&&this.left>=container.left&&this.right<=container.right},BoxPosition.prototype.overlapsOppositeAxis=function(container,axis){switch(axis){case"+x":return this.left<container.left;case"-x":return this.right>container.right;case"+y":return this.top<container.top;case"-y":return this.bottom>container.bottom}},BoxPosition.prototype.intersectPercentage=function(b2){return Math.max(0,Math.min(this.right,b2.right)-Math.max(this.left,b2.left))*Math.max(0,Math.min(this.bottom,b2.bottom)-Math.max(this.top,b2.top))/(this.height*this.width)},BoxPosition.prototype.toCSSCompatValues=function(reference){return{top:this.top-reference.top,bottom:reference.bottom-this.bottom,left:this.left-reference.left,right:reference.right-this.right,height:this.height,width:this.width}},BoxPosition.getSimpleBoxPosition=function(obj){var height=obj.div?obj.div.offsetHeight:obj.tagName?obj.offsetHeight:0,width=obj.div?obj
.div.offsetWidth:obj.tagName?obj.offsetWidth:0,top=obj.div?obj.div.offsetTop:obj.tagName?obj.offsetTop:0;return{left:(obj=obj.div?obj.div.getBoundingClientRect():obj.tagName?obj.getBoundingClientRect():obj).left,right:obj.right,top:obj.top||top,height:obj.height||height,bottom:obj.bottom||top+(obj.height||height),width:obj.width||width}},WebVTT$1.StringDecoder=function(){return{decode:function(data){if(!data)return"";if("string"!=typeof data)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(data))}}},WebVTT$1.convertCueToDOMTree=function(window,cuetext){return window&&cuetext?parseContent(window,cuetext):null};WebVTT$1.processCues=function(window,cues,overlay){if(!window||!cues||!overlay)return null;for(;overlay.firstChild;)overlay.removeChild(overlay.firstChild);var paddedOverlay=window.document.createElement("div");if(paddedOverlay.style.position="absolute",paddedOverlay.style.left="0",paddedOverlay.style.right="0",paddedOverlay.style.top="0",paddedOverlay.style.
bottom="0",paddedOverlay.style.margin="1.5%",overlay.appendChild(paddedOverlay),function(cues){for(var i=0;i<cues.length;i++)if(cues[i].hasBeenReset||!cues[i].displayState)return!0;return!1}(cues)){var boxPositions=[],containerBox=BoxPosition.getSimpleBoxPosition(paddedOverlay),styleOptions={font:Math.round(.05*containerBox.height*100)/100+"px sans-serif"};!function(){for(var styleBox,cue,i=0;i<cues.length;i++)cue=cues[i],styleBox=new CueStyleBox(window,cue,styleOptions),paddedOverlay.appendChild(styleBox.div),moveBoxToLinePosition(0,styleBox,containerBox,boxPositions),cue.displayState=styleBox.div,boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox))}()}else for(var i=0;i<cues.length;i++)paddedOverlay.appendChild(cues[i].displayState)},WebVTT$1.Parser=function(window,vttjs,decoder){decoder||(decoder=vttjs,vttjs={}),vttjs||(vttjs={}),this.window=window,this.vttjs=vttjs,this.state="INITIAL",this.buffer="",this.decoder=decoder||new TextDecoder("utf8"),this.regionList=[]},WebVTT$1.Parser.prototype={repo
rtOrThrowError:function(e){if(!(e instanceof ParsingError))throw e;this.onparsingerror&&this.onparsingerror(e)},parse:function(data){var self=this;function collectNextLine(){for(var buffer=self.buffer,pos=0;pos<buffer.length&&"\r"!==buffer[pos]&&"\n"!==buffer[pos];)++pos;var line=buffer.substr(0,pos);return"\r"===buffer[pos]&&++pos,"\n"===buffer[pos]&&++pos,self.buffer=buffer.substr(pos),line}function parseHeader(input){input.match(/X-TIMESTAMP-MAP/)?parseOptions(input,(function(k,v){if("X-TIMESTAMP-MAP"===k)!function(input){var settings=new Settings;parseOptions(input,(function(k,v){switch(k){case"MPEGT":settings.integer(k+"S",v);break;case"LOCA":settings.set(k+"L",parseTimeStamp(v))}}),/[^\d]:/,/,/),self.ontimestampmap&&self.ontimestampmap({MPEGTS:settings.get("MPEGTS"),LOCAL:settings.get("LOCAL")})}(v)}),/=/):parseOptions(input,(function(k,v){if("Region"===k)!function(input){var settings=new Settings;if(parseOptions(input,(function(k,v){switch(k){case"id":settings.set(k,v);break;case"width":settings.perce
nt(k,v);break;case"lines":settings.integer(k,v);break;case"regionanchor":case"viewportanchor":var xy=v.split(",");if(2!==xy.length)break;var anchor=new Settings;if(anchor.percent("x",xy[0]),anchor.percent("y",xy[1]),!anchor.has("x")||!anchor.has("y"))break;settings.set(k+"X",anchor.get("x")),settings.set(k+"Y",anchor.get("y"));break;case"scroll":settings.alt(k,v,["up"])}}),/=/,/\s/),settings.has("id")){var region=new(self.vttjs.VTTRegion||self.window.VTTRegion);region.width=settings.get("width",100),region.lines=settings.get("lines",3),region.regionAnchorX=settings.get("regionanchorX",0),region.regionAnchorY=settings.get("regionanchorY",100),region.viewportAnchorX=settings.get("viewportanchorX",0),region.viewportAnchorY=settings.get("viewportanchorY",100),region.scroll=settings.get("scroll",""),self.onregion&&self.onregion(region),self.regionList.push({id:settings.get("id"),region:region})}}(v)}),/:/)}data&&(self.buffer+=self.decoder.decode(data,{stream:!0}));try{var line;if("INITIAL"===self.state){if(!/\r\n
|\n/.test(self.buffer))return this;var m=(line=collectNextLine()).match(/^WEBVTT([ \t].*)?$/);if(!m||!m[0])throw new ParsingError(ParsingError.Errors.BadSignature);self.state="HEADER"}for(var alreadyCollectedLine=!1;self.buffer;){if(!/\r\n|\n/.test(self.buffer))return this;switch(alreadyCollectedLine?alreadyCollectedLine=!1:line=collectNextLine(),self.state){case"HEADER":/:/.test(line)?parseHeader(line):line||(self.state="ID");continue;case"NOTE":line||(self.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(line)){self.state="NOTE";break}if(!line)continue;self.cue=new(self.vttjs.VTTCue||self.window.VTTCue)(0,0,"");try{self.cue.align="center"}catch(e){self.cue.align="middle"}if(self.state="CUE",-1===line.indexOf("--\x3e")){self.cue.id=line;continue}case"CUE":try{parseCue(line,self.cue,self.regionList)}catch(e){self.reportOrThrowError(e),self.cue=null,self.state="BADCUE";continue}self.state="CUETEXT";continue;case"CUETEXT":var hasSubstring=-1!==line.indexOf("--\x3e");if(!line||hasSubstring&&(alreadyCollec
tedLine=!0)){self.oncue&&self.oncue(self.cue),self.cue=null,self.state="ID";continue}self.cue.text&&(self.cue.text+="\n"),self.cue.text+=line.replace(/\u2028/g,"\n").replace(/u2029/g,"\n");continue;case"BADCUE":line||(self.state="ID");continue}}}catch(e){self.reportOrThrowError(e),"CUETEXT"===self.state&&self.cue&&self.oncue&&self.oncue(self.cue),self.cue=null,self.state="INITIAL"===self.state?"BADWEBVTT":"BADCUE"}return this},flush:function(){try{if(this.buffer+=this.decoder.decode(),(this.cue||"HEADER"===this.state)&&(this.buffer+="\n\n",this.parse()),"INITIAL"===this.state)throw new ParsingError(ParsingError.Errors.BadSignature)}catch(e){this.reportOrThrowError(e)}return this.onflush&&this.onflush(),this}};var vtt=WebVTT$1,directionSetting={"":1,lr:1,rl:1},alignSetting={start:1,center:1,end:1,left:1,right:1,auto:1,"line-left":1,"line-right":1};function findAlignSetting(value){return"string"==typeof value&&(!!alignSetting[value.toLowerCase()]&&value.toLowerCase())}function VTTCue(startTime,endTime,text){th
is.hasBeenReset=!1;var _id="",_pauseOnExit=!1,_startTime=startTime,_endTime=endTime,_text=text,_region=null,_vertical="",_snapToLines=!0,_line="auto",_lineAlign="start",_position="auto",_positionAlign="auto",_size=100,_align="center";Object.defineProperties(this,{id:{enumerable:!0,get:function(){return _id},set:function(value){_id=""+value}},pauseOnExit:{enumerable:!0,get:function(){return _pauseOnExit},set:function(value){_pauseOnExit=!!value}},startTime:{enumerable:!0,get:function(){return _startTime},set:function(value){if("number"!=typeof value)throw new TypeError("Start time must be set to a number.");_startTime=value,this.hasBeenReset=!0}},endTime:{enumerable:!0,get:function(){return _endTime},set:function(value){if("number"!=typeof value)throw new TypeError("End time must be set to a number.");_endTime=value,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return _text},set:function(value){_text=""+value,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return _region},set:function(
value){_region=value,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return _vertical},set:function(value){var setting=function(value){return"string"==typeof value&&!!directionSetting[value.toLowerCase()]&&value.toLowerCase()}(value);if(!1===setting)throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");_vertical=setting,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return _snapToLines},set:function(value){_snapToLines=!!value,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return _line},set:function(value){if("number"!=typeof value&&"auto"!==value)throw new SyntaxError("Line: an invalid number or illegal string was specified.");_line=value,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return _lineAlign},set:function(value){var setting=findAlignSetting(value);setting?(_lineAlign=setting,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function
(){return _position},set:function(value){if(value<0||value>100)throw new Error("Position must be between 0 and 100.");_position=value,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return _positionAlign},set:function(value){var setting=findAlignSetting(value);setting?(_positionAlign=setting,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return _size},set:function(value){if(value<0||value>100)throw new Error("Size must be between 0 and 100.");_size=value,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return _align},set:function(value){var setting=findAlignSetting(value);if(!setting)throw new SyntaxError("align: an invalid or illegal alignment string was specified.");_align=setting,this.hasBeenReset=!0}}}),this.displayState=void 0}VTTCue.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)};var vttcue=VTTCue,scrollSetting={"":!0,up:!0};function isValidPercentVa
lue(value){return"number"==typeof value&&value>=0&&value<=100}var vttregion=function(){var _width=100,_lines=3,_regionAnchorX=0,_regionAnchorY=100,_viewportAnchorX=0,_viewportAnchorY=100,_scroll="";Object.defineProperties(this,{width:{enumerable:!0,get:function(){return _width},set:function(value){if(!isValidPercentValue(value))throw new Error("Width must be between 0 and 100.");_width=value}},lines:{enumerable:!0,get:function(){return _lines},set:function(value){if("number"!=typeof value)throw new TypeError("Lines must be set to a number.");_lines=value}},regionAnchorY:{enumerable:!0,get:function(){return _regionAnchorY},set:function(value){if(!isValidPercentValue(value))throw new Error("RegionAnchorX must be between 0 and 100.");_regionAnchorY=value}},regionAnchorX:{enumerable:!0,get:function(){return _regionAnchorX},set:function(value){if(!isValidPercentValue(value))throw new Error("RegionAnchorY must be between 0 and 100.");_regionAnchorX=value}},viewportAnchorY:{enumerable:!0,get:function(){return _view
portAnchorY},set:function(value){if(!isValidPercentValue(value))throw new Error("ViewportAnchorY must be between 0 and 100.");_viewportAnchorY=value}},viewportAnchorX:{enumerable:!0,get:function(){return _viewportAnchorX},set:function(value){if(!isValidPercentValue(value))throw new Error("ViewportAnchorX must be between 0 and 100.");_viewportAnchorX=value}},scroll:{enumerable:!0,get:function(){return _scroll},set:function(value){var setting=function(value){return"string"==typeof value&&!!scrollSetting[value.toLowerCase()]&&value.toLowerCase()}(value);!1===setting?console.warn("Scroll: an invalid or illegal string was specified."):_scroll=setting}}})},browserIndex=createCommonjsModule((function(module){var vttjs=module.exports={WebVTT:vtt,VTTCue:vttcue,VTTRegion:vttregion};window_1.vttjs=vttjs,window_1.WebVTT=vttjs.WebVTT;var cueShim=vttjs.VTTCue,regionShim=vttjs.VTTRegion,nativeVTTCue=window_1.VTTCue,nativeVTTRegion=window_1.VTTRegion;vttjs.shim=function(){window_1.VTTCue=cueShim,window_1.VTTRegion=regionShi
m},vttjs.restore=function(){window_1.VTTCue=nativeVTTCue,window_1.VTTRegion=nativeVTTRegion},window_1.VTTCue||vttjs.shim()}));browserIndex.WebVTT,browserIndex.VTTCue,browserIndex.VTTRegion;class Tech extends Component$1{constructor(){let options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},ready=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){};options.reportTouchActivity=!1,super(null,options,ready),this.onDurationChange_=e=>this.onDurationChange(e),this.trackProgress_=e=>this.trackProgress(e),this.trackCurrentTime_=e=>this.trackCurrentTime(e),this.stopTrackingCurrentTime_=e=>this.stopTrackingCurrentTime(e),this.disposeSourceHandler_=e=>this.disposeSourceHandler(e),this.queuedHanders_=new Set,this.hasStarted_=!1,this.on("playing",(function(){this.hasStarted_=!0})),this.on("loadstart",(function(){this.hasStarted_=!1})),ALL.names.forEach((name=>{const props=ALL[name];options&&options[props.getterName]&&(this[props.privateName]=options[props.getterName])})),this.featuresProgressE
vents||this.manualProgressOn(),this.featuresTimeupdateEvents||this.manualTimeUpdatesOn(),["Text","Audio","Video"].forEach((track=>{!1===options["native".concat(track,"Tracks")]&&(this["featuresNative".concat(track,"Tracks")]=!1)})),!1===options.nativeCaptions||!1===options.nativeTextTracks?this.featuresNativeTextTracks=!1:!0!==options.nativeCaptions&&!0!==options.nativeTextTracks||(this.featuresNativeTextTracks=!0),this.featuresNativeTextTracks||this.emulateTextTracks(),this.preloadTextTracks=!1!==options.preloadTextTracks,this.autoRemoteTextTracks_=new ALL.text.ListClass,this.initTrackListeners(),options.nativeControlsForTouch||this.emitTapEvents(),this.constructor&&(this.name_=this.constructor.name||"Unknown Tech")}triggerSourceset(src){this.isReady_||this.one("ready",(()=>this.setTimeout((()=>this.triggerSourceset(src)),1))),this.trigger({src:src,type:"sourceset"})}manualProgressOn(){this.on("durationchange",this.onDurationChange_),this.manualProgress=!0,this.one("ready",this.trackProgress_)}manualProgres
sOff(){this.manualProgress=!1,this.stopTrackingProgress(),this.off("durationchange",this.onDurationChange_)}trackProgress(event){this.stopTrackingProgress(),this.progressInterval=this.setInterval(bind_(this,(function(){const numBufferedPercent=this.bufferedPercent();this.bufferedPercent_!==numBufferedPercent&&this.trigger("progress"),this.bufferedPercent_=numBufferedPercent,1===numBufferedPercent&&this.stopTrackingProgress()})),500)}onDurationChange(event){this.duration_=this.duration()}buffered(){return createTimeRanges$1(0,0)}bufferedPercent(){return bufferedPercent(this.buffered(),this.duration_)}stopTrackingProgress(){this.clearInterval(this.progressInterval)}manualTimeUpdatesOn(){this.manualTimeUpdates=!0,this.on("play",this.trackCurrentTime_),this.on("pause",this.stopTrackingCurrentTime_)}manualTimeUpdatesOff(){this.manualTimeUpdates=!1,this.stopTrackingCurrentTime(),this.off("play",this.trackCurrentTime_),this.off("pause",this.stopTrackingCurrentTime_)}trackCurrentTime(){this.currentTimeInterval&&this
.stopTrackingCurrentTime(),this.currentTimeInterval=this.setInterval((function(){this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}),250)}stopTrackingCurrentTime(){this.clearInterval(this.currentTimeInterval),this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}dispose(){this.clearTracks(NORMAL.names),this.manualProgress&&this.manualProgressOff(),this.manualTimeUpdates&&this.manualTimeUpdatesOff(),super.dispose()}clearTracks(types){(types=[].concat(types)).forEach((type=>{const list=this["".concat(type,"Tracks")]()||[];let i=list.length;for(;i--;){const track=list[i];"text"===type&&this.removeRemoteTextTrack(track),list.removeTrack(track)}}))}cleanupAutoTextTracks(){const list=this.autoRemoteTextTracks_||[];let i=list.length;for(;i--;){const track=list[i];this.removeRemoteTextTrack(track)}}reset(){}crossOrigin(){}setCrossOrigin(){}error(err){return void 0!==err&&(this.error_=new MediaError(err),this.trigger("error")),this.error_}played(){return this.hasStarted_?createTimeRanges
$1(0,0):createTimeRanges$1()}play(){}setScrubbing(_isScrubbing){}scrubbing(){}setCurrentTime(_seconds){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}initTrackListeners(){NORMAL.names.forEach((name=>{const props=NORMAL[name],trackListChanges=()=>{this.trigger("".concat(name,"trackchange"))},tracks=this[props.getterName]();tracks.addEventListener("removetrack",trackListChanges),tracks.addEventListener("addtrack",trackListChanges),this.on("dispose",(()=>{tracks.removeEventListener("removetrack",trackListChanges),tracks.removeEventListener("addtrack",trackListChanges)}))}))}addWebVttScript_(){if(!window.WebVTT)if(document.body.contains(this.el())){if(!this.options_["vtt.js"]&&isPlain(browserIndex)&&Object.keys(browserIndex).length>0)return void this.trigger("vttjsloaded");const script=document.createElement("script");script.src=this.options_["vtt.js"]||"https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js",script.onload=()=>{this.trigger("vttjsloaded")},script.onerror=()=>{
this.trigger("vttjserror")},this.on("dispose",(()=>{script.onload=null,script.onerror=null})),window.WebVTT=!0,this.el().parentNode.appendChild(script)}else this.ready(this.addWebVttScript_)}emulateTextTracks(){const tracks=this.textTracks(),remoteTracks=this.remoteTextTracks(),handleAddTrack=e=>tracks.addTrack(e.track),handleRemoveTrack=e=>tracks.removeTrack(e.track);remoteTracks.on("addtrack",handleAddTrack),remoteTracks.on("removetrack",handleRemoveTrack),this.addWebVttScript_();const updateDisplay=()=>this.trigger("texttrackchange"),textTracksChanges=()=>{updateDisplay();for(let i=0;i<tracks.length;i++){const track=tracks[i];track.removeEventListener("cuechange",updateDisplay),"showing"===track.mode&&track.addEventListener("cuechange",updateDisplay)}};textTracksChanges(),tracks.addEventListener("change",textTracksChanges),tracks.addEventListener("addtrack",textTracksChanges),tracks.addEventListener("removetrack",textTracksChanges),this.on("dispose",(function(){remoteTracks.off("addtrack",handleAddTrack),
remoteTracks.off("removetrack",handleRemoveTrack),tracks.removeEventListener("change",textTracksChanges),tracks.removeEventListener("addtrack",textTracksChanges),tracks.removeEventListener("removetrack",textTracksChanges);for(let i=0;i<tracks.length;i++){tracks[i].removeEventListener("cuechange",updateDisplay)}}))}addTextTrack(kind,label,language){if(!kind)throw new Error("TextTrack kind is required but was not provided");return function(self,kind,label,language){let options=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};const tracks=self.textTracks();options.kind=kind,label&&(options.label=label),language&&(options.language=language),options.tech=self;const track=new ALL.text.TrackClass(options);return tracks.addTrack(track),track}(this,kind,label,language)}createRemoteTextTrack(options){const track=merge$2(options,{tech:this});return new REMOTE.remoteTextEl.TrackClass(track)}addRemoteTextTrack(){let options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},manualCleanup=arguments.length>
1?arguments[1]:void 0;const htmlTrackElement=this.createRemoteTextTrack(options);return"boolean"!=typeof manualCleanup&&(manualCleanup=!1),this.remoteTextTrackEls().addTrackElement_(htmlTrackElement),this.remoteTextTracks().addTrack(htmlTrackElement.track),!1===manualCleanup&&this.ready((()=>this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track))),htmlTrackElement}removeRemoteTextTrack(track){const trackElement=this.remoteTextTrackEls().getTrackElementByTrack_(track);this.remoteTextTrackEls().removeTrackElement_(trackElement),this.remoteTextTracks().removeTrack(track),this.autoRemoteTextTracks_.removeTrack(track)}getVideoPlaybackQuality(){return{}}requestPictureInPicture(){return Promise.reject()}disablePictureInPicture(){return!0}setDisablePictureInPicture(){}requestVideoFrameCallback(cb){const id=newGUID();return!this.isReady_||this.paused()?(this.queuedHanders_.add(id),this.one("playing",(()=>{this.queuedHanders_.has(id)&&(this.queuedHanders_.delete(id),cb())}))):this.requestNamedAnimationFrame(id,cb
),id}cancelVideoFrameCallback(id){this.queuedHanders_.has(id)?this.queuedHanders_.delete(id):this.cancelNamedAnimationFrame(id)}setPoster(){}playsinline(){}setPlaysinline(){}overrideNativeAudioTracks(override){}overrideNativeVideoTracks(override){}canPlayType(_type){return""}static canPlayType(_type){return""}static canPlaySource(srcObj,options){return Tech.canPlayType(srcObj.type)}static isTech(component){return component.prototype instanceof Tech||component instanceof Tech||component===Tech}static registerTech(name,tech){if(Tech.techs_||(Tech.techs_={}),!Tech.isTech(tech))throw new Error("Tech ".concat(name," must be a Tech"));if(!Tech.canPlayType)throw new Error("Techs must have a static canPlayType method on them");if(!Tech.canPlaySource)throw new Error("Techs must have a static canPlaySource method on them");return name=toTitleCase$1(name),Tech.techs_[name]=tech,Tech.techs_[toLowerCase(name)]=tech,"Tech"!==name&&Tech.defaultTechOrder_.push(name),tech}static getTech(name){if(name)return Tech.techs_&&Tech
.techs_[name]?Tech.techs_[name]:(name=toTitleCase$1(name),window&&window.videojs&&window.videojs[name]?(log$1.warn("The ".concat(name," tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)")),window.videojs[name]):void 0)}}ALL.names.forEach((function(name){const props=ALL[name];Tech.prototype[props.getterName]=function(){return this[props.privateName]=this[props.privateName]||new props.ListClass,this[props.privateName]}})),Tech.prototype.featuresVolumeControl=!0,Tech.prototype.featuresMuteControl=!0,Tech.prototype.featuresFullscreenResize=!1,Tech.prototype.featuresPlaybackRate=!1,Tech.prototype.featuresProgressEvents=!1,Tech.prototype.featuresSourceset=!1,Tech.prototype.featuresTimeupdateEvents=!1,Tech.prototype.featuresNativeTextTracks=!1,Tech.prototype.featuresVideoFrameCallback=!1,Tech.withSourceHandlers=function(_Tech){_Tech.registerSourceHandler=function(handler,index){let handlers=_Tech.sourceHandlers;handlers||(handlers=_Tech.sourceHandlers=[]),void
0===index&&(index=handlers.length),handlers.splice(index,0,handler)},_Tech.canPlayType=function(type){const handlers=_Tech.sourceHandlers||[];let can;for(let i=0;i<handlers.length;i++)if(can=handlers[i].canPlayType(type),can)return can;return""},_Tech.selectSourceHandler=function(source,options){const handlers=_Tech.sourceHandlers||[];let can;for(let i=0;i<handlers.length;i++)if(can=handlers[i].canHandleSource(source,options),can)return handlers[i];return null},_Tech.canPlaySource=function(srcObj,options){const sh=_Tech.selectSourceHandler(srcObj,options);return sh?sh.canHandleSource(srcObj,options):""};["seekable","seeking","duration"].forEach((function(fnName){const originalFn=this[fnName];"function"==typeof originalFn&&(this[fnName]=function(){return this.sourceHandler_&&this.sourceHandler_[fnName]?this.sourceHandler_[fnName].apply(this.sourceHandler_,arguments):originalFn.apply(this,arguments)})}),_Tech.prototype),_Tech.prototype.setSource=function(source){let sh=_Tech.selectSourceHandler(source,this.opt
ions_);sh||(_Tech.nativeSourceHandler?sh=_Tech.nativeSourceHandler:log$1.error("No source handler found for the current source.")),this.disposeSourceHandler(),this.off("dispose",this.disposeSourceHandler_),sh!==_Tech.nativeSourceHandler&&(this.currentSource_=source),this.sourceHandler_=sh.handleSource(source,this,this.options_),this.one("dispose",this.disposeSourceHandler_)},_Tech.prototype.disposeSourceHandler=function(){this.currentSource_&&(this.clearTracks(["audio","video"]),this.currentSource_=null),this.cleanupAutoTextTracks(),this.sourceHandler_&&(this.sourceHandler_.dispose&&this.sourceHandler_.dispose(),this.sourceHandler_=null)}},Component$1.registerComponent("Tech",Tech),Tech.registerTech("Tech",Tech),Tech.defaultTechOrder_=[];const middlewares={},middlewareInstances={},TERMINATOR={};function setSource(player,src,next){player.setTimeout((()=>setSourceHelper(src,middlewares[src.type],next,player)),1)}function mediate(middleware,tech,method){let arg=arguments.length>3&&void 0!==arguments[3]?argument
s[3]:null;const callMethod="call"+toTitleCase$1(method),middlewareValue=middleware.reduce(middlewareIterator(callMethod),arg),terminated=middlewareValue===TERMINATOR,returnValue=terminated?null:tech[method](middlewareValue);return executeRight(middleware,method,returnValue,terminated),returnValue}const allowedGetters={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},allowedSetters={setCurrentTime:1,setMuted:1,setVolume:1},allowedMediators={play:1,pause:1};function middlewareIterator(method){return(value,mw)=>value===TERMINATOR?TERMINATOR:mw[method]?mw[method](value):value}function executeRight(mws,method,value,terminated){for(let i=mws.length-1;i>=0;i--){const mw=mws[i];mw[method]&&mw[method](terminated,value)}}function getOrCreateFactory(player,mwFactory){const mws=middlewareInstances[player.id()];let mw=null;if(null==mws)return mw=mwFactory(player),middlewareInstances[player.id()]=[[mwFactory,mw]],mw;for(let i=0;i<mws.length;i++){const[mwf,mwi]=mws[i];mwf===mwFacto
ry&&(mw=mwi)}return null===mw&&(mw=mwFactory(player),mws.push([mwFactory,mw])),mw}function setSourceHelper(){let src=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},middleware=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],next=arguments.length>2?arguments[2]:void 0,player=arguments.length>3?arguments[3]:void 0,acc=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],lastRun=arguments.length>5&&void 0!==arguments[5]&&arguments[5];const[mwFactory,...mwrest]=middleware;if("string"==typeof mwFactory)setSourceHelper(src,middlewares[mwFactory],next,player,acc,lastRun);else if(mwFactory){const mw=getOrCreateFactory(player,mwFactory);if(!mw.setSource)return acc.push(mw),setSourceHelper(src,mwrest,next,player,acc,lastRun);mw.setSource(Object.assign({},src),(function(err,_src){if(err)return setSourceHelper(src,mwrest,next,player,acc,lastRun);acc.push(mw),setSourceHelper(_src,src.type===_src.type?mwrest:middlewares[_src.type],next,player,acc,lastRun)}))}else mwrest.length?setSourceHelper(src,
mwrest,next,player,acc,lastRun):lastRun?next(src,acc):setSourceHelper(src,middlewares["*"],next,player,acc,!0)}const MimetypesKind={opus:"video/ogg",ogv:"video/ogg",mp4:"video/mp4",mov:"video/mp4",m4v:"video/mp4",mkv:"video/x-matroska",m4a:"audio/mp4",mp3:"audio/mpeg",aac:"audio/aac",caf:"audio/x-caf",flac:"audio/flac",oga:"audio/ogg",wav:"audio/wav",m3u8:"application/x-mpegURL",mpd:"application/dash+xml",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",png:"image/png",svg:"image/svg+xml",webp:"image/webp"},getMimetype=function(){let src=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";const ext=getFileExtension(src),mimetype=MimetypesKind[ext.toLowerCase()];return mimetype||""},filterSource=function(src){if(Array.isArray(src)){let newsrc=[];src.forEach((function(srcobj){srcobj=filterSource(srcobj),Array.isArray(srcobj)?newsrc=newsrc.concat(srcobj):isObject$1(srcobj)&&newsrc.push(srcobj)})),src=newsrc}else src="string"==typeof src&&src.trim()?[fixSource({src:src})]:isObject$1(src)&&"string"==typeo
f src.src&&src.src&&src.src.trim()?[fixSource(src)]:[];return src};function fixSource(src){if(!src.type){const mimetype=getMimetype(src.src);mimetype&&(src.type=mimetype)}return src}Component$1.registerComponent("MediaLoader",class extends Component$1{constructor(player,options,ready){if(super(player,merge$2({createEl:!1},options),ready),options.playerOptions.sources&&0!==options.playerOptions.sources.length)player.src(options.playerOptions.sources);else for(let i=0,j=options.playerOptions.techOrder;i<j.length;i++){const techName=toTitleCase$1(j[i]);let tech=Tech.getTech(techName);if(techName||(tech=Component$1.getComponent(techName)),tech&&tech.isSupported()){player.loadTech_(techName);break}}}});class ClickableComponent extends Component$1{constructor(player,options){super(player,options),this.options_.controlText&&this.controlText(this.options_.controlText),this.handleMouseOver_=e=>this.handleMouseOver(e),this.handleMouseOut_=e=>this.handleMouseOut(e),this.handleClick_=e=>this.handleClick(e),this.handleKe
yDown_=e=>this.handleKeyDown(e),this.emitTapEvents(),this.enable()}createEl(){let tag=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"div",props=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},attributes=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};props=Object.assign({className:this.buildCSSClass(),tabIndex:0},props),"button"===tag&&log$1.error("Creating a ClickableComponent with an HTML element of ".concat(tag," is not supported; use a Button instead.")),attributes=Object.assign({role:"button"},attributes),this.tabIndex_=props.tabIndex;const el=createEl(tag,props,attributes);return this.player_.options_.experimentalSvgIcons||el.appendChild(createEl("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(el),el}dispose(){this.controlTextEl_=null,super.dispose()}createControlTextEl(el){return this.controlTextEl_=createEl("span",{className:"vjs-control-text"},{"aria-live":"polite"}),el&&el.appendChild(this.controlTextEl_),this.controlText(this.con
trolText_,el),this.controlTextEl_}controlText(text){let el=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.el();if(void 0===text)return this.controlText_||"Need Text";const localizedText=this.localize(text);this.controlText_=text,textContent(this.controlTextEl_,localizedText),this.nonIconControl||this.player_.options_.noUITitleAttributes||el.setAttribute("title",localizedText)}buildCSSClass(){return"vjs-control vjs-button ".concat(super.buildCSSClass())}enable(){this.enabled_||(this.enabled_=!0,this.removeClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","false"),void 0!==this.tabIndex_&&this.el_.setAttribute("tabIndex",this.tabIndex_),this.on(["tap","click"],this.handleClick_),this.on("keydown",this.handleKeyDown_))}disable(){this.enabled_=!1,this.addClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","true"),void 0!==this.tabIndex_&&this.el_.removeAttribute("tabIndex"),this.off("mouseover",this.handleMouseOver_),this.off("mouseout",this.handleMouseOut_),this.off(["tap","click"
],this.handleClick_),this.off("keydown",this.handleKeyDown_)}handleLanguagechange(){this.controlText(this.controlText_)}handleClick(event){this.options_.clickHandler&&this.options_.clickHandler.call(this,arguments)}handleKeyDown(event){keycode.isEventKey(event,"Space")||keycode.isEventKey(event,"Enter")?(event.preventDefault(),event.stopPropagation(),this.trigger("click")):super.handleKeyDown(event)}}Component$1.registerComponent("ClickableComponent",ClickableComponent);class PosterImage extends ClickableComponent{constructor(player,options){super(player,options),this.update(),this.update_=e=>this.update(e),player.on("posterchange",this.update_)}dispose(){this.player().off("posterchange",this.update_),super.dispose()}createEl(){return createEl("div",{className:"vjs-poster"})}crossOrigin(value){if(void 0===value)return this.$("img")?this.$("img").crossOrigin:this.player_.tech_&&this.player_.tech_.isReady_?this.player_.crossOrigin():this.player_.options_.crossOrigin||this.player_.options_.crossorigin||null;nul
l===value||"anonymous"===value||"use-credentials"===value?this.$("img")&&(this.$("img").crossOrigin=value):this.player_.log.warn('crossOrigin must be null, "anonymous" or "use-credentials", given "'.concat(value,'"'))}update(event){const url=this.player().poster();this.setSrc(url),url?this.show():this.hide()}setSrc(url){url?(this.$("img")||this.el_.appendChild(createEl("picture",{className:"vjs-poster",tabIndex:-1},{},createEl("img",{loading:"lazy",crossOrigin:this.crossOrigin()},{alt:""}))),this.$("img").src=url):this.el_.textContent=""}handleClick(event){this.player_.controls()&&(this.player_.tech(!0)&&this.player_.tech(!0).focus(),this.player_.paused()?silencePromise(this.player_.play()):this.player_.pause())}}PosterImage.prototype.crossorigin=PosterImage.prototype.crossOrigin,Component$1.registerComponent("PosterImage",PosterImage);const fontMap={monospace:"monospace",sansSerif:"sans-serif",serif:"serif",monospaceSansSerif:'"Andale Mono", "Lucida Console", monospace',monospaceSerif:'"Courier New", monos
pace',proportionalSansSerif:"sans-serif",proportionalSerif:"serif",casual:'"Comic Sans MS", Impact, fantasy',script:'"Monotype Corsiva", cursive',smallcaps:'"Andale Mono", "Lucida Console", monospace, sans-serif'};function constructColor(color,opacity){let hex;if(4===color.length)hex=color[1]+color[1]+color[2]+color[2]+color[3]+color[3];else{if(7!==color.length)throw new Error("Invalid color code provided, "+color+"; must be formatted as e.g. #f0e or #f604e2.");hex=color.slice(1)}return"rgba("+parseInt(hex.slice(0,2),16)+","+parseInt(hex.slice(2,4),16)+","+parseInt(hex.slice(4,6),16)+","+opacity+")"}function tryUpdateStyle(el,style,rule){try{el.style[style]=rule}catch(e){return}}function getCSSPositionValue(position){return position?"".concat(position,"px"):""}Component$1.registerComponent("TextTrackDisplay",class extends Component$1{constructor(player,options,ready){super(player,options,ready);const updateDisplayHandler=e=>{this.updateDisplayOverlay(),this.updateDisplay(e)};player.on("loadstart",(e=>this.to
ggleDisplay(e))),player.on("texttrackchange",(e=>this.updateDisplay(e))),player.on("loadedmetadata",(e=>{this.updateDisplayOverlay(),this.preselectTrack(e)})),player.ready(bind_(this,(function(){if(player.tech_&&player.tech_.featuresNativeTextTracks)return void this.hide();player.on("fullscreenchange",updateDisplayHandler),player.on("playerresize",updateDisplayHandler);const screenOrientation=window.screen.orientation||window,changeOrientationEvent=window.screen.orientation?"change":"orientationchange";screenOrientation.addEventListener(changeOrientationEvent,updateDisplayHandler),player.on("dispose",(()=>screenOrientation.removeEventListener(changeOrientationEvent,updateDisplayHandler)));const tracks=this.options_.playerOptions.tracks||[];for(let i=0;i<tracks.length;i++)this.player_.addRemoteTextTrack(tracks[i],!0);this.preselectTrack()})))}preselectTrack(){const modes={captions:1,subtitles:1},trackList=this.player_.textTracks(),userPref=this.player_.cache_.selectedLanguage;let firstDesc,firstCaptions,prefe
rredTrack;for(let i=0;i<trackList.length;i++){const track=trackList[i];userPref&&userPref.enabled&&userPref.language&&userPref.language===track.language&&track.kind in modes?track.kind===userPref.kind?preferredTrack=track:preferredTrack||(preferredTrack=track):userPref&&!userPref.enabled?(preferredTrack=null,firstDesc=null,firstCaptions=null):track.default&&("descriptions"!==track.kind||firstDesc?track.kind in modes&&!firstCaptions&&(firstCaptions=track):firstDesc=track)}preferredTrack?preferredTrack.mode="showing":firstCaptions?firstCaptions.mode="showing":firstDesc&&(firstDesc.mode="showing")}toggleDisplay(){this.player_.tech_&&this.player_.tech_.featuresNativeTextTracks?this.hide():this.show()}createEl(){return super.createEl("div",{className:"vjs-text-track-display"},{translate:"yes","aria-live":"off","aria-atomic":"true"})}clearDisplay(){"function"==typeof window.WebVTT&&window.WebVTT.processCues(window,[],this.el_)}updateDisplay(){const tracks=this.player_.textTracks(),allowMultipleShowingTracks=this.o
ptions_.allowMultipleShowingTracks;if(this.clearDisplay(),allowMultipleShowingTracks){const showingTracks=[];for(let i=0;i<tracks.length;++i){const track=tracks[i];"showing"===track.mode&&showingTracks.push(track)}return void this.updateForTrack(showingTracks)}let descriptionsTrack=null,captionsSubtitlesTrack=null,i=tracks.length;for(;i--;){const track=tracks[i];"showing"===track.mode&&("descriptions"===track.kind?descriptionsTrack=track:captionsSubtitlesTrack=track)}captionsSubtitlesTrack?("off"!==this.getAttribute("aria-live")&&this.setAttribute("aria-live","off"),this.updateForTrack(captionsSubtitlesTrack)):descriptionsTrack&&("assertive"!==this.getAttribute("aria-live")&&this.setAttribute("aria-live","assertive"),this.updateForTrack(descriptionsTrack))}updateDisplayOverlay(){if(!this.player_.videoHeight()||!window.CSS.supports("inset-inline: 10px"))return;const playerWidth=this.player_.currentWidth(),playerHeight=this.player_.currentHeight(),playerAspectRatio=playerWidth/playerHeight,videoAspectRatio=thi
s.player_.videoWidth()/this.player_.videoHeight();let insetInlineMatch=0,insetBlockMatch=0;Math.abs(playerAspectRatio-videoAspectRatio)>.1&&(playerAspectRatio>videoAspectRatio?insetInlineMatch=Math.round((playerWidth-playerHeight*videoAspectRatio)/2):insetBlockMatch=Math.round((playerHeight-playerWidth/videoAspectRatio)/2)),tryUpdateStyle(this.el_,"insetInline",getCSSPositionValue(insetInlineMatch)),tryUpdateStyle(this.el_,"insetBlock",getCSSPositionValue(insetBlockMatch))}updateDisplayState(track){const overrides=this.player_.textTrackSettings.getValues(),cues=track.activeCues;let i=cues.length;for(;i--;){const cue=cues[i];if(!cue)continue;const cueDiv=cue.displayState;if(overrides.color&&(cueDiv.firstChild.style.color=overrides.color),overrides.textOpacity&&tryUpdateStyle(cueDiv.firstChild,"color",constructColor(overrides.color||"#fff",overrides.textOpacity)),overrides.backgroundColor&&(cueDiv.firstChild.style.backgroundColor=overrides.backgroundColor),overrides.backgroundOpacity&&tryUpdateStyle(cueDiv.fir
stChild,"backgroundColor",constructColor(overrides.backgroundColor||"#000",overrides.backgroundOpacity)),overrides.windowColor&&(overrides.windowOpacity?tryUpdateStyle(cueDiv,"backgroundColor",constructColor(overrides.windowColor,overrides.windowOpacity)):cueDiv.style.backgroundColor=overrides.windowColor),overrides.edgeStyle&&("dropshadow"===overrides.edgeStyle?cueDiv.firstChild.style.textShadow="2px 2px 3px ".concat("#222",", 2px 2px 4px ").concat("#222",", 2px 2px 5px ").concat("#222"):"raised"===overrides.edgeStyle?cueDiv.firstChild.style.textShadow="1px 1px ".concat("#222",", 2px 2px ").concat("#222",", 3px 3px ").concat("#222"):"depressed"===overrides.edgeStyle?cueDiv.firstChild.style.textShadow="1px 1px ".concat("#ccc",", 0 1px ").concat("#ccc",", -1px -1px ").concat("#222",", 0 -1px ").concat("#222"):"uniform"===overrides.edgeStyle&&(cueDiv.firstChild.style.textShadow="0 0 4px ".concat("#222",", 0 0 4px ").concat("#222",", 0 0 4px ").concat("#222",", 0 0 4px ").concat("#222"))),overrides.fontPercent&
&1!==overrides.fontPercent){const fontSize=window.parseFloat(cueDiv.style.fontSize);cueDiv.style.fontSize=fontSize*overrides.fontPercent+"px",cueDiv.style.height="auto",cueDiv.style.top="auto"}overrides.fontFamily&&"default"!==overrides.fontFamily&&("small-caps"===overrides.fontFamily?cueDiv.firstChild.style.fontVariant="small-caps":cueDiv.firstChild.style.fontFamily=fontMap[overrides.fontFamily])}}updateForTrack(tracks){if(Array.isArray(tracks)||(tracks=[tracks]),"function"!=typeof window.WebVTT||tracks.every((track=>!track.activeCues)))return;const cues=[];for(let i=0;i<tracks.length;++i){const track=tracks[i];for(let j=0;j<track.activeCues.length;++j)cues.push(track.activeCues[j])}window.WebVTT.processCues(window,cues,this.el_);for(let i=0;i<tracks.length;++i){const track=tracks[i];for(let j=0;j<track.activeCues.length;++j){const cueEl=track.activeCues[j].displayState;addClass(cueEl,"vjs-text-track-cue","vjs-text-track-cue-"+(track.language?track.language:i)),track.language&&setAttribute(cueEl,"lang",trac
k.language)}this.player_.textTrackSettings&&this.updateDisplayState(track)}}});Component$1.registerComponent("LoadingSpinner",class extends Component$1{createEl(){const isAudio=this.player_.isAudio(),playerType=this.localize(isAudio?"Audio Player":"Video Player"),controlText=createEl("span",{className:"vjs-control-text",textContent:this.localize("{1} is loading.",[playerType])}),el=super.createEl("div",{className:"vjs-loading-spinner",dir:"ltr"});return el.appendChild(controlText),el}handleLanguagechange(){this.$(".vjs-control-text").textContent=this.localize("{1} is loading.",[this.player_.isAudio()?"Audio Player":"Video Player"])}});class Button extends ClickableComponent{createEl(tag){let props=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},attributes=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};tag="button",props=Object.assign({className:this.buildCSSClass()},props),attributes=Object.assign({type:"button"},attributes);const el=createEl("button",props,attributes);return this.player
_.options_.experimentalSvgIcons||el.appendChild(createEl("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(el),el}addChild(child){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const className=this.constructor.name;return log$1.warn("Adding an actionable (user controllable) child to a Button (".concat(className,") is not supported; use a ClickableComponent instead.")),Component$1.prototype.addChild.call(this,child,options)}enable(){super.enable(),this.el_.removeAttribute("disabled")}disable(){super.disable(),this.el_.setAttribute("disabled","disabled")}handleKeyDown(event){keycode.isEventKey(event,"Space")||keycode.isEventKey(event,"Enter")?event.stopPropagation():super.handleKeyDown(event)}}Component$1.registerComponent("Button",Button);class BigPlayButton extends Button{constructor(player,options){super(player,options),this.mouseused_=!1,this.setIcon("play"),this.on("mousedown",(e=>this.handleMouseDown(e)))}buildCSSClass(){return"vjs-big-play-but
ton"}handleClick(event){const playPromise=this.player_.play();if(this.mouseused_&&"clientX"in event&&"clientY"in event)return silencePromise(playPromise),void(this.player_.tech(!0)&&this.player_.tech(!0).focus());const cb=this.player_.getChild("controlBar"),playToggle=cb&&cb.getChild("playToggle");if(!playToggle)return void this.player_.tech(!0).focus();const playFocus=()=>playToggle.focus();isPromise(playPromise)?playPromise.then(playFocus,(()=>{})):this.setTimeout(playFocus,1)}handleKeyDown(event){this.mouseused_=!1,super.handleKeyDown(event)}handleMouseDown(event){this.mouseused_=!0}}BigPlayButton.prototype.controlText_="Play Video",Component$1.registerComponent("BigPlayButton",BigPlayButton);Component$1.registerComponent("CloseButton",class extends Button{constructor(player,options){super(player,options),this.setIcon("cancel"),this.controlText(options&&options.controlText||this.localize("Close"))}buildCSSClass(){return"vjs-close-button ".concat(super.buildCSSClass())}handleClick(event){this.trigger({type
:"close",bubbles:!1})}handleKeyDown(event){keycode.isEventKey(event,"Esc")?(event.preventDefault(),event.stopPropagation(),this.trigger("click")):super.handleKeyDown(event)}});class PlayToggle extends Button{constructor(player){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(player,options),options.replay=void 0===options.replay||options.replay,this.setIcon("play"),this.on(player,"play",(e=>this.handlePlay(e))),this.on(player,"pause",(e=>this.handlePause(e))),options.replay&&this.on(player,"ended",(e=>this.handleEnded(e)))}buildCSSClass(){return"vjs-play-control ".concat(super.buildCSSClass())}handleClick(event){this.player_.paused()?silencePromise(this.player_.play()):this.player_.pause()}handleSeeked(event){this.removeClass("vjs-ended"),this.player_.paused()?this.handlePause(event):this.handlePlay(event)}handlePlay(event){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.setIcon("pause"),this.controlText("Pause")}handlePause(event){this.removeClass("vj
s-playing"),this.addClass("vjs-paused"),this.setIcon("play"),this.controlText("Play")}handleEnded(event){this.removeClass("vjs-playing"),this.addClass("vjs-ended"),this.setIcon("replay"),this.controlText("Replay"),this.one(this.player_,"seeked",(e=>this.handleSeeked(e)))}}PlayToggle.prototype.controlText_="Play",Component$1.registerComponent("PlayToggle",PlayToggle);class TimeDisplay extends Component$1{constructor(player,options){super(player,options),this.on(player,["timeupdate","ended","seeking"],(e=>this.update(e))),this.updateTextNode_()}createEl(){const className=this.buildCSSClass(),el=super.createEl("div",{className:"".concat(className," vjs-time-control vjs-control")}),span=createEl("span",{className:"vjs-control-text",textContent:"".concat(this.localize(this.labelText_)," ")},{role:"presentation"});return el.appendChild(span),this.contentEl_=createEl("span",{className:"".concat(className,"-display")},{role:"presentation"}),el.appendChild(this.contentEl_),el}dispose(){this.contentEl_=null,this.text
Node_=null,super.dispose()}update(event){(this.player_.options_.enableSmoothSeeking||"seeking"!==event.type)&&this.updateContent(event)}updateTextNode_(){let time=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;time=formatTime(time),this.formattedTime_!==time&&(this.formattedTime_=time,this.requestNamedAnimationFrame("TimeDisplay#updateTextNode_",(()=>{if(!this.contentEl_)return;let oldNode=this.textNode_;oldNode&&this.contentEl_.firstChild!==oldNode&&(oldNode=null,log$1.warn("TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.")),this.textNode_=document.createTextNode(this.formattedTime_),this.textNode_&&(oldNode?this.contentEl_.replaceChild(this.textNode_,oldNode):this.contentEl_.appendChild(this.textNode_))})))}updateContent(event){}}TimeDisplay.prototype.labelText_="Time",TimeDisplay.prototype.controlText_="Time",Component$1.registerComponent("TimeDisplay",TimeDisplay);class CurrentTimeDisplay extends
TimeDisplay{buildCSSClass(){return"vjs-current-time"}updateContent(event){let time;time=this.player_.ended()?this.player_.duration():this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime(),this.updateTextNode_(time)}}CurrentTimeDisplay.prototype.labelText_="Current Time",CurrentTimeDisplay.prototype.controlText_="Current Time",Component$1.registerComponent("CurrentTimeDisplay",CurrentTimeDisplay);class DurationDisplay extends TimeDisplay{constructor(player,options){super(player,options);const updateContent=e=>this.updateContent(e);this.on(player,"durationchange",updateContent),this.on(player,"loadstart",updateContent),this.on(player,"loadedmetadata",updateContent)}buildCSSClass(){return"vjs-duration"}updateContent(event){const duration=this.player_.duration();this.updateTextNode_(duration)}}DurationDisplay.prototype.labelText_="Duration",DurationDisplay.prototype.controlText_="Duration",Component$1.registerComponent("DurationDisplay",DurationDisplay);Component$1.registerCompon
ent("TimeDivider",class extends Component$1{createEl(){const el=super.createEl("div",{className:"vjs-time-control vjs-time-divider"},{"aria-hidden":!0}),div=super.createEl("div"),span=super.createEl("span",{textContent:"/"});return div.appendChild(span),el.appendChild(div),el}});class RemainingTimeDisplay extends TimeDisplay{constructor(player,options){super(player,options),this.on(player,"durationchange",(e=>this.updateContent(e)))}buildCSSClass(){return"vjs-remaining-time"}createEl(){const el=super.createEl();return!1!==this.options_.displayNegative&&el.insertBefore(createEl("span",{},{"aria-hidden":!0},"-"),this.contentEl_),el}updateContent(event){if("number"!=typeof this.player_.duration())return;let time;time=this.player_.ended()?0:this.player_.remainingTimeDisplay?this.player_.remainingTimeDisplay():this.player_.remainingTime(),this.updateTextNode_(time)}}RemainingTimeDisplay.prototype.labelText_="Remaining Time",RemainingTimeDisplay.prototype.controlText_="Remaining Time",Component$1.registerComponent
("RemainingTimeDisplay",RemainingTimeDisplay);Component$1.registerComponent("LiveDisplay",class extends Component$1{constructor(player,options){super(player,options),this.updateShowing(),this.on(this.player(),"durationchange",(e=>this.updateShowing(e)))}createEl(){const el=super.createEl("div",{className:"vjs-live-control vjs-control"});return this.contentEl_=createEl("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(createEl("span",{className:"vjs-control-text",textContent:"".concat(this.localize("Stream Type")," ")})),this.contentEl_.appendChild(document.createTextNode(this.localize("LIVE"))),el.appendChild(this.contentEl_),el}dispose(){this.contentEl_=null,super.dispose()}updateShowing(event){this.player().duration()===1/0?this.show():this.hide()}});class SeekToLive extends Button{constructor(player,options){super(player,options),this.updateLiveEdgeStatus(),this.player_.liveTracker&&(this.updateLiveEdgeStatusHandler_=e=>this.updateLiveEdgeStatus(e),this.on(this.player_
.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_))}createEl(){const el=super.createEl("button",{className:"vjs-seek-to-live-control vjs-control"});return this.setIcon("circle",el),this.textEl_=createEl("span",{className:"vjs-seek-to-live-text",textContent:this.localize("LIVE")},{"aria-hidden":"true"}),el.appendChild(this.textEl_),el}updateLiveEdgeStatus(){!this.player_.liveTracker||this.player_.liveTracker.atLiveEdge()?(this.setAttribute("aria-disabled",!0),this.addClass("vjs-at-live-edge"),this.controlText("Seek to live, currently playing live")):(this.setAttribute("aria-disabled",!1),this.removeClass("vjs-at-live-edge"),this.controlText("Seek to live, currently behind live"))}handleClick(){this.player_.liveTracker.seekToLiveEdge()}dispose(){this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_),this.textEl_=null,super.dispose()}}function clamp(number,min,max){return number=Number(number),Math.min(max,Math.max(min,isNaN(number)?min:numb
er))}SeekToLive.prototype.controlText_="Seek to live, currently playing live",Component$1.registerComponent("SeekToLive",SeekToLive);var Num=Object.freeze({__proto__:null,clamp:clamp});class Slider extends Component$1{constructor(player,options){super(player,options),this.handleMouseDown_=e=>this.handleMouseDown(e),this.handleMouseUp_=e=>this.handleMouseUp(e),this.handleKeyDown_=e=>this.handleKeyDown(e),this.handleClick_=e=>this.handleClick(e),this.handleMouseMove_=e=>this.handleMouseMove(e),this.update_=e=>this.update(e),this.bar=this.getChild(this.options_.barName),this.vertical(!!this.options_.vertical),this.enable()}enabled(){return this.enabled_}enable(){this.enabled()||(this.on("mousedown",this.handleMouseDown_),this.on("touchstart",this.handleMouseDown_),this.on("keydown",this.handleKeyDown_),this.on("click",this.handleClick_),this.on(this.player_,"controlsvisible",this.update),this.playerEvent&&this.on(this.player_,this.playerEvent,this.update),this.removeClass("disabled"),this.setAttribute("tabindex
",0),this.enabled_=!0)}disable(){if(!this.enabled())return;const doc=this.bar.el_.ownerDocument;this.off("mousedown",this.handleMouseDown_),this.off("touchstart",this.handleMouseDown_),this.off("keydown",this.handleKeyDown_),this.off("click",this.handleClick_),this.off(this.player_,"controlsvisible",this.update_),this.off(doc,"mousemove",this.handleMouseMove_),this.off(doc,"mouseup",this.handleMouseUp_),this.off(doc,"touchmove",this.handleMouseMove_),this.off(doc,"touchend",this.handleMouseUp_),this.removeAttribute("tabindex"),this.addClass("disabled"),this.playerEvent&&this.off(this.player_,this.playerEvent,this.update),this.enabled_=!1}createEl(type){let props=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},attributes=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return props.className=props.className+" vjs-slider",props=Object.assign({tabIndex:0},props),attributes=Object.assign({role:"slider","aria-valuenow":0,"aria-valuemin":0,"aria-valuemax":100},attributes),super.createEl(type,pro
ps,attributes)}handleMouseDown(event){const doc=this.bar.el_.ownerDocument;"mousedown"===event.type&&event.preventDefault(),"touchstart"!==event.type||IS_CHROME||event.preventDefault(),blockTextSelection(),this.addClass("vjs-sliding"),this.trigger("slideractive"),this.on(doc,"mousemove",this.handleMouseMove_),this.on(doc,"mouseup",this.handleMouseUp_),this.on(doc,"touchmove",this.handleMouseMove_),this.on(doc,"touchend",this.handleMouseUp_),this.handleMouseMove(event,!0)}handleMouseMove(event){}handleMouseUp(event){const doc=this.bar.el_.ownerDocument;unblockTextSelection(),this.removeClass("vjs-sliding"),this.trigger("sliderinactive"),this.off(doc,"mousemove",this.handleMouseMove_),this.off(doc,"mouseup",this.handleMouseUp_),this.off(doc,"touchmove",this.handleMouseMove_),this.off(doc,"touchend",this.handleMouseUp_),this.update()}update(){if(!this.el_||!this.bar)return;const progress=this.getProgress();return progress===this.progress_||(this.progress_=progress,this.requestNamedAnimationFrame("Slider#update"
,(()=>{const sizeKey=this.vertical()?"height":"width";this.bar.el().style[sizeKey]=(100*progress).toFixed(2)+"%"}))),progress}getProgress(){return Number(clamp(this.getPercent(),0,1).toFixed(4))}calculateDistance(event){const position=getPointerPosition(this.el_,event);return this.vertical()?position.y:position.x}handleKeyDown(event){keycode.isEventKey(event,"Left")||keycode.isEventKey(event,"Down")?(event.preventDefault(),event.stopPropagation(),this.stepBack()):keycode.isEventKey(event,"Right")||keycode.isEventKey(event,"Up")?(event.preventDefault(),event.stopPropagation(),this.stepForward()):super.handleKeyDown(event)}handleClick(event){event.stopPropagation(),event.preventDefault()}vertical(bool){if(void 0===bool)return this.vertical_||!1;this.vertical_=!!bool,this.vertical_?this.addClass("vjs-slider-vertical"):this.addClass("vjs-slider-horizontal")}}Component$1.registerComponent("Slider",Slider);const percentify=(time,end)=>clamp(time/end*100,0,100).toFixed(2)+"%";Component$1.registerComponent("LoadProg
ressBar",class extends Component$1{constructor(player,options){super(player,options),this.partEls_=[],this.on(player,"progress",(e=>this.update(e)))}createEl(){const el=super.createEl("div",{className:"vjs-load-progress"}),wrapper=createEl("span",{className:"vjs-control-text"}),loadedText=createEl("span",{textContent:this.localize("Loaded")}),separator=document.createTextNode(": ");return this.percentageEl_=createEl("span",{className:"vjs-control-text-loaded-percentage",textContent:"0%"}),el.appendChild(wrapper),wrapper.appendChild(loadedText),wrapper.appendChild(separator),wrapper.appendChild(this.percentageEl_),el}dispose(){this.partEls_=null,this.percentageEl_=null,super.dispose()}update(event){this.requestNamedAnimationFrame("LoadProgressBar#update",(()=>{const liveTracker=this.player_.liveTracker,buffered=this.player_.buffered(),duration=liveTracker&&liveTracker.isLive()?liveTracker.seekableEnd():this.player_.duration(),bufferedEnd=this.player_.bufferedEnd(),children=this.partEls_,percent=percentify(buf
feredEnd,duration);this.percent_!==percent&&(this.el_.style.width=percent,textContent(this.percentageEl_,percent),this.percent_=percent);for(let i=0;i<buffered.length;i++){const start=buffered.start(i),end=buffered.end(i);let part=children[i];part||(part=this.el_.appendChild(createEl()),children[i]=part),part.dataset.start===start&&part.dataset.end===end||(part.dataset.start=start,part.dataset.end=end,part.style.left=percentify(start,bufferedEnd),part.style.width=percentify(end-start,bufferedEnd))}for(let i=children.length;i>buffered.length;i--)this.el_.removeChild(children[i-1]);children.length=buffered.length}))}});Component$1.registerComponent("TimeTooltip",class extends Component$1{constructor(player,options){super(player,options),this.update=throttle(bind_(this,this.update),30)}createEl(){return super.createEl("div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})}update(seekBarRect,seekBarPoint,content){const tooltipRect=findPosition(this.el_),playerRect=getBoundingClientRect(this.player_.el()),s
eekBarPointPx=seekBarRect.width*seekBarPoint;if(!playerRect||!tooltipRect)return;const spaceLeftOfPoint=seekBarRect.left-playerRect.left+seekBarPointPx,spaceRightOfPoint=seekBarRect.width-seekBarPointPx+(playerRect.right-seekBarRect.right);let pullTooltipBy=tooltipRect.width/2;spaceLeftOfPoint<pullTooltipBy?pullTooltipBy+=pullTooltipBy-spaceLeftOfPoint:spaceRightOfPoint<pullTooltipBy&&(pullTooltipBy=spaceRightOfPoint),pullTooltipBy<0?pullTooltipBy=0:pullTooltipBy>tooltipRect.width&&(pullTooltipBy=tooltipRect.width),pullTooltipBy=Math.round(pullTooltipBy),this.el_.style.right="-".concat(pullTooltipBy,"px"),this.write(content)}write(content){textContent(this.el_,content)}updateTime(seekBarRect,seekBarPoint,time,cb){this.requestNamedAnimationFrame("TimeTooltip#updateTime",(()=>{let content;const duration=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){const liveWindow=this.player_.liveTracker.liveWindow(),secondsBehind=liveWindow-seekBarPoint*liveWindow;content=(secondsBe
hind<1?"":"-")+formatTime(secondsBehind,liveWindow)}else content=formatTime(time,duration);this.update(seekBarRect,seekBarPoint,content),cb&&cb()}))}});class PlayProgressBar extends Component$1{constructor(player,options){super(player,options),this.setIcon("circle"),this.update=throttle(bind_(this,this.update),30)}createEl(){return super.createEl("div",{className:"vjs-play-progress vjs-slider-bar"},{"aria-hidden":"true"})}update(seekBarRect,seekBarPoint){const timeTooltip=this.getChild("timeTooltip");if(!timeTooltip)return;const time=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();timeTooltip.updateTime(seekBarRect,seekBarPoint,time)}}PlayProgressBar.prototype.options_={children:[]},IS_IOS||IS_ANDROID||PlayProgressBar.prototype.options_.children.push("timeTooltip"),Component$1.registerComponent("PlayProgressBar",PlayProgressBar);class MouseTimeDisplay extends Component$1{constructor(player,options){super(player,options),this.update=throttle(bind_(this,this.update),30)}
createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(seekBarRect,seekBarPoint){const time=seekBarPoint*this.player_.duration();this.getChild("timeTooltip").updateTime(seekBarRect,seekBarPoint,time,(()=>{this.el_.style.left="".concat(seekBarRect.width*seekBarPoint,"px")}))}}MouseTimeDisplay.prototype.options_={children:["timeTooltip"]},Component$1.registerComponent("MouseTimeDisplay",MouseTimeDisplay);class SeekBar extends Slider{constructor(player,options){super(player,options),this.setEventHandlers_()}setEventHandlers_(){this.update_=bind_(this,this.update),this.update=throttle(this.update_,30),this.on(this.player_,["ended","durationchange","timeupdate"],this.update),this.player_.liveTracker&&this.on(this.player_.liveTracker,"liveedgechange",this.update),this.updateInterval=null,this.enableIntervalHandler_=e=>this.enableInterval_(e),this.disableIntervalHandler_=e=>this.disableInterval_(e),this.on(this.player_,["playing"],this.enableIntervalHandler_),this.on(this.player_,["ended","p
ause","waiting"],this.disableIntervalHandler_),"hidden"in document&&"visibilityState"in document&&this.on(document,"visibilitychange",this.toggleVisibility_)}toggleVisibility_(e){"hidden"===document.visibilityState?(this.cancelNamedAnimationFrame("SeekBar#update"),this.cancelNamedAnimationFrame("Slider#update"),this.disableInterval_(e)):(this.player_.ended()||this.player_.paused()||this.enableInterval_(),this.update())}enableInterval_(){this.updateInterval||(this.updateInterval=this.setInterval(this.update,30))}disableInterval_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&e&&"ended"!==e.type||this.updateInterval&&(this.clearInterval(this.updateInterval),this.updateInterval=null)}createEl(){return super.createEl("div",{className:"vjs-progress-holder"},{"aria-label":this.localize("Progress Bar")})}update(event){if("hidden"===document.visibilityState)return;const percent=super.update();return this.requestNamedAnimationFrame("SeekBar#update",(()=>{const currentTime=this.player_.ended()?this.pl
ayer_.duration():this.getCurrentTime_(),liveTracker=this.player_.liveTracker;let duration=this.player_.duration();liveTracker&&liveTracker.isLive()&&(duration=this.player_.liveTracker.liveCurrentTime()),this.percent_!==percent&&(this.el_.setAttribute("aria-valuenow",(100*percent).toFixed(2)),this.percent_=percent),this.currentTime_===currentTime&&this.duration_===duration||(this.el_.setAttribute("aria-valuetext",this.localize("progress bar timing: currentTime={1} duration={2}",[formatTime(currentTime,duration),formatTime(duration,duration)],"{1} of {2}")),this.currentTime_=currentTime,this.duration_=duration),this.bar&&this.bar.update(getBoundingClientRect(this.el()),this.getProgress())})),percent}userSeek_(ct){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(ct)}getCurrentTime_(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime()}getPercent(){const currentTime=this.getCurrentTime_()
;let percent;const liveTracker=this.player_.liveTracker;return liveTracker&&liveTracker.isLive()?(percent=(currentTime-liveTracker.seekableStart())/liveTracker.liveWindow(),liveTracker.atLiveEdge()&&(percent=1)):percent=currentTime/this.player_.duration(),percent}handleMouseDown(event){isSingleLeftClick(event)&&(event.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.player_.pause(),super.handleMouseDown(event))}handleMouseMove(event){let newTime,mouseDown=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!isSingleLeftClick(event)||isNaN(this.player_.duration()))return;mouseDown||this.player_.scrubbing()||this.player_.scrubbing(!0);const distance=this.calculateDistance(event),liveTracker=this.player_.liveTracker;if(liveTracker&&liveTracker.isLive()){if(distance>=.99)return void liveTracker.seekToLiveEdge();const seekableStart=liveTracker.seekableStart(),seekableEnd=liveTracker.liveCurrentTime();if(newTime=seekableStart+distance*liveTracker.liveWindow(),newTime>=seekableEnd&&(newTime
=seekableEnd),newTime<=seekableStart&&(newTime=seekableStart+.1),newTime===1/0)return}else newTime=distance*this.player_.duration(),newTime===this.player_.duration()&&(newTime-=.1);this.userSeek_(newTime),this.player_.options_.enableSmoothSeeking&&this.update()}enable(){super.enable();const mouseTimeDisplay=this.getChild("mouseTimeDisplay");mouseTimeDisplay&&mouseTimeDisplay.show()}disable(){super.disable();const mouseTimeDisplay=this.getChild("mouseTimeDisplay");mouseTimeDisplay&&mouseTimeDisplay.hide()}handleMouseUp(event){super.handleMouseUp(event),event&&event.stopPropagation(),this.player_.scrubbing(!1),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0}),this.videoWasPlaying?silencePromise(this.player_.play()):this.update_()}stepForward(){this.userSeek_(this.player_.currentTime()+5)}stepBack(){this.userSeek_(this.player_.currentTime()-5)}handleAction(event){this.player_.paused()?this.player_.play():this.player_.pause()}handleKeyDown(event){const liveTracker=this.player_.liveTracke
r;if(keycode.isEventKey(event,"Space")||keycode.isEventKey(event,"Enter"))event.preventDefault(),event.stopPropagation(),this.handleAction(event);else if(keycode.isEventKey(event,"Home"))event.preventDefault(),event.stopPropagation(),this.userSeek_(0);else if(keycode.isEventKey(event,"End"))event.preventDefault(),event.stopPropagation(),liveTracker&&liveTracker.isLive()?this.userSeek_(liveTracker.liveCurrentTime()):this.userSeek_(this.player_.duration());else if(/^[0-9]$/.test(keycode(event))){event.preventDefault(),event.stopPropagation();const gotoFraction=10*(keycode.codes[keycode(event)]-keycode.codes[0])/100;liveTracker&&liveTracker.isLive()?this.userSeek_(liveTracker.seekableStart()+liveTracker.liveWindow()*gotoFraction):this.userSeek_(this.player_.duration()*gotoFraction)}else keycode.isEventKey(event,"PgDn")?(event.preventDefault(),event.stopPropagation(),this.userSeek_(this.player_.currentTime()-60)):keycode.isEventKey(event,"PgUp")?(event.preventDefault(),event.stopPropagation(),this.userSeek_(this
.player_.currentTime()+60)):super.handleKeyDown(event)}dispose(){this.disableInterval_(),this.off(this.player_,["ended","durationchange","timeupdate"],this.update),this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.update),this.off(this.player_,["playing"],this.enableIntervalHandler_),this.off(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in document&&"visibilityState"in document&&this.off(document,"visibilitychange",this.toggleVisibility_),super.dispose()}}SeekBar.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar"},IS_IOS||IS_ANDROID||SeekBar.prototype.options_.children.splice(1,0,"mouseTimeDisplay"),Component$1.registerComponent("SeekBar",SeekBar);class ProgressControl extends Component$1{constructor(player,options){super(player,options),this.handleMouseMove=throttle(bind_(this,this.handleMouseMove),30),this.throttledHandleMouseSeek=throttle(bind_(this,this.handleMouseSeek),30),this.handleMouseUpHandle
r_=e=>this.handleMouseUp(e),this.handleMouseDownHandler_=e=>this.handleMouseDown(e),this.enable()}createEl(){return super.createEl("div",{className:"vjs-progress-control vjs-control"})}handleMouseMove(event){const seekBar=this.getChild("seekBar");if(!seekBar)return;const playProgressBar=seekBar.getChild("playProgressBar"),mouseTimeDisplay=seekBar.getChild("mouseTimeDisplay");if(!playProgressBar&&!mouseTimeDisplay)return;const seekBarEl=seekBar.el(),seekBarRect=findPosition(seekBarEl);let seekBarPoint=getPointerPosition(seekBarEl,event).x;seekBarPoint=clamp(seekBarPoint,0,1),mouseTimeDisplay&&mouseTimeDisplay.update(seekBarRect,seekBarPoint),playProgressBar&&playProgressBar.update(seekBarRect,seekBar.getProgress())}handleMouseSeek(event){const seekBar=this.getChild("seekBar");seekBar&&seekBar.handleMouseMove(event)}enabled(){return this.enabled_}disable(){if(this.children().forEach((child=>child.disable&&child.disable())),this.enabled()&&(this.off(["mousedown","touchstart"],this.handleMouseDownHandler_),this.
off(this.el_,"mousemove",this.handleMouseMove),this.removeListenersAddedOnMousedownAndTouchstart(),this.addClass("disabled"),this.enabled_=!1,this.player_.scrubbing())){const seekBar=this.getChild("seekBar");this.player_.scrubbing(!1),seekBar.videoWasPlaying&&silencePromise(this.player_.play())}}enable(){this.children().forEach((child=>child.enable&&child.enable())),this.enabled()||(this.on(["mousedown","touchstart"],this.handleMouseDownHandler_),this.on(this.el_,"mousemove",this.handleMouseMove),this.removeClass("disabled"),this.enabled_=!0)}removeListenersAddedOnMousedownAndTouchstart(){const doc=this.el_.ownerDocument;this.off(doc,"mousemove",this.throttledHandleMouseSeek),this.off(doc,"touchmove",this.throttledHandleMouseSeek),this.off(doc,"mouseup",this.handleMouseUpHandler_),this.off(doc,"touchend",this.handleMouseUpHandler_)}handleMouseDown(event){const doc=this.el_.ownerDocument,seekBar=this.getChild("seekBar");seekBar&&seekBar.handleMouseDown(event),this.on(doc,"mousemove",this.throttledHandleMouseS
eek),this.on(doc,"touchmove",this.throttledHandleMouseSeek),this.on(doc,"mouseup",this.handleMouseUpHandler_),this.on(doc,"touchend",this.handleMouseUpHandler_)}handleMouseUp(event){const seekBar=this.getChild("seekBar");seekBar&&seekBar.handleMouseUp(event),this.removeListenersAddedOnMousedownAndTouchstart()}}ProgressControl.prototype.options_={children:["seekBar"]},Component$1.registerComponent("ProgressControl",ProgressControl);class PictureInPictureToggle extends Button{constructor(player,options){super(player,options),this.setIcon("picture-in-picture-enter"),this.on(player,["enterpictureinpicture","leavepictureinpicture"],(e=>this.handlePictureInPictureChange(e))),this.on(player,["disablepictureinpicturechanged","loadedmetadata"],(e=>this.handlePictureInPictureEnabledChange(e))),this.on(player,["loadedmetadata","audioonlymodechange","audiopostermodechange"],(()=>this.handlePictureInPictureAudioModeChange())),this.disable()}buildCSSClass(){return"vjs-picture-in-picture-control vjs-hidden ".concat(super.b
uildCSSClass())}handlePictureInPictureAudioModeChange(){"audio"===this.player_.currentType().substring(0,5)||this.player_.audioPosterMode()||this.player_.audioOnlyMode()?(this.player_.isInPictureInPicture()&&this.player_.exitPictureInPicture(),this.hide()):this.show()}handlePictureInPictureEnabledChange(){document.pictureInPictureEnabled&&!1===this.player_.disablePictureInPicture()||this.player_.options_.enableDocumentPictureInPicture&&"documentPictureInPicture"in window?this.enable():this.disable()}handlePictureInPictureChange(event){this.player_.isInPictureInPicture()?(this.setIcon("picture-in-picture-exit"),this.controlText("Exit Picture-in-Picture")):(this.setIcon("picture-in-picture-enter"),this.controlText("Picture-in-Picture")),this.handlePictureInPictureEnabledChange()}handleClick(event){this.player_.isInPictureInPicture()?this.player_.exitPictureInPicture():this.player_.requestPictureInPicture()}show(){"function"==typeof document.exitPictureInPicture&&super.show()}}PictureInPictureToggle.prototype.c
ontrolText_="Picture-in-Picture",Component$1.registerComponent("PictureInPictureToggle",PictureInPictureToggle);class FullscreenToggle extends Button{constructor(player,options){super(player,options),this.setIcon("fullscreen-enter"),this.on(player,"fullscreenchange",(e=>this.handleFullscreenChange(e))),!1===document[player.fsApi_.fullscreenEnabled]&&this.disable()}buildCSSClass(){return"vjs-fullscreen-control ".concat(super.buildCSSClass())}handleFullscreenChange(event){this.player_.isFullscreen()?(this.controlText("Exit Fullscreen"),this.setIcon("fullscreen-exit")):(this.controlText("Fullscreen"),this.setIcon("fullscreen-enter"))}handleClick(event){this.player_.isFullscreen()?this.player_.exitFullscreen():this.player_.requestFullscreen()}}FullscreenToggle.prototype.controlText_="Fullscreen",Component$1.registerComponent("FullscreenToggle",FullscreenToggle);Component$1.registerComponent("VolumeLevel",class extends Component$1{createEl(){const el=super.createEl("div",{className:"vjs-volume-level"});return thi
s.setIcon("circle",el),el.appendChild(super.createEl("span",{className:"vjs-control-text"})),el}});Component$1.registerComponent("VolumeLevelTooltip",class extends Component$1{constructor(player,options){super(player,options),this.update=throttle(bind_(this,this.update),30)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(rangeBarRect,rangeBarPoint,vertical,content){if(!vertical){const tooltipRect=getBoundingClientRect(this.el_),playerRect=getBoundingClientRect(this.player_.el()),volumeBarPointPx=rangeBarRect.width*rangeBarPoint;if(!playerRect||!tooltipRect)return;const spaceLeftOfPoint=rangeBarRect.left-playerRect.left+volumeBarPointPx,spaceRightOfPoint=rangeBarRect.width-volumeBarPointPx+(playerRect.right-rangeBarRect.right);let pullTooltipBy=tooltipRect.width/2;spaceLeftOfPoint<pullTooltipBy?pullTooltipBy+=pullTooltipBy-spaceLeftOfPoint:spaceRightOfPoint<pullTooltipBy&&(pullTooltipBy=spaceRightOfPoint),pullTooltipBy<0?pullTooltipBy=0:pullTooltipBy>tool
tipRect.width&&(pullTooltipBy=tooltipRect.width),this.el_.style.right="-".concat(pullTooltipBy,"px")}this.write("".concat(content,"%"))}write(content){textContent(this.el_,content)}updateVolume(rangeBarRect,rangeBarPoint,vertical,volume,cb){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",(()=>{this.update(rangeBarRect,rangeBarPoint,vertical,volume.toFixed(0)),cb&&cb()}))}});class MouseVolumeLevelDisplay extends Component$1{constructor(player,options){super(player,options),this.update=throttle(bind_(this,this.update),30)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(rangeBarRect,rangeBarPoint,vertical){const volume=100*rangeBarPoint;this.getChild("volumeLevelTooltip").updateVolume(rangeBarRect,rangeBarPoint,vertical,volume,(()=>{vertical?this.el_.style.bottom="".concat(rangeBarRect.height*rangeBarPoint,"px"):this.el_.style.left="".concat(rangeBarRect.width*rangeBarPoint,"px")}))}}MouseVolumeLevelDisplay.prototype.options_={children:["volumeLevelTooltip"]},Com
ponent$1.registerComponent("MouseVolumeLevelDisplay",MouseVolumeLevelDisplay);class VolumeBar extends Slider{constructor(player,options){super(player,options),this.on("slideractive",(e=>this.updateLastVolume_(e))),this.on(player,"volumechange",(e=>this.updateARIAAttributes(e))),player.ready((()=>this.updateARIAAttributes()))}createEl(){return super.createEl("div",{className:"vjs-volume-bar vjs-slider-bar"},{"aria-label":this.localize("Volume Level"),"aria-live":"polite"})}handleMouseDown(event){isSingleLeftClick(event)&&super.handleMouseDown(event)}handleMouseMove(event){const mouseVolumeLevelDisplay=this.getChild("mouseVolumeLevelDisplay");if(mouseVolumeLevelDisplay){const volumeBarEl=this.el(),volumeBarRect=getBoundingClientRect(volumeBarEl),vertical=this.vertical();let volumeBarPoint=getPointerPosition(volumeBarEl,event);volumeBarPoint=vertical?volumeBarPoint.y:volumeBarPoint.x,volumeBarPoint=clamp(volumeBarPoint,0,1),mouseVolumeLevelDisplay.update(volumeBarRect,volumeBarPoint,vertical)}isSingleLeftClick(
event)&&(this.checkMuted(),this.player_.volume(this.calculateDistance(event)))}checkMuted(){this.player_.muted()&&this.player_.muted(!1)}getPercent(){return this.player_.muted()?0:this.player_.volume()}stepForward(){this.checkMuted(),this.player_.volume(this.player_.volume()+.1)}stepBack(){this.checkMuted(),this.player_.volume(this.player_.volume()-.1)}updateARIAAttributes(event){const ariaValue=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute("aria-valuenow",ariaValue),this.el_.setAttribute("aria-valuetext",ariaValue+"%")}volumeAsPercentage_(){return Math.round(100*this.player_.volume())}updateLastVolume_(){const volumeBeforeDrag=this.player_.volume();this.one("sliderinactive",(()=>{0===this.player_.volume()&&this.player_.lastVolume_(volumeBeforeDrag)}))}}VolumeBar.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"},IS_IOS||IS_ANDROID||VolumeBar.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay"),VolumeBar.prototype.playerEvent="volumechange",Component$1.
registerComponent("VolumeBar",VolumeBar);class VolumeControl extends Component$1{constructor(player){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};options.vertical=options.vertical||!1,(void 0===options.volumeBar||isPlain(options.volumeBar))&&(options.volumeBar=options.volumeBar||{},options.volumeBar.vertical=options.vertical),super(player,options),function(self,player){player.tech_&&!player.tech_.featuresVolumeControl&&self.addClass("vjs-hidden"),self.on(player,"loadstart",(function(){player.tech_.featuresVolumeControl?self.removeClass("vjs-hidden"):self.addClass("vjs-hidden")}))}(this,player),this.throttledHandleMouseMove=throttle(bind_(this,this.handleMouseMove),30),this.handleMouseUpHandler_=e=>this.handleMouseUp(e),this.on("mousedown",(e=>this.handleMouseDown(e))),this.on("touchstart",(e=>this.handleMouseDown(e))),this.on("mousemove",(e=>this.handleMouseMove(e))),this.on(this.volumeBar,["focus","slideractive"],(()=>{this.volumeBar.addClass("vjs-slider-active"),this.addClass("vjs-
slider-active"),this.trigger("slideractive")})),this.on(this.volumeBar,["blur","sliderinactive"],(()=>{this.volumeBar.removeClass("vjs-slider-active"),this.removeClass("vjs-slider-active"),this.trigger("sliderinactive")}))}createEl(){let orientationClass="vjs-volume-horizontal";return this.options_.vertical&&(orientationClass="vjs-volume-vertical"),super.createEl("div",{className:"vjs-volume-control vjs-control ".concat(orientationClass)})}handleMouseDown(event){const doc=this.el_.ownerDocument;this.on(doc,"mousemove",this.throttledHandleMouseMove),this.on(doc,"touchmove",this.throttledHandleMouseMove),this.on(doc,"mouseup",this.handleMouseUpHandler_),this.on(doc,"touchend",this.handleMouseUpHandler_)}handleMouseUp(event){const doc=this.el_.ownerDocument;this.off(doc,"mousemove",this.throttledHandleMouseMove),this.off(doc,"touchmove",this.throttledHandleMouseMove),this.off(doc,"mouseup",this.handleMouseUpHandler_),this.off(doc,"touchend",this.handleMouseUpHandler_)}handleMouseMove(event){this.volumeBar.handl
eMouseMove(event)}}VolumeControl.prototype.options_={children:["volumeBar"]},Component$1.registerComponent("VolumeControl",VolumeControl);class MuteToggle extends Button{constructor(player,options){super(player,options),function(self,player){player.tech_&&!player.tech_.featuresMuteControl&&self.addClass("vjs-hidden"),self.on(player,"loadstart",(function(){player.tech_.featuresMuteControl?self.removeClass("vjs-hidden"):self.addClass("vjs-hidden")}))}(this,player),this.on(player,["loadstart","volumechange"],(e=>this.update(e)))}buildCSSClass(){return"vjs-mute-control ".concat(super.buildCSSClass())}handleClick(event){const vol=this.player_.volume(),lastVolume=this.player_.lastVolume_();if(0===vol){const volumeToSet=lastVolume<.1?.1:lastVolume;this.player_.volume(volumeToSet),this.player_.muted(!1)}else this.player_.muted(!this.player_.muted())}update(event){this.updateIcon_(),this.updateControlText_()}updateIcon_(){const vol=this.player_.volume();let level=3;this.setIcon("volume-high"),IS_IOS&&this.player_.tec
h_&&this.player_.tech_.el_&&this.player_.muted(this.player_.tech_.el_.muted),0===vol||this.player_.muted()?(this.setIcon("volume-mute"),level=0):vol<.33?(this.setIcon("volume-low"),level=1):vol<.67&&(this.setIcon("volume-medium"),level=2),removeClass(this.el_,[0,1,2,3].reduce(((str,i)=>str+"".concat(i?" ":"","vjs-vol-").concat(i)),"")),addClass(this.el_,"vjs-vol-".concat(level))}updateControlText_(){const text=this.player_.muted()||0===this.player_.volume()?"Unmute":"Mute";this.controlText()!==text&&this.controlText(text)}}MuteToggle.prototype.controlText_="Mute",Component$1.registerComponent("MuteToggle",MuteToggle);class VolumePanel extends Component$1{constructor(player){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};void 0!==options.inline?options.inline=options.inline:options.inline=!0,(void 0===options.volumeControl||isPlain(options.volumeControl))&&(options.volumeControl=options.volumeControl||{},options.volumeControl.vertical=!options.inline),super(player,options),this.handleKe
yPressHandler_=e=>this.handleKeyPress(e),this.on(player,["loadstart"],(e=>this.volumePanelState_(e))),this.on(this.muteToggle,"keyup",(e=>this.handleKeyPress(e))),this.on(this.volumeControl,"keyup",(e=>this.handleVolumeControlKeyUp(e))),this.on("keydown",(e=>this.handleKeyPress(e))),this.on("mouseover",(e=>this.handleMouseOver(e))),this.on("mouseout",(e=>this.handleMouseOut(e))),this.on(this.volumeControl,["slideractive"],this.sliderActive_),this.on(this.volumeControl,["sliderinactive"],this.sliderInactive_)}sliderActive_(){this.addClass("vjs-slider-active")}sliderInactive_(){this.removeClass("vjs-slider-active")}volumePanelState_(){this.volumeControl.hasClass("vjs-hidden")&&this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-hidden"),this.volumeControl.hasClass("vjs-hidden")&&!this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-mute-toggle-only")}createEl(){let orientationClass="vjs-volume-panel-horizontal";return this.options_.inline||(orientationClass="vjs-volume-panel-vertical"),super.creat
eEl("div",{className:"vjs-volume-panel vjs-control ".concat(orientationClass)})}dispose(){this.handleMouseOut(),super.dispose()}handleVolumeControlKeyUp(event){keycode.isEventKey(event,"Esc")&&this.muteToggle.focus()}handleMouseOver(event){this.addClass("vjs-hover"),on(document,"keyup",this.handleKeyPressHandler_)}handleMouseOut(event){this.removeClass("vjs-hover"),off(document,"keyup",this.handleKeyPressHandler_)}handleKeyPress(event){keycode.isEventKey(event,"Esc")&&this.handleMouseOut()}}VolumePanel.prototype.options_={children:["muteToggle","volumeControl"]},Component$1.registerComponent("VolumePanel",VolumePanel);class SkipForward extends Button{constructor(player,options){super(player,options),this.validOptions=[5,10,30],this.skipTime=this.getSkipForwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon("forward-".concat(this.skipTime)),this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime])),this.show()):this.hide()}getSkipForwardTime(){const playerOptions
=this.options_.playerOptions;return playerOptions.controlBar&&playerOptions.controlBar.skipButtons&&playerOptions.controlBar.skipButtons.forward}buildCSSClass(){return"vjs-skip-forward-".concat(this.getSkipForwardTime()," ").concat(super.buildCSSClass())}handleClick(event){if(isNaN(this.player_.duration()))return;const currentVideoTime=this.player_.currentTime(),liveTracker=this.player_.liveTracker,duration=liveTracker&&liveTracker.isLive()?liveTracker.seekableEnd():this.player_.duration();let newTime;newTime=currentVideoTime+this.skipTime<=duration?currentVideoTime+this.skipTime:duration,this.player_.currentTime(newTime)}handleLanguagechange(){this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime]))}}SkipForward.prototype.controlText_="Skip Forward",Component$1.registerComponent("SkipForward",SkipForward);class SkipBackward extends Button{constructor(player,options){super(player,options),this.validOptions=[5,10,30],this.skipTime=this.getSkipBackwardTime(),this.skipTime&&this.validOptions.
includes(this.skipTime)?(this.setIcon("replay-".concat(this.skipTime)),this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime])),this.show()):this.hide()}getSkipBackwardTime(){const playerOptions=this.options_.playerOptions;return playerOptions.controlBar&&playerOptions.controlBar.skipButtons&&playerOptions.controlBar.skipButtons.backward}buildCSSClass(){return"vjs-skip-backward-".concat(this.getSkipBackwardTime()," ").concat(super.buildCSSClass())}handleClick(event){const currentVideoTime=this.player_.currentTime(),liveTracker=this.player_.liveTracker,seekableStart=liveTracker&&liveTracker.isLive()&&liveTracker.seekableStart();let newTime;newTime=seekableStart&¤tVideoTime-this.skipTime<=seekableStart?seekableStart:currentVideoTime>=this.skipTime?currentVideoTime-this.skipTime:0,this.player_.currentTime(newTime)}handleLanguagechange(){this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime]))}}SkipBackward.prototype.controlText_="Skip Backward",Component$1.registerC
omponent("SkipBackward",SkipBackward);class Menu extends Component$1{constructor(player,options){super(player,options),options&&(this.menuButton_=options.menuButton),this.focusedChild_=-1,this.on("keydown",(e=>this.handleKeyDown(e))),this.boundHandleBlur_=e=>this.handleBlur(e),this.boundHandleTapClick_=e=>this.handleTapClick(e)}addEventListenerForItem(component){component instanceof Component$1&&(this.on(component,"blur",this.boundHandleBlur_),this.on(component,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(component){component instanceof Component$1&&(this.off(component,"blur",this.boundHandleBlur_),this.off(component,["tap","click"],this.boundHandleTapClick_))}removeChild(component){"string"==typeof component&&(component=this.getChild(component)),this.removeEventListenerForItem(component),super.removeChild(component)}addItem(component){const childComponent=this.addChild(component);childComponent&&this.addEventListenerForItem(childComponent)}createEl(){const contentElType=this.option
s_.contentElType||"ul";this.contentEl_=createEl(contentElType,{className:"vjs-menu-content"}),this.contentEl_.setAttribute("role","menu");const el=super.createEl("div",{append:this.contentEl_,className:"vjs-menu"});return el.appendChild(this.contentEl_),on(el,"click",(function(event){event.preventDefault(),event.stopImmediatePropagation()})),el}dispose(){this.contentEl_=null,this.boundHandleBlur_=null,this.boundHandleTapClick_=null,super.dispose()}handleBlur(event){const relatedTarget=event.relatedTarget||document.activeElement;if(!this.children().some((element=>element.el()===relatedTarget))){const btn=this.menuButton_;btn&&btn.buttonPressed_&&relatedTarget!==btn.el().firstChild&&btn.unpressButton()}}handleTapClick(event){if(this.menuButton_){this.menuButton_.unpressButton();const childComponents=this.children();if(!Array.isArray(childComponents))return;const foundComponent=childComponents.filter((component=>component.el()===event.target))[0];if(!foundComponent)return;"CaptionSettingsMenuItem"!==foundCompon
ent.name()&&this.menuButton_.focus()}}handleKeyDown(event){keycode.isEventKey(event,"Left")||keycode.isEventKey(event,"Down")?(event.preventDefault(),event.stopPropagation(),this.stepForward()):(keycode.isEventKey(event,"Right")||keycode.isEventKey(event,"Up"))&&(event.preventDefault(),event.stopPropagation(),this.stepBack())}stepForward(){let stepChild=0;void 0!==this.focusedChild_&&(stepChild=this.focusedChild_+1),this.focus(stepChild)}stepBack(){let stepChild=0;void 0!==this.focusedChild_&&(stepChild=this.focusedChild_-1),this.focus(stepChild)}focus(){let item=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;const children=this.children().slice();children.length&&children[0].hasClass("vjs-menu-title")&&children.shift(),children.length>0&&(item<0?item=0:item>=children.length&&(item=children.length-1),this.focusedChild_=item,children[item].el_.focus())}}Component$1.registerComponent("Menu",Menu);class MenuButton extends Component$1{constructor(player){let options=arguments.length>1&&void 0!==argumen
ts[1]?arguments[1]:{};super(player,options),this.menuButton_=new Button(player,options),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");const buttonClass=Button.prototype.buildCSSClass();this.menuButton_.el_.className=this.buildCSSClass()+" "+buttonClass,this.menuButton_.removeClass("vjs-control"),this.addChild(this.menuButton_),this.update(),this.enabled_=!0;const handleClick=e=>this.handleClick(e);this.handleMenuKeyUp_=e=>this.handleMenuKeyUp(e),this.on(this.menuButton_,"tap",handleClick),this.on(this.menuButton_,"click",handleClick),this.on(this.menuButton_,"keydown",(e=>this.handleKeyDown(e))),this.on(this.menuButton_,"mouseenter",(()=>{this.addClass("vjs-hover"),this.menu.show(),on(document,"keyup",this.handleMenuKeyUp_)})),this.on("mouseleave",(e=>this.handleMouseLeave(e))),this.on("keydown",(e=>this.handleSubmenuKeyDown(e)))}update(){const menu=this.createMenu();this.menu&&(this.menu.dispose(),this.removeChild(this.menu)),this.menu=menu,this.ad
dChild(menu),this.buttonPressed_=!1,this.menuButton_.el_.setAttribute("aria-expanded","false"),this.items&&this.items.length<=this.hideThreshold_?(this.hide(),this.menu.contentEl_.removeAttribute("role")):(this.show(),this.menu.contentEl_.setAttribute("role","menu"))}createMenu(){const menu=new Menu(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){const titleEl=createEl("li",{className:"vjs-menu-title",textContent:toTitleCase$1(this.options_.title),tabIndex:-1}),titleComponent=new Component$1(this.player_,{el:titleEl});menu.addItem(titleComponent)}if(this.items=this.createItems(),this.items)for(let i=0;i<this.items.length;i++)menu.addItem(this.items[i]);return menu}createItems(){}createEl(){return super.createEl("div",{className:this.buildWrapperCSSClass()},{})}setIcon(name){super.setIcon(name,this.menuButton_.el_)}buildWrapperCSSClass(){let menuButtonClass="vjs-menu-button";!0===this.options_.inline?menuButtonClass+="-inline":menuButtonClass+="-popup";const buttonClass=Button.pr
ototype.buildCSSClass();return"vjs-menu-button ".concat(menuButtonClass," ").concat(buttonClass," ").concat(super.buildCSSClass())}buildCSSClass(){let menuButtonClass="vjs-menu-button";return!0===this.options_.inline?menuButtonClass+="-inline":menuButtonClass+="-popup","vjs-menu-button ".concat(menuButtonClass," ").concat(super.buildCSSClass())}controlText(text){let el=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.menuButton_.el();return this.menuButton_.controlText(text,el)}dispose(){this.handleMouseLeave(),super.dispose()}handleClick(event){this.buttonPressed_?this.unpressButton():this.pressButton()}handleMouseLeave(event){this.removeClass("vjs-hover"),off(document,"keyup",this.handleMenuKeyUp_)}focus(){this.menuButton_.focus()}blur(){this.menuButton_.blur()}handleKeyDown(event){keycode.isEventKey(event,"Esc")||keycode.isEventKey(event,"Tab")?(this.buttonPressed_&&this.unpressButton(),keycode.isEventKey(event,"Tab")||(event.preventDefault(),this.menuButton_.focus())):(keycode.isEventKey(event
,"Up")||keycode.isEventKey(event,"Down"))&&(this.buttonPressed_||(event.preventDefault(),this.pressButton()))}handleMenuKeyUp(event){(keycode.isEventKey(event,"Esc")||keycode.isEventKey(event,"Tab"))&&this.removeClass("vjs-hover")}handleSubmenuKeyPress(event){this.handleSubmenuKeyDown(event)}handleSubmenuKeyDown(event){(keycode.isEventKey(event,"Esc")||keycode.isEventKey(event,"Tab"))&&(this.buttonPressed_&&this.unpressButton(),keycode.isEventKey(event,"Tab")||(event.preventDefault(),this.menuButton_.focus()))}pressButton(){if(this.enabled_){if(this.buttonPressed_=!0,this.menu.show(),this.menu.lockShowing(),this.menuButton_.el_.setAttribute("aria-expanded","true"),IS_IOS&&isInFrame())return;this.menu.focus()}}unpressButton(){this.enabled_&&(this.buttonPressed_=!1,this.menu.unlockShowing(),this.menu.hide(),this.menuButton_.el_.setAttribute("aria-expanded","false"))}disable(){this.unpressButton(),this.enabled_=!1,this.addClass("vjs-disabled"),this.menuButton_.disable()}enable(){this.enabled_=!0,this.removeClas
s("vjs-disabled"),this.menuButton_.enable()}}Component$1.registerComponent("MenuButton",MenuButton);class TrackButton extends MenuButton{constructor(player,options){const tracks=options.tracks;if(super(player,options),this.items.length<=1&&this.hide(),!tracks)return;const updateHandler=bind_(this,this.update);tracks.addEventListener("removetrack",updateHandler),tracks.addEventListener("addtrack",updateHandler),tracks.addEventListener("labelchange",updateHandler),this.player_.on("ready",updateHandler),this.player_.on("dispose",(function(){tracks.removeEventListener("removetrack",updateHandler),tracks.removeEventListener("addtrack",updateHandler),tracks.removeEventListener("labelchange",updateHandler)}))}}Component$1.registerComponent("TrackButton",TrackButton);const MenuKeys=["Tab","Esc","Up","Down","Right","Left"];class MenuItem extends ClickableComponent{constructor(player,options){super(player,options),this.selectable=options.selectable,this.isSelected_=options.selected||!1,this.multiSelectable=options.mul
tiSelectable,this.selected(this.isSelected_),this.selectable?this.multiSelectable?this.el_.setAttribute("role","menuitemcheckbox"):this.el_.setAttribute("role","menuitemradio"):this.el_.setAttribute("role","menuitem")}createEl(type,props,attrs){this.nonIconControl=!0;const el=super.createEl("li",Object.assign({className:"vjs-menu-item",tabIndex:-1},props),attrs),menuItemEl=createEl("span",{className:"vjs-menu-item-text",textContent:this.localize(this.options_.label)});return this.player_.options_.experimentalSvgIcons?el.appendChild(menuItemEl):el.replaceChild(menuItemEl,el.querySelector(".vjs-icon-placeholder")),el}handleKeyDown(event){MenuKeys.some((key=>keycode.isEventKey(event,key)))||super.handleKeyDown(event)}handleClick(event){this.selected(!0)}selected(selected){this.selectable&&(selected?(this.addClass("vjs-selected"),this.el_.setAttribute("aria-checked","true"),this.controlText(", selected"),this.isSelected_=!0):(this.removeClass("vjs-selected"),this.el_.setAttribute("aria-checked","false"),this.con
trolText(""),this.isSelected_=!1))}}Component$1.registerComponent("MenuItem",MenuItem);class TextTrackMenuItem extends MenuItem{constructor(player,options){var _this3;const track=options.track,tracks=player.textTracks();options.label=track.label||track.language||"Unknown",options.selected="showing"===track.mode,super(player,options),_this3=this,this.track=track,this.kinds=(options.kinds||[options.kind||this.track.kind]).filter(Boolean);const changeHandler=function(){for(var _len17=arguments.length,args=new Array(_len17),_key17=0;_key17<_len17;_key17++)args[_key17]=arguments[_key17];_this3.handleTracksChange.apply(_this3,args)},selectedLanguageChangeHandler=function(){for(var _len18=arguments.length,args=new Array(_len18),_key18=0;_key18<_len18;_key18++)args[_key18]=arguments[_key18];_this3.handleSelectedLanguageChange.apply(_this3,args)};if(player.on(["loadstart","texttrackchange"],changeHandler),tracks.addEventListener("change",changeHandler),tracks.addEventListener("selectedlanguagechange",selectedLanguage
ChangeHandler),this.on("dispose",(function(){player.off(["loadstart","texttrackchange"],changeHandler),tracks.removeEventListener("change",changeHandler),tracks.removeEventListener("selectedlanguagechange",selectedLanguageChangeHandler)})),void 0===tracks.onchange){let event;this.on(["tap","click"],(function(){if("object"!=typeof window.Event)try{event=new window.Event("change")}catch(err){}event||(event=document.createEvent("Event"),event.initEvent("change",!0,!0)),tracks.dispatchEvent(event)}))}this.handleTracksChange()}handleClick(event){const referenceTrack=this.track,tracks=this.player_.textTracks();if(super.handleClick(event),tracks)for(let i=0;i<tracks.length;i++){const track=tracks[i];-1!==this.kinds.indexOf(track.kind)&&(track===referenceTrack?"showing"!==track.mode&&(track.mode="showing"):"disabled"!==track.mode&&(track.mode="disabled"))}}handleTracksChange(event){const shouldBeSelected="showing"===this.track.mode;shouldBeSelected!==this.isSelected_&&this.selected(shouldBeSelected)}handleSelectedLa
nguageChange(event){if("showing"===this.track.mode){const selectedLanguage=this.player_.cache_.selectedLanguage;if(selectedLanguage&&selectedLanguage.enabled&&selectedLanguage.language===this.track.language&&selectedLanguage.kind!==this.track.kind)return;this.player_.cache_.selectedLanguage={enabled:!0,language:this.track.language,kind:this.track.kind}}}dispose(){this.track=null,super.dispose()}}Component$1.registerComponent("TextTrackMenuItem",TextTrackMenuItem);class OffTextTrackMenuItem extends TextTrackMenuItem{constructor(player,options){options.track={player:player,kind:options.kind,kinds:options.kinds,default:!1,mode:"disabled"},options.kinds||(options.kinds=[options.kind]),options.label?options.track.label=options.label:options.track.label=options.kinds.join(" and ")+" off",options.selectable=!0,options.multiSelectable=!1,super(player,options)}handleTracksChange(event){const tracks=this.player().textTracks();let shouldBeSelected=!0;for(let i=0,l=tracks.length;i<l;i++){const track=tracks[i];if(this.op
tions_.kinds.indexOf(track.kind)>-1&&"showing"===track.mode){shouldBeSelected=!1;break}}shouldBeSelected!==this.isSelected_&&this.selected(shouldBeSelected)}handleSelectedLanguageChange(event){const tracks=this.player().textTracks();let allHidden=!0;for(let i=0,l=tracks.length;i<l;i++){const track=tracks[i];if(["captions","descriptions","subtitles"].indexOf(track.kind)>-1&&"showing"===track.mode){allHidden=!1;break}}allHidden&&(this.player_.cache_.selectedLanguage={enabled:!1})}handleLanguagechange(){this.$(".vjs-menu-item-text").textContent=this.player_.localize(this.options_.label),super.handleLanguagechange()}}Component$1.registerComponent("OffTextTrackMenuItem",OffTextTrackMenuItem);class TextTrackButton extends TrackButton{constructor(player){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};options.tracks=player.textTracks(),super(player,options)}createItems(){let label,items=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],TrackMenuItem=arguments.length>1&&void 0!==argumen
ts[1]?arguments[1]:TextTrackMenuItem;this.label_&&(label="".concat(this.label_," off")),items.push(new OffTextTrackMenuItem(this.player_,{kinds:this.kinds_,kind:this.kind_,label:label})),this.hideThreshold_+=1;const tracks=this.player_.textTracks();Array.isArray(this.kinds_)||(this.kinds_=[this.kind_]);for(let i=0;i<tracks.length;i++){const track=tracks[i];if(this.kinds_.indexOf(track.kind)>-1){const item=new TrackMenuItem(this.player_,{track:track,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});item.addClass("vjs-".concat(track.kind,"-menu-item")),items.push(item)}}return items}}Component$1.registerComponent("TextTrackButton",TextTrackButton);class ChaptersTrackMenuItem extends MenuItem{constructor(player,options){const track=options.track,cue=options.cue,currentTime=player.currentTime();options.selectable=!0,options.multiSelectable=!1,options.label=cue.text,options.selected=cue.startTime<=currentTime&¤tTime<cue.endTime,super(player,options),this.track=track,this.cue=cue}handleCli
ck(event){super.handleClick(),this.player_.currentTime(this.cue.startTime)}}Component$1.registerComponent("ChaptersTrackMenuItem",ChaptersTrackMenuItem);class ChaptersButton extends TextTrackButton{constructor(player,options,ready){super(player,options,ready),this.setIcon("chapters"),this.selectCurrentItem_=()=>{this.items.forEach((item=>{item.selected(this.track_.activeCues[0]===item.cue)}))}}buildCSSClass(){return"vjs-chapters-button ".concat(super.buildCSSClass())}buildWrapperCSSClass(){return"vjs-chapters-button ".concat(super.buildWrapperCSSClass())}update(event){if(event&&event.track&&"chapters"!==event.track.kind)return;const track=this.findChaptersTrack();track!==this.track_?(this.setTrack(track),super.update()):(!this.items||track&&track.cues&&track.cues.length!==this.items.length)&&super.update()}setTrack(track){if(this.track_!==track){if(this.updateHandler_||(this.updateHandler_=this.update.bind(this)),this.track_){const remoteTextTrackEl=this.player_.remoteTextTrackEls().getTrackElementByTrack_(t
his.track_);remoteTextTrackEl&&remoteTextTrackEl.removeEventListener("load",this.updateHandler_),this.track_.removeEventListener("cuechange",this.selectCurrentItem_),this.track_=null}if(this.track_=track,this.track_){this.track_.mode="hidden";const remoteTextTrackEl=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);remoteTextTrackEl&&remoteTextTrackEl.addEventListener("load",this.updateHandler_),this.track_.addEventListener("cuechange",this.selectCurrentItem_)}}}findChaptersTrack(){const tracks=this.player_.textTracks()||[];for(let i=tracks.length-1;i>=0;i--){const track=tracks[i];if(track.kind===this.kind_)return track}}getMenuCaption(){return this.track_&&this.track_.label?this.track_.label:this.localize(toTitleCase$1(this.kind_))}createMenu(){return this.options_.title=this.getMenuCaption(),super.createMenu()}createItems(){const items=[];if(!this.track_)return items;const cues=this.track_.cues;if(!cues)return items;for(let i=0,l=cues.length;i<l;i++){const cue=cues[i],mi=new ChaptersTr
ackMenuItem(this.player_,{track:this.track_,cue:cue});items.push(mi)}return items}}ChaptersButton.prototype.kind_="chapters",ChaptersButton.prototype.controlText_="Chapters",Component$1.registerComponent("ChaptersButton",ChaptersButton);class DescriptionsButton extends TextTrackButton{constructor(player,options,ready){super(player,options,ready),this.setIcon("audio-description");const tracks=player.textTracks(),changeHandler=bind_(this,this.handleTracksChange);tracks.addEventListener("change",changeHandler),this.on("dispose",(function(){tracks.removeEventListener("change",changeHandler)}))}handleTracksChange(event){const tracks=this.player().textTracks();let disabled=!1;for(let i=0,l=tracks.length;i<l;i++){const track=tracks[i];if(track.kind!==this.kind_&&"showing"===track.mode){disabled=!0;break}}disabled?this.disable():this.enable()}buildCSSClass(){return"vjs-descriptions-button ".concat(super.buildCSSClass())}buildWrapperCSSClass(){return"vjs-descriptions-button ".concat(super.buildWrapperCSSClass())}}Des
criptionsButton.prototype.kind_="descriptions",DescriptionsButton.prototype.controlText_="Descriptions",Component$1.registerComponent("DescriptionsButton",DescriptionsButton);class SubtitlesButton extends TextTrackButton{constructor(player,options,ready){super(player,options,ready),this.setIcon("subtitles")}buildCSSClass(){return"vjs-subtitles-button ".concat(super.buildCSSClass())}buildWrapperCSSClass(){return"vjs-subtitles-button ".concat(super.buildWrapperCSSClass())}}SubtitlesButton.prototype.kind_="subtitles",SubtitlesButton.prototype.controlText_="Subtitles",Component$1.registerComponent("SubtitlesButton",SubtitlesButton);class CaptionSettingsMenuItem extends TextTrackMenuItem{constructor(player,options){options.track={player:player,kind:options.kind,label:options.kind+" settings",selectable:!1,default:!1,mode:"disabled"},options.selectable=!1,options.name="CaptionSettingsMenuItem",super(player,options),this.addClass("vjs-texttrack-settings"),this.controlText(", opens "+options.kind+" settings dialog")
}handleClick(event){this.player().getChild("textTrackSettings").open()}handleLanguagechange(){this.$(".vjs-menu-item-text").textContent=this.player_.localize(this.options_.kind+" settings"),super.handleLanguagechange()}}Component$1.registerComponent("CaptionSettingsMenuItem",CaptionSettingsMenuItem);class CaptionsButton extends TextTrackButton{constructor(player,options,ready){super(player,options,ready),this.setIcon("captions")}buildCSSClass(){return"vjs-captions-button ".concat(super.buildCSSClass())}buildWrapperCSSClass(){return"vjs-captions-button ".concat(super.buildWrapperCSSClass())}createItems(){const items=[];return this.player().tech_&&this.player().tech_.featuresNativeTextTracks||!this.player().getChild("textTrackSettings")||(items.push(new CaptionSettingsMenuItem(this.player_,{kind:this.kind_})),this.hideThreshold_+=1),super.createItems(items)}}CaptionsButton.prototype.kind_="captions",CaptionsButton.prototype.controlText_="Captions",Component$1.registerComponent("CaptionsButton",CaptionsButton);
class SubsCapsMenuItem extends TextTrackMenuItem{createEl(type,props,attrs){const el=super.createEl(type,props,attrs),parentSpan=el.querySelector(".vjs-menu-item-text");return"captions"===this.options_.track.kind&&(this.player_.options_.experimentalSvgIcons?this.setIcon("captions",el):parentSpan.appendChild(createEl("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),parentSpan.appendChild(createEl("span",{className:"vjs-control-text",textContent:" ".concat(this.localize("Captions"))}))),el}}Component$1.registerComponent("SubsCapsMenuItem",SubsCapsMenuItem);class SubsCapsButton extends TextTrackButton{constructor(player){super(player,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}),this.label_="subtitles",this.setIcon("subtitles"),["en","en-us","en-ca","fr-ca"].indexOf(this.player_.language_)>-1&&(this.label_="captions",this.setIcon("captions")),this.menuButton_.controlText(toTitleCase$1(this.label_))}buildCSSClass(){return"vjs-subs-caps-button ".concat(super.buildCSSClass())}buildWrappe
rCSSClass(){return"vjs-subs-caps-button ".concat(super.buildWrapperCSSClass())}createItems(){let items=[];return this.player().tech_&&this.player().tech_.featuresNativeTextTracks||!this.player().getChild("textTrackSettings")||(items.push(new CaptionSettingsMenuItem(this.player_,{kind:this.label_})),this.hideThreshold_+=1),items=super.createItems(items,SubsCapsMenuItem),items}}SubsCapsButton.prototype.kinds_=["captions","subtitles"],SubsCapsButton.prototype.controlText_="Subtitles",Component$1.registerComponent("SubsCapsButton",SubsCapsButton);class AudioTrackMenuItem extends MenuItem{constructor(player,options){var _this4;const track=options.track,tracks=player.audioTracks();options.label=track.label||track.language||"Unknown",options.selected=track.enabled,super(player,options),_this4=this,this.track=track,this.addClass("vjs-".concat(track.kind,"-menu-item"));const changeHandler=function(){for(var _len19=arguments.length,args=new Array(_len19),_key19=0;_key19<_len19;_key19++)args[_key19]=arguments[_key19];_
this4.handleTracksChange.apply(_this4,args)};tracks.addEventListener("change",changeHandler),this.on("dispose",(()=>{tracks.removeEventListener("change",changeHandler)}))}createEl(type,props,attrs){const el=super.createEl(type,props,attrs),parentSpan=el.querySelector(".vjs-menu-item-text");return["main-desc","description"].indexOf(this.options_.track.kind)>=0&&(parentSpan.appendChild(createEl("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),parentSpan.appendChild(createEl("span",{className:"vjs-control-text",textContent:" "+this.localize("Descriptions")}))),el}handleClick(event){if(super.handleClick(event),this.track.enabled=!0,this.player_.tech_.featuresNativeAudioTracks){const tracks=this.player_.audioTracks();for(let i=0;i<tracks.length;i++){const track=tracks[i];track!==this.track&&(track.enabled=track===this.track)}}}handleTracksChange(event){this.selected(this.track.enabled)}}Component$1.registerComponent("AudioTrackMenuItem",AudioTrackMenuItem);class AudioTrackButton extends TrackButton{
constructor(player){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};options.tracks=player.audioTracks(),super(player,options),this.setIcon("audio")}buildCSSClass(){return"vjs-audio-button ".concat(super.buildCSSClass())}buildWrapperCSSClass(){return"vjs-audio-button ".concat(super.buildWrapperCSSClass())}createItems(){let items=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];this.hideThreshold_=1;const tracks=this.player_.audioTracks();for(let i=0;i<tracks.length;i++){const track=tracks[i];items.push(new AudioTrackMenuItem(this.player_,{track:track,selectable:!0,multiSelectable:!1}))}return items}}AudioTrackButton.prototype.controlText_="Audio Track",Component$1.registerComponent("AudioTrackButton",AudioTrackButton);class PlaybackRateMenuItem extends MenuItem{constructor(player,options){const label=options.rate,rate=parseFloat(label,10);options.label=label,options.selected=rate===player.playbackRate(),options.selectable=!0,options.multiSelectable=!1,super(player,options),this.
label=label,this.rate=rate,this.on(player,"ratechange",(e=>this.update(e)))}handleClick(event){super.handleClick(),this.player().playbackRate(this.rate)}update(event){this.selected(this.player().playbackRate()===this.rate)}}PlaybackRateMenuItem.prototype.contentElType="button",Component$1.registerComponent("PlaybackRateMenuItem",PlaybackRateMenuItem);class PlaybackRateMenuButton extends MenuButton{constructor(player,options){super(player,options),this.menuButton_.el_.setAttribute("aria-describedby",this.labelElId_),this.updateVisibility(),this.updateLabel(),this.on(player,"loadstart",(e=>this.updateVisibility(e))),this.on(player,"ratechange",(e=>this.updateLabel(e))),this.on(player,"playbackrateschange",(e=>this.handlePlaybackRateschange(e)))}createEl(){const el=super.createEl();return this.labelElId_="vjs-playback-rate-value-label-"+this.id_,this.labelEl_=createEl("div",{className:"vjs-playback-rate-value",id:this.labelElId_,textContent:"1x"}),el.appendChild(this.labelEl_),el}dispose(){this.labelEl_=null,su
per.dispose()}buildCSSClass(){return"vjs-playback-rate ".concat(super.buildCSSClass())}buildWrapperCSSClass(){return"vjs-playback-rate ".concat(super.buildWrapperCSSClass())}createItems(){const rates=this.playbackRates(),items=[];for(let i=rates.length-1;i>=0;i--)items.push(new PlaybackRateMenuItem(this.player(),{rate:rates[i]+"x"}));return items}handlePlaybackRateschange(event){this.update()}playbackRates(){const player=this.player();return player.playbackRates&&player.playbackRates()||[]}playbackRateSupported(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0}updateVisibility(event){this.playbackRateSupported()?this.removeClass("vjs-hidden"):this.addClass("vjs-hidden")}updateLabel(event){this.playbackRateSupported()&&(this.labelEl_.textContent=this.player().playbackRate()+"x")}}PlaybackRateMenuButton.prototype.controlText_="Playback Rate",Component$1.registerComponent("PlaybackRateMenuButton",PlaybackRateMenuButton);class Spacer exten
ds Component$1{buildCSSClass(){return"vjs-spacer ".concat(super.buildCSSClass())}createEl(){let tag=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"div",props=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},attributes=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return props.className||(props.className=this.buildCSSClass()),super.createEl(tag,props,attributes)}}Component$1.registerComponent("Spacer",Spacer);Component$1.registerComponent("CustomControlSpacer",class extends Spacer{buildCSSClass(){return"vjs-custom-control-spacer ".concat(super.buildCSSClass())}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:" "})}});class ControlBar extends Component$1{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}ControlBar.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay
","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]},Component$1.registerComponent("ControlBar",ControlBar);class ErrorDisplay extends ModalDialog{constructor(player,options){super(player,options),this.on(player,"error",(e=>{this.close(),this.open(e)}))}buildCSSClass(){return"vjs-error-display ".concat(super.buildCSSClass())}content(){const error=this.player().error();return error?this.localize(error.message):""}}ErrorDisplay.prototype.options_=Object.assign({},ModalDialog.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0}),Component$1.registerComponent("ErrorDisplay",ErrorDisplay);const COLOR_BLACK=["#000","Black"],COLOR_BLUE=["#00F","Blue"],COLOR_CYAN=["#0FF","Cyan"],COLOR_GREEN=["#0F0","Green"],COLOR_MAGENTA=["#F0F","Magenta"],COLOR_RED=["#F00","Red"],COLOR_WHITE=["#FFF","White"],COLOR_YELLOW=["#FF0","Yellow"],OPACITY_OPAQUE=["1","Opaque"],OPACITY_SEMI=["0.5","Semi
-Transparent"],OPACITY_TRANS=["0","Transparent"],selectConfigs={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[COLOR_BLACK,COLOR_WHITE,COLOR_RED,COLOR_GREEN,COLOR_BLUE,COLOR_YELLOW,COLOR_MAGENTA,COLOR_CYAN]},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[OPACITY_OPAQUE,OPACITY_SEMI,OPACITY_TRANS]},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[COLOR_WHITE,COLOR_BLACK,COLOR_RED,COLOR_GREEN,COLOR_BLUE,COLOR_YELLOW,COLOR_MAGENTA,COLOR_CYAN]},edgeStyle:{selector:".vjs-edge-style > select",id:"%s",label:"Text Edge Style",options:[["none","None"],["raised","Raised"],["depressed","Depressed"],["uniform","Uniform"],["dropshadow","Drop shadow"]]},fontFamily:{selector:".vjs-font-family > select",id:"captions-font-family-%s",label:"Font Family",options:[["proportionalSansSerif","Proportional Sans-Serif"],["monospaceSansSerif","Monospace Sa
ns-Serif"],["proportionalSerif","Proportional Serif"],["monospaceSerif","Monospace Serif"],["casual","Casual"],["script","Script"],["small-caps","Small Caps"]]},fontPercent:{selector:".vjs-font-percent > select",id:"captions-font-size-%s",label:"Font Size",options:[["0.50","50%"],["0.75","75%"],["1.00","100%"],["1.25","125%"],["1.50","150%"],["1.75","175%"],["2.00","200%"],["3.00","300%"],["4.00","400%"]],default:2,parser:v=>"1.00"===v?null:Number(v)},textOpacity:{selector:".vjs-text-opacity > select",id:"captions-foreground-opacity-%s",label:"Opacity",options:[OPACITY_OPAQUE,OPACITY_SEMI]},windowColor:{selector:".vjs-window-color > select",id:"captions-window-color-%s",label:"Color"},windowOpacity:{selector:".vjs-window-opacity > select",id:"captions-window-opacity-%s",label:"Opacity",options:[OPACITY_TRANS,OPACITY_SEMI,OPACITY_OPAQUE]}};function parseOptionValue(value,parser){if(parser&&(value=parser(value)),value&&"none"!==value)return value}selectConfigs.windowColor.options=selectConfigs.backgroundColor.
options;Component$1.registerComponent("TextTrackSettings",class extends ModalDialog{constructor(player,options){options.temporary=!1,super(player,options),this.updateDisplay=this.updateDisplay.bind(this),this.fill(),this.hasBeenOpened_=this.hasBeenFilled_=!0,this.endDialog=createEl("p",{className:"vjs-control-text",textContent:this.localize("End of dialog window.")}),this.el().appendChild(this.endDialog),this.setDefaults(),void 0===options.persistTextTrackSettings&&(this.options_.persistTextTrackSettings=this.options_.playerOptions.persistTextTrackSettings),this.on(this.$(".vjs-done-button"),"click",(()=>{this.saveSettings(),this.close()})),this.on(this.$(".vjs-default-button"),"click",(()=>{this.setDefaults(),this.updateDisplay()})),each(selectConfigs,(config=>{this.on(this.$(config.selector),"change",this.updateDisplay)})),this.options_.persistTextTrackSettings&&this.restoreSettings()}dispose(){this.endDialog=null,super.dispose()}createElSelect_(key){let legendId=arguments.length>1&&void 0!==arguments[1]?a
rguments[1]:"",type=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"label";const config=selectConfigs[key],id=config.id.replace("%s",this.id_),selectLabelledbyIds=[legendId,id].join(" ").trim(),guid="vjs_select_".concat(newGUID());return["<".concat(type,' id="').concat(id,'"').concat("label"===type?' for="'.concat(guid,'" class="vjs-label"'):"",">"),this.localize(config.label),"</".concat(type,">"),'<select aria-labelledby="'.concat(selectLabelledbyIds,'" id="').concat(guid,'">')].concat(config.options.map((o=>{const optionId=id+"-"+o[1].replace(/\W+/g,"");return['<option id="'.concat(optionId,'" value="').concat(o[0],'" '),'aria-labelledby="'.concat(selectLabelledbyIds," ").concat(optionId,'">'),this.localize(o[1]),"</option>"].join("")}))).concat("</select>").join("")}createElFgColor_(){const legendId="captions-text-legend-".concat(this.id_);return['<fieldset class="vjs-fg vjs-track-setting">','<legend id="'.concat(legendId,'">'),this.localize("Text"),"</legend>",'<span class="vjs-text-color">',thi
s.createElSelect_("color",legendId),"</span>",'<span class="vjs-text-opacity vjs-opacity">',this.createElSelect_("textOpacity",legendId),"</span>","</fieldset>"].join("")}createElBgColor_(){const legendId="captions-background-".concat(this.id_);return['<fieldset class="vjs-bg vjs-track-setting">','<legend id="'.concat(legendId,'">'),this.localize("Text Background"),"</legend>",'<span class="vjs-bg-color">',this.createElSelect_("backgroundColor",legendId),"</span>",'<span class="vjs-bg-opacity vjs-opacity">',this.createElSelect_("backgroundOpacity",legendId),"</span>","</fieldset>"].join("")}createElWinColor_(){const legendId="captions-window-".concat(this.id_);return['<fieldset class="vjs-window vjs-track-setting">','<legend id="'.concat(legendId,'">'),this.localize("Caption Area Background"),"</legend>",'<span class="vjs-window-color">',this.createElSelect_("windowColor",legendId),"</span>",'<span class="vjs-window-opacity vjs-opacity">',this.createElSelect_("windowOpacity",legendId),"</span>","</fieldset>"
].join("")}createElColors_(){return createEl("div",{className:"vjs-track-settings-colors",innerHTML:[this.createElFgColor_(),this.createElBgColor_(),this.createElWinColor_()].join("")})}createElFont_(){return createEl("div",{className:"vjs-track-settings-font",innerHTML:['<fieldset class="vjs-font-percent vjs-track-setting">',this.createElSelect_("fontPercent","","legend"),"</fieldset>",'<fieldset class="vjs-edge-style vjs-track-setting">',this.createElSelect_("edgeStyle","","legend"),"</fieldset>",'<fieldset class="vjs-font-family vjs-track-setting">',this.createElSelect_("fontFamily","","legend"),"</fieldset>"].join("")})}createElControls_(){const defaultsDescription=this.localize("restore all settings to the default values");return createEl("div",{className:"vjs-track-settings-controls",innerHTML:['<button type="button" class="vjs-default-button" title="'.concat(defaultsDescription,'">'),this.localize("Reset"),'<span class="vjs-control-text"> '.concat(defaultsDescription,"</span>"),"</button>",'<button ty
pe="button" class="vjs-done-button">'.concat(this.localize("Done"),"</button>")].join("")})}content(){return[this.createElColors_(),this.createElFont_(),this.createElControls_()]}label(){return this.localize("Caption Settings Dialog")}description(){return this.localize("Beginning of dialog window. Escape will cancel and close the window.")}buildCSSClass(){return super.buildCSSClass()+" vjs-text-track-settings"}getValues(){return reduce(selectConfigs,((accum,config,key)=>{const value=(el=this.$(config.selector),parser=config.parser,parseOptionValue(el.options[el.options.selectedIndex].value,parser));var el,parser;return void 0!==value&&(accum[key]=value),accum}),{})}setValues(values){each(selectConfigs,((config,key)=>{!function(el,value,parser){if(value)for(let i=0;i<el.options.length;i++)if(parseOptionValue(el.options[i].value,parser)===value){el.selectedIndex=i;break}}(this.$(config.selector),values[key],config.parser)}))}setDefaults(){each(selectConfigs,(config=>{const index=config.hasOwnProperty("default"
)?config.default:0;this.$(config.selector).selectedIndex=index}))}restoreSettings(){let values;try{values=JSON.parse(window.localStorage.getItem("vjs-text-track-settings"))}catch(err){log$1.warn(err)}values&&this.setValues(values)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;const values=this.getValues();try{Object.keys(values).length?window.localStorage.setItem("vjs-text-track-settings",JSON.stringify(values)):window.localStorage.removeItem("vjs-text-track-settings")}catch(err){log$1.warn(err)}}updateDisplay(){const ttDisplay=this.player_.getChild("textTrackDisplay");ttDisplay&&ttDisplay.updateDisplay()}conditionalBlur_(){this.previouslyActiveEl_=null;const cb=this.player_.controlBar,subsCapsBtn=cb&&cb.subsCapsButton,ccBtn=cb&&cb.captionsButton;subsCapsBtn?subsCapsBtn.focus():ccBtn&&ccBtn.focus()}handleLanguagechange(){this.fill()}});Component$1.registerComponent("ResizeManager",class extends Component$1{constructor(player,options){let RESIZE_OBSERVER_AVAILABLE=options.ResizeObserver||wi
ndow.ResizeObserver;null===options.ResizeObserver&&(RESIZE_OBSERVER_AVAILABLE=!1);super(player,merge$2({createEl:!RESIZE_OBSERVER_AVAILABLE,reportTouchActivity:!1},options)),this.ResizeObserver=options.ResizeObserver||window.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=debounce((()=>{this.resizeHandler()}),100,!1,this),RESIZE_OBSERVER_AVAILABLE?(this.resizeObserver_=new this.ResizeObserver(this.debouncedHandler_),this.resizeObserver_.observe(player.el())):(this.loadListener_=()=>{if(!this.el_||!this.el_.contentWindow)return;const debouncedHandler_=this.debouncedHandler_;let unloadListener_=this.unloadListener_=function(){off(this,"resize",debouncedHandler_),off(this,"unload",unloadListener_),unloadListener_=null};on(this.el_.contentWindow,"unload",unloadListener_),on(this.el_.contentWindow,"resize",debouncedHandler_)},this.one("load",this.loadListener_))}createEl(){return super.createEl("iframe",{className:"vjs-resize-manager",tabIndex:-1,title:this.localize("No con
tent")},{"aria-hidden":"true"})}resizeHandler(){this.player_&&this.player_.trigger&&this.player_.trigger("playerresize")}dispose(){this.debouncedHandler_&&this.debouncedHandler_.cancel(),this.resizeObserver_&&(this.player_.el()&&this.resizeObserver_.unobserve(this.player_.el()),this.resizeObserver_.disconnect()),this.loadListener_&&this.off("load",this.loadListener_),this.el_&&this.el_.contentWindow&&this.unloadListener_&&this.unloadListener_.call(this.el_.contentWindow),this.ResizeObserver=null,this.resizeObserver=null,this.debouncedHandler_=null,this.loadListener_=null,super.dispose()}});const defaults={trackingThreshold:20,liveTolerance:15};Component$1.registerComponent("LiveTracker",class extends Component$1{constructor(player,options){super(player,merge$2(defaults,options,{createEl:!1})),this.trackLiveHandler_=()=>this.trackLive_(),this.handlePlay_=e=>this.handlePlay(e),this.handleFirstTimeupdate_=e=>this.handleFirstTimeupdate(e),this.handleSeeked_=e=>this.handleSeeked(e),this.seekToLiveEdge_=e=>this.se
ekToLiveEdge(e),this.reset_(),this.on(this.player_,"durationchange",(e=>this.handleDurationchange(e))),this.on(this.player_,"canplay",(()=>this.toggleTracking()))}trackLive_(){const seekable=this.player_.seekable();if(!seekable||!seekable.length)return;const newTime=Number(window.performance.now().toFixed(4)),deltaTime=-1===this.lastTime_?0:(newTime-this.lastTime_)/1e3;this.lastTime_=newTime,this.pastSeekEnd_=this.pastSeekEnd()+deltaTime;const liveCurrentTime=this.liveCurrentTime(),currentTime=this.player_.currentTime();let isBehind=this.player_.paused()||this.seekedBehindLive_||Math.abs(liveCurrentTime-currentTime)>this.options_.liveTolerance;this.timeupdateSeen_&&liveCurrentTime!==1/0||(isBehind=!1),isBehind!==this.behindLiveEdge_&&(this.behindLiveEdge_=isBehind,this.trigger("liveedgechange"))}handleDurationchange(){this.toggleTracking()}toggleTracking(){this.player_.duration()===1/0&&this.liveWindow()>=this.options_.trackingThreshold?(this.player_.options_.liveui&&this.player_.addClass("vjs-liveui"),this.
startTracking()):(this.player_.removeClass("vjs-liveui"),this.stopTracking())}startTracking(){this.isTracking()||(this.timeupdateSeen_||(this.timeupdateSeen_=this.player_.hasStarted()),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,30),this.trackLive_(),this.on(this.player_,["play","pause"],this.trackLiveHandler_),this.timeupdateSeen_?this.on(this.player_,"seeked",this.handleSeeked_):(this.one(this.player_,"play",this.handlePlay_),this.one(this.player_,"timeupdate",this.handleFirstTimeupdate_)))}handleFirstTimeupdate(){this.timeupdateSeen_=!0,this.on(this.player_,"seeked",this.handleSeeked_)}handleSeeked(){const timeDiff=Math.abs(this.liveCurrentTime()-this.player_.currentTime());this.seekedBehindLive_=this.nextSeekedFromUser_&&timeDiff>2,this.nextSeekedFromUser_=!1,this.trackLive_()}handlePlay(){this.one(this.player_,"timeupdate",this.seekToLiveEdge_)}reset_(){this.lastTime_=-1,this.pastSeekEnd_=0,this.lastSeekEnd_=-1,this.behindLiveEdge_=!0,this.timeupdateSeen_=!1,this.seekedBehindLive_=!1,
this.nextSeekedFromUser_=!1,this.clearInterval(this.trackingInterval_),this.trackingInterval_=null,this.off(this.player_,["play","pause"],this.trackLiveHandler_),this.off(this.player_,"seeked",this.handleSeeked_),this.off(this.player_,"play",this.handlePlay_),this.off(this.player_,"timeupdate",this.handleFirstTimeupdate_),this.off(this.player_,"timeupdate",this.seekToLiveEdge_)}nextSeekedFromUser(){this.nextSeekedFromUser_=!0}stopTracking(){this.isTracking()&&(this.reset_(),this.trigger("liveedgechange"))}seekableEnd(){const seekable=this.player_.seekable(),seekableEnds=[];let i=seekable?seekable.length:0;for(;i--;)seekableEnds.push(seekable.end(i));return seekableEnds.length?seekableEnds.sort()[seekableEnds.length-1]:1/0}seekableStart(){const seekable=this.player_.seekable(),seekableStarts=[];let i=seekable?seekable.length:0;for(;i--;)seekableStarts.push(seekable.start(i));return seekableStarts.length?seekableStarts.sort()[0]:0}liveWindow(){const liveCurrentTime=this.liveCurrentTime();return liveCurrentTime
===1/0?0:liveCurrentTime-this.seekableStart()}isLive(){return this.isTracking()}atLiveEdge(){return!this.behindLiveEdge()}liveCurrentTime(){return this.pastSeekEnd()+this.seekableEnd()}pastSeekEnd(){const seekableEnd=this.seekableEnd();return-1!==this.lastSeekEnd_&&seekableEnd!==this.lastSeekEnd_&&(this.pastSeekEnd_=0),this.lastSeekEnd_=seekableEnd,this.pastSeekEnd_}behindLiveEdge(){return this.behindLiveEdge_}isTracking(){return"number"==typeof this.trackingInterval_}seekToLiveEdge(){this.seekedBehindLive_=!1,this.atLiveEdge()||(this.nextSeekedFromUser_=!1,this.player_.currentTime(this.liveCurrentTime()))}dispose(){this.stopTracking(),super.dispose()}});Component$1.registerComponent("TitleBar",class extends Component$1{constructor(player,options){super(player,options),this.on("statechanged",(e=>this.updateDom_())),this.updateDom_()}createEl(){return this.els={title:createEl("div",{className:"vjs-title-bar-title",id:"vjs-title-bar-title-".concat(newGUID())}),description:createEl("div",{className:"vjs-title-b
ar-description",id:"vjs-title-bar-description-".concat(newGUID())})},createEl("div",{className:"vjs-title-bar"},{},values$1(this.els))}updateDom_(){const tech=this.player_.tech_,techEl=tech&&tech.el_,techAriaAttrs={title:"aria-labelledby",description:"aria-describedby"};["title","description"].forEach((k=>{const value=this.state[k],el=this.els[k],techAriaAttr=techAriaAttrs[k];emptyEl(el),value&&textContent(el,value),techEl&&(techEl.removeAttribute(techAriaAttr),value&&techEl.setAttribute(techAriaAttr,el.id))})),this.state.title||this.state.description?this.show():this.hide()}update(options){this.setState(options)}dispose(){const tech=this.player_.tech_,techEl=tech&&tech.el_;techEl&&(techEl.removeAttribute("aria-labelledby"),techEl.removeAttribute("aria-describedby")),super.dispose(),this.els=null}});const sourcesetLoad=tech=>{const el=tech.el();if(el.hasAttribute("src"))return tech.triggerSourceset(el.src),!0;const sources=tech.$$("source"),srcUrls=[];let src="";if(!sources.length)return!1;for(let i=0;i<sour
ces.length;i++){const url=sources[i].src;url&&-1===srcUrls.indexOf(url)&&srcUrls.push(url)}return!!srcUrls.length&&(1===srcUrls.length&&(src=srcUrls[0]),tech.triggerSourceset(src),!0)},innerHTMLDescriptorPolyfill=Object.defineProperty({},"innerHTML",{get(){return this.cloneNode(!0).innerHTML},set(v){const dummy=document.createElement(this.nodeName.toLowerCase());dummy.innerHTML=v;const docFrag=document.createDocumentFragment();for(;dummy.childNodes.length;)docFrag.appendChild(dummy.childNodes[0]);return this.innerText="",window.Element.prototype.appendChild.call(this,docFrag),this.innerHTML}}),getDescriptor=(priority,prop)=>{let descriptor={};for(let i=0;i<priority.length&&(descriptor=Object.getOwnPropertyDescriptor(priority[i],prop),!(descriptor&&descriptor.set&&descriptor.get));i++);return descriptor.enumerable=!0,descriptor.configurable=!0,descriptor},firstSourceWatch=function(tech){const el=tech.el();if(el.resetSourceWatch_)return;const old={},innerDescriptor=(tech=>getDescriptor([tech.el(),window.HTMLMe
diaElement.prototype,window.Element.prototype,innerHTMLDescriptorPolyfill],"innerHTML"))(tech),appendWrapper=appendFn=>function(){for(var _len20=arguments.length,args=new Array(_len20),_key20=0;_key20<_len20;_key20++)args[_key20]=arguments[_key20];const retval=appendFn.apply(el,args);return sourcesetLoad(tech),retval};["append","appendChild","insertAdjacentHTML"].forEach((k=>{el[k]&&(old[k]=el[k],el[k]=appendWrapper(old[k]))})),Object.defineProperty(el,"innerHTML",merge$2(innerDescriptor,{set:appendWrapper(innerDescriptor.set)})),el.resetSourceWatch_=()=>{el.resetSourceWatch_=null,Object.keys(old).forEach((k=>{el[k]=old[k]})),Object.defineProperty(el,"innerHTML",innerDescriptor)},tech.one("sourceset",el.resetSourceWatch_)},srcDescriptorPolyfill=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?getAbsoluteURL(window.Element.prototype.getAttribute.call(this,"src")):""},set(v){return window.Element.prototype.setAttribute.call(this,"src",v),v}}),setupSourceset=function(tech){if(!tech.features
Sourceset)return;const el=tech.el();if(el.resetSourceset_)return;const srcDescriptor=(tech=>getDescriptor([tech.el(),window.HTMLMediaElement.prototype,srcDescriptorPolyfill],"src"))(tech),oldSetAttribute=el.setAttribute,oldLoad=el.load;Object.defineProperty(el,"src",merge$2(srcDescriptor,{set:v=>{const retval=srcDescriptor.set.call(el,v);return tech.triggerSourceset(el.src),retval}})),el.setAttribute=(n,v)=>{const retval=oldSetAttribute.call(el,n,v);return/src/i.test(n)&&tech.triggerSourceset(el.src),retval},el.load=()=>{const retval=oldLoad.call(el);return sourcesetLoad(tech)||(tech.triggerSourceset(""),firstSourceWatch(tech)),retval},el.currentSrc?tech.triggerSourceset(el.currentSrc):sourcesetLoad(tech)||firstSourceWatch(tech),el.resetSourceset_=()=>{el.resetSourceset_=null,el.load=oldLoad,el.setAttribute=oldSetAttribute,Object.defineProperty(el,"src",srcDescriptor),el.resetSourceWatch_&&el.resetSourceWatch_()}};class Html5 extends Tech{constructor(options,ready){super(options,ready);const source=options.s
ource;let crossoriginTracks=!1;if(this.featuresVideoFrameCallback=this.featuresVideoFrameCallback&&"VIDEO"===this.el_.tagName,source&&(this.el_.currentSrc!==source.src||options.tag&&3===options.tag.initNetworkState_)?this.setSource(source):this.handleLateInit_(this.el_),options.enableSourceset&&this.setupSourcesetHandling_(),this.isScrubbing_=!1,this.el_.hasChildNodes()){const nodes=this.el_.childNodes;let nodesLength=nodes.length;const removeNodes=[];for(;nodesLength--;){const node=nodes[nodesLength];"track"===node.nodeName.toLowerCase()&&(this.featuresNativeTextTracks?(this.remoteTextTrackEls().addTrackElement_(node),this.remoteTextTracks().addTrack(node.track),this.textTracks().addTrack(node.track),crossoriginTracks||this.el_.hasAttribute("crossorigin")||!isCrossOrigin(node.src)||(crossoriginTracks=!0)):removeNodes.push(node))}for(let i=0;i<removeNodes.length;i++)this.el_.removeChild(removeNodes[i])}this.proxyNativeTracks_(),this.featuresNativeTextTracks&&crossoriginTracks&&log$1.warn("Text Tracks are bei
ng loaded from another origin but the crossorigin attribute isn't used.\nThis may prevent text tracks from loading."),this.restoreMetadataTracksInIOSNativePlayer_(),(TOUCH_ENABLED||IS_IPHONE)&&!0===options.nativeControlsForTouch&&this.setControls(!0),this.proxyWebkitFullscreen_(),this.triggerReady()}dispose(){this.el_&&this.el_.resetSourceset_&&this.el_.resetSourceset_(),Html5.disposeMediaElement(this.el_),this.options_=null,super.dispose()}setupSourcesetHandling_(){setupSourceset(this)}restoreMetadataTracksInIOSNativePlayer_(){const textTracks=this.textTracks();let metadataTracksPreFullscreenState;const takeMetadataTrackSnapshot=()=>{metadataTracksPreFullscreenState=[];for(let i=0;i<textTracks.length;i++){const track=textTracks[i];"metadata"===track.kind&&metadataTracksPreFullscreenState.push({track:track,storedMode:track.mode})}};takeMetadataTrackSnapshot(),textTracks.addEventListener("change",takeMetadataTrackSnapshot),this.on("dispose",(()=>textTracks.removeEventListener("change",takeMetadataTrackSnapsho
t)));const restoreTrackMode=()=>{for(let i=0;i<metadataTracksPreFullscreenState.length;i++){const storedTrack=metadataTracksPreFullscreenState[i];"disabled"===storedTrack.track.mode&&storedTrack.track.mode!==storedTrack.storedMode&&(storedTrack.track.mode=storedTrack.storedMode)}textTracks.removeEventListener("change",restoreTrackMode)};this.on("webkitbeginfullscreen",(()=>{textTracks.removeEventListener("change",takeMetadataTrackSnapshot),textTracks.removeEventListener("change",restoreTrackMode),textTracks.addEventListener("change",restoreTrackMode)})),this.on("webkitendfullscreen",(()=>{textTracks.removeEventListener("change",takeMetadataTrackSnapshot),textTracks.addEventListener("change",takeMetadataTrackSnapshot),textTracks.removeEventListener("change",restoreTrackMode)}))}overrideNative_(type,override){if(override!==this["featuresNative".concat(type,"Tracks")])return;const lowerCaseType=type.toLowerCase();this["".concat(lowerCaseType,"TracksListeners_")]&&Object.keys(this["".concat(lowerCaseType,"Tracks
Listeners_")]).forEach((eventName=>{this.el()["".concat(lowerCaseType,"Tracks")].removeEventListener(eventName,this["".concat(lowerCaseType,"TracksListeners_")][eventName])})),this["featuresNative".concat(type,"Tracks")]=!override,this["".concat(lowerCaseType,"TracksListeners_")]=null,this.proxyNativeTracksForType_(lowerCaseType)}overrideNativeAudioTracks(override){this.overrideNative_("Audio",override)}overrideNativeVideoTracks(override){this.overrideNative_("Video",override)}proxyNativeTracksForType_(name){const props=NORMAL[name],elTracks=this.el()[props.getterName],techTracks=this[props.getterName]();if(!this["featuresNative".concat(props.capitalName,"Tracks")]||!elTracks||!elTracks.addEventListener)return;const listeners={change:e=>{const event={type:"change",target:techTracks,currentTarget:techTracks,srcElement:techTracks};techTracks.trigger(event),"text"===name&&this[REMOTE.remoteText.getterName]().trigger(event)},addtrack(e){techTracks.addTrack(e.track)},removetrack(e){techTracks.removeTrack(e.track)
}},removeOldTracks=function(){const removeTracks=[];for(let i=0;i<techTracks.length;i++){let found=!1;for(let j=0;j<elTracks.length;j++)if(elTracks[j]===techTracks[i]){found=!0;break}found||removeTracks.push(techTracks[i])}for(;removeTracks.length;)techTracks.removeTrack(removeTracks.shift())};this[props.getterName+"Listeners_"]=listeners,Object.keys(listeners).forEach((eventName=>{const listener=listeners[eventName];elTracks.addEventListener(eventName,listener),this.on("dispose",(e=>elTracks.removeEventListener(eventName,listener)))})),this.on("loadstart",removeOldTracks),this.on("dispose",(e=>this.off("loadstart",removeOldTracks)))}proxyNativeTracks_(){NORMAL.names.forEach((name=>{this.proxyNativeTracksForType_(name)}))}createEl(){let el=this.options_.tag;if(!el||!this.options_.playerElIngest&&!this.movingMediaElementInDOM){if(el){const clone=el.cloneNode(!0);el.parentNode&&el.parentNode.insertBefore(clone,el),Html5.disposeMediaElement(el),el=clone}else{el=document.createElement("video");const attributes=m
erge$2({},this.options_.tag&&getAttributes(this.options_.tag));TOUCH_ENABLED&&!0===this.options_.nativeControlsForTouch||delete attributes.controls,setAttributes(el,Object.assign(attributes,{id:this.options_.techId,class:"vjs-tech"}))}el.playerId=this.options_.playerId}void 0!==this.options_.preload&&setAttribute(el,"preload",this.options_.preload),void 0!==this.options_.disablePictureInPicture&&(el.disablePictureInPicture=this.options_.disablePictureInPicture);const settingsAttrs=["loop","muted","playsinline","autoplay"];for(let i=0;i<settingsAttrs.length;i++){const attr=settingsAttrs[i],value=this.options_[attr];void 0!==value&&(value?setAttribute(el,attr,attr):removeAttribute(el,attr),el[attr]=value)}return el}handleLateInit_(el){if(0===el.networkState||3===el.networkState)return;if(0===el.readyState){let loadstartFired=!1;const setLoadstartFired=function(){loadstartFired=!0};this.on("loadstart",setLoadstartFired);const triggerLoadstart=function(){loadstartFired||this.trigger("loadstart")};return this.on(
"loadedmetadata",triggerLoadstart),void this.ready((function(){this.off("loadstart",setLoadstartFired),this.off("loadedmetadata",triggerLoadstart),loadstartFired||this.trigger("loadstart")}))}const eventsToTrigger=["loadstart"];eventsToTrigger.push("loadedmetadata"),el.readyState>=2&&eventsToTrigger.push("loadeddata"),el.readyState>=3&&eventsToTrigger.push("canplay"),el.readyState>=4&&eventsToTrigger.push("canplaythrough"),this.ready((function(){eventsToTrigger.forEach((function(type){this.trigger(type)}),this)}))}setScrubbing(isScrubbing){this.isScrubbing_=isScrubbing}scrubbing(){return this.isScrubbing_}setCurrentTime(seconds){try{this.isScrubbing_&&this.el_.fastSeek&&IS_ANY_SAFARI?this.el_.fastSeek(seconds):this.el_.currentTime=seconds}catch(e){log$1(e,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&IS_ANDROID&&IS_CHROME&&0===this.el_.currentTime){const checkProgress=()=>{this.el_.currentTime>0&&(this.el_.duration===1/0&&this.trigger("durationchange"),this.off("timeupdate",checkP
rogress))};return this.on("timeupdate",checkProgress),NaN}return this.el_.duration||NaN}width(){return this.el_.offsetWidth}height(){return this.el_.offsetHeight}proxyWebkitFullscreen_(){if(!("webkitDisplayingFullscreen"in this.el_))return;const endFn=function(){this.trigger("fullscreenchange",{isFullscreen:!1}),this.el_.controls&&!this.options_.nativeControlsForTouch&&this.controls()&&(this.el_.controls=!1)},beginFn=function(){"webkitPresentationMode"in this.el_&&"picture-in-picture"!==this.el_.webkitPresentationMode&&(this.one("webkitendfullscreen",endFn),this.trigger("fullscreenchange",{isFullscreen:!0,nativeIOSFullscreen:!0}))};this.on("webkitbeginfullscreen",beginFn),this.on("dispose",(()=>{this.off("webkitbeginfullscreen",beginFn),this.off("webkitendfullscreen",endFn)}))}supportsFullScreen(){return"function"==typeof this.el_.webkitEnterFullScreen}enterFullScreen(){const video=this.el_;if(video.paused&&video.networkState<=video.HAVE_METADATA)silencePromise(this.el_.play()),this.setTimeout((function(){vi
deo.pause();try{video.webkitEnterFullScreen()}catch(e){this.trigger("fullscreenerror",e)}}),0);else try{video.webkitEnterFullScreen()}catch(e){this.trigger("fullscreenerror",e)}}exitFullScreen(){this.el_.webkitDisplayingFullscreen?this.el_.webkitExitFullScreen():this.trigger("fullscreenerror",new Error("The video is not fullscreen"))}requestPictureInPicture(){return this.el_.requestPictureInPicture()}requestVideoFrameCallback(cb){return this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.requestVideoFrameCallback(cb):super.requestVideoFrameCallback(cb)}cancelVideoFrameCallback(id){this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.cancelVideoFrameCallback(id):super.cancelVideoFrameCallback(id)}src(src){if(void 0===src)return this.el_.src;this.setSrc(src)}reset(){Html5.resetMediaElement(this.el_)}currentSrc(){return this.currentSource_?this.currentSource_.src:this.el_.currentSrc}setControls(val){this.el_.controls=!!val}addTextTrack(kind,label,language){return this.featuresNativeTextTrac
ks?this.el_.addTextTrack(kind,label,language):super.addTextTrack(kind,label,language)}createRemoteTextTrack(options){if(!this.featuresNativeTextTracks)return super.createRemoteTextTrack(options);const htmlTrackElement=document.createElement("track");return options.kind&&(htmlTrackElement.kind=options.kind),options.label&&(htmlTrackElement.label=options.label),(options.language||options.srclang)&&(htmlTrackElement.srclang=options.language||options.srclang),options.default&&(htmlTrackElement.default=options.default),options.id&&(htmlTrackElement.id=options.id),options.src&&(htmlTrackElement.src=options.src),htmlTrackElement}addRemoteTextTrack(options,manualCleanup){const htmlTrackElement=super.addRemoteTextTrack(options,manualCleanup);return this.featuresNativeTextTracks&&this.el().appendChild(htmlTrackElement),htmlTrackElement}removeRemoteTextTrack(track){if(super.removeRemoteTextTrack(track),this.featuresNativeTextTracks){const tracks=this.$$("track");let i=tracks.length;for(;i--;)track!==tracks[i]&&track!==
tracks[i].track||this.el().removeChild(tracks[i])}}getVideoPlaybackQuality(){if("function"==typeof this.el().getVideoPlaybackQuality)return this.el().getVideoPlaybackQuality();const videoPlaybackQuality={};return void 0!==this.el().webkitDroppedFrameCount&&void 0!==this.el().webkitDecodedFrameCount&&(videoPlaybackQuality.droppedVideoFrames=this.el().webkitDroppedFrameCount,videoPlaybackQuality.totalVideoFrames=this.el().webkitDecodedFrameCount),window.performance&&(videoPlaybackQuality.creationTime=window.performance.now()),videoPlaybackQuality}}defineLazyProperty(Html5,"TEST_VID",(function(){if(!isReal())return;const video=document.createElement("video"),track=document.createElement("track");return track.kind="captions",track.srclang="en",track.label="English",video.appendChild(track),video})),Html5.isSupported=function(){try{Html5.TEST_VID.volume=.5}catch(e){return!1}return!(!Html5.TEST_VID||!Html5.TEST_VID.canPlayType)},Html5.canPlayType=function(type){return Html5.TEST_VID.canPlayType(type)},Html5.canPla
ySource=function(srcObj,options){return Html5.canPlayType(srcObj.type)},Html5.canControlVolume=function(){try{const volume=Html5.TEST_VID.volume;Html5.TEST_VID.volume=volume/2+.1;const canControl=volume!==Html5.TEST_VID.volume;return canControl&&IS_IOS?(window.setTimeout((()=>{Html5&&Html5.prototype&&(Html5.prototype.featuresVolumeControl=volume!==Html5.TEST_VID.volume)})),!1):canControl}catch(e){return!1}},Html5.canMuteVolume=function(){try{const muted=Html5.TEST_VID.muted;return Html5.TEST_VID.muted=!muted,Html5.TEST_VID.muted?setAttribute(Html5.TEST_VID,"muted","muted"):removeAttribute(Html5.TEST_VID,"muted"),muted!==Html5.TEST_VID.muted}catch(e){return!1}},Html5.canControlPlaybackRate=function(){if(IS_ANDROID&&IS_CHROME&&CHROME_VERSION<58)return!1;try{const playbackRate=Html5.TEST_VID.playbackRate;return Html5.TEST_VID.playbackRate=playbackRate/2+.1,playbackRate!==Html5.TEST_VID.playbackRate}catch(e){return!1}},Html5.canOverrideAttributes=function(){try{const noop=()=>{};Object.defineProperty(document.cr
eateElement("video"),"src",{get:noop,set:noop}),Object.defineProperty(document.createElement("audio"),"src",{get:noop,set:noop}),Object.defineProperty(document.createElement("video"),"innerHTML",{get:noop,set:noop}),Object.defineProperty(document.createElement("audio"),"innerHTML",{get:noop,set:noop})}catch(e){return!1}return!0},Html5.supportsNativeTextTracks=function(){return IS_ANY_SAFARI||IS_IOS&&IS_CHROME},Html5.supportsNativeVideoTracks=function(){return!(!Html5.TEST_VID||!Html5.TEST_VID.videoTracks)},Html5.supportsNativeAudioTracks=function(){return!(!Html5.TEST_VID||!Html5.TEST_VID.audioTracks)},Html5.Events=["loadstart","suspend","abort","error","emptied","stalled","loadedmetadata","loadeddata","canplay","canplaythrough","playing","waiting","seeking","seeked","ended","durationchange","timeupdate","progress","play","pause","ratechange","resize","volumechange"],[["featuresMuteControl","canMuteVolume"],["featuresPlaybackRate","canControlPlaybackRate"],["featuresSourceset","canOverrideAttributes"],["feat
uresNativeTextTracks","supportsNativeTextTracks"],["featuresNativeVideoTracks","supportsNativeVideoTracks"],["featuresNativeAudioTracks","supportsNativeAudioTracks"]].forEach((function(_ref5){let[key,fn]=_ref5;defineLazyProperty(Html5.prototype,key,(()=>Html5[fn]()),!0)})),Html5.prototype.featuresVolumeControl=Html5.canControlVolume(),Html5.prototype.movingMediaElementInDOM=!IS_IOS,Html5.prototype.featuresFullscreenResize=!0,Html5.prototype.featuresProgressEvents=!0,Html5.prototype.featuresTimeupdateEvents=!0,Html5.prototype.featuresVideoFrameCallback=!(!Html5.TEST_VID||!Html5.TEST_VID.requestVideoFrameCallback),Html5.disposeMediaElement=function(el){if(el){for(el.parentNode&&el.parentNode.removeChild(el);el.hasChildNodes();)el.removeChild(el.firstChild);el.removeAttribute("src"),"function"==typeof el.load&&function(){try{el.load()}catch(e){}}()}},Html5.resetMediaElement=function(el){if(!el)return;const sources=el.querySelectorAll("source");let i=sources.length;for(;i--;)el.removeChild(sources[i]);el.removeA
ttribute("src"),"function"==typeof el.load&&function(){try{el.load()}catch(e){}}()},["muted","defaultMuted","autoplay","controls","loop","playsinline"].forEach((function(prop){Html5.prototype[prop]=function(){return this.el_[prop]||this.el_.hasAttribute(prop)}})),["muted","defaultMuted","autoplay","loop","playsinline"].forEach((function(prop){Html5.prototype["set"+toTitleCase$1(prop)]=function(v){this.el_[prop]=v,v?this.el_.setAttribute(prop,prop):this.el_.removeAttribute(prop)}})),["paused","currentTime","buffered","volume","poster","preload","error","seeking","seekable","ended","playbackRate","defaultPlaybackRate","disablePictureInPicture","played","networkState","readyState","videoWidth","videoHeight","crossOrigin"].forEach((function(prop){Html5.prototype[prop]=function(){return this.el_[prop]}})),["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach((function(prop){Html5.prototype["set"+toTitleCase$1(prop)]=function(v){this.el_[prop]=v}})
),["pause","load","play"].forEach((function(prop){Html5.prototype[prop]=function(){return this.el_[prop]()}})),Tech.withSourceHandlers(Html5),Html5.nativeSourceHandler={},Html5.nativeSourceHandler.canPlayType=function(type){try{return Html5.TEST_VID.canPlayType(type)}catch(e){return""}},Html5.nativeSourceHandler.canHandleSource=function(source,options){if(source.type)return Html5.nativeSourceHandler.canPlayType(source.type);if(source.src){const ext=getFileExtension(source.src);return Html5.nativeSourceHandler.canPlayType("video/".concat(ext))}return""},Html5.nativeSourceHandler.handleSource=function(source,tech,options){tech.setSrc(source.src)},Html5.nativeSourceHandler.dispose=function(){},Html5.registerSourceHandler(Html5.nativeSourceHandler),Tech.registerTech("Html5",Html5);const TECH_EVENTS_RETRIGGER=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],TECH_EVENTS_QUEUE={canplay:"CanPlay",canplaythrough:"CanPlayThrough",pl
aying:"Playing",seeked:"Seeked"},BREAKPOINT_ORDER=["tiny","xsmall","small","medium","large","xlarge","huge"],BREAKPOINT_CLASSES={};BREAKPOINT_ORDER.forEach((k=>{const v="x"===k.charAt(0)?"x-".concat(k.substring(1)):k;BREAKPOINT_CLASSES[k]="vjs-layout-".concat(v)}));const DEFAULT_BREAKPOINTS={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};class Player extends Component$1{constructor(tag,options,ready){if(tag.id=tag.id||options.id||"vjs_video_".concat(newGUID()),(options=Object.assign(Player.getTagSettings(tag),options)).initChildren=!1,options.createEl=!1,options.evented=!1,options.reportTouchActivity=!1,!options.language){const closest=tag.closest("[lang]");closest&&(options.language=closest.getAttribute("lang"))}if(super(null,options,ready),this.boundDocumentFullscreenChange_=e=>this.documentFullscreenChange_(e),this.boundFullWindowOnEscKey_=e=>this.fullWindowOnEscKey(e),this.boundUpdateStyleEl_=e=>this.updateStyleEl_(e),this.boundApplyInitTime_=e=>this.applyInitTime_(e),this.boun
dUpdateCurrentBreakpoint_=e=>this.updateCurrentBreakpoint_(e),this.boundHandleTechClick_=e=>this.handleTechClick_(e),this.boundHandleTechDoubleClick_=e=>this.handleTechDoubleClick_(e),this.boundHandleTechTouchStart_=e=>this.handleTechTouchStart_(e),this.boundHandleTechTouchMove_=e=>this.handleTechTouchMove_(e),this.boundHandleTechTouchEnd_=e=>this.handleTechTouchEnd_(e),this.boundHandleTechTap_=e=>this.handleTechTap_(e),this.isFullscreen_=!1,this.log=createLogger(this.id_),this.fsApi_=FullscreenApi,this.isPosterFromTech_=!1,this.queuedCallbacks_=[],this.isReady_=!1,this.hasStarted_=!1,this.userActive_=!1,this.debugEnabled_=!1,this.audioOnlyMode_=!1,this.audioPosterMode_=!1,this.audioOnlyCache_={playerHeight:null,hiddenChildren:[]},!this.options_||!this.options_.techOrder||!this.options_.techOrder.length)throw new Error("No techOrder specified. Did you overwrite videojs.options instead of just changing the properties you want to override?");if(this.tag=tag,this.tagAttributes=tag&&getAttributes(tag),this.langu
age(this.options_.language),options.languages){const languagesToLower={};Object.getOwnPropertyNames(options.languages).forEach((function(name){languagesToLower[name.toLowerCase()]=options.languages[name]})),this.languages_=languagesToLower}else this.languages_=Player.prototype.options_.languages;this.resetCache_(),this.poster_=options.poster||"",this.controls_=!!options.controls,tag.controls=!1,tag.removeAttribute("controls"),this.changingSrc_=!1,this.playCallbacks_=[],this.playTerminatedQueue_=[],tag.hasAttribute("autoplay")?this.autoplay(!0):this.autoplay(this.options_.autoplay),options.plugins&&Object.keys(options.plugins).forEach((name=>{if("function"!=typeof this[name])throw new Error('plugin "'.concat(name,'" does not exist'))})),this.scrubbing_=!1,this.el_=this.createEl(),evented(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&(on(document,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&t
his.on(["playerreset","resize"],this.boundUpdateStyleEl_);const playerOptionsCopy=merge$2(this.options_);if(options.plugins&&Object.keys(options.plugins).forEach((name=>{this[name](options.plugins[name])})),options.debug&&this.debug(!0),this.options_.playerOptions=playerOptionsCopy,this.middleware_=[],this.playbackRates(options.playbackRates),options.experimentalSvgIcons){const parsedSVG=(new window.DOMParser).parseFromString('<svg xmlns="http://www.w3.org/2000/svg">\n <defs>\n <symbol viewBox="0 0 48 48" id="vjs-icon-play">\n <path d="M16 10v28l22-14z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-pause">\n <path d="M12 38h8V10h-8v28zm16-28v28h8V10h-8z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-audio">\n <path d="M24 2C14.06 2 6 10.06 6 20v14c0 3.31 2.69 6 6 6h6V24h-8v-4c0-7.73 6.27-14 14-14s14 6.27 14 14v4h-8v16h6c3.31 0 6-2.69 6-6V20c0-9.94-8.06-18-18-18z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-captions">\n
<path d="M38 8H10c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zM22 22h-3v-1h-4v6h4v-1h3v2a2 2 0 0 1-2 2h-6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2zm14 0h-3v-1h-4v6h4v-1h3v2a2 2 0 0 1-2 2h-6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-subtitles">\n <path d="M40 8H8c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zM8 24h8v4H8v-4zm20 12H8v-4h20v4zm12 0h-8v-4h8v4zm0-8H20v-4h20v4z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-fullscreen-enter">\n <path d="M14 28h-4v10h10v-4h-6v-6zm-4-8h4v-6h6v-4H10v10zm24 14h-6v4h10V28h-4v6zm-6-24v4h6v6h4V10H28z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-fullscreen-exit">\n <path d="M10 32h6v6h4V28H10v4zm6-16h-6v4h10V10h-4v6zm12 22h4v-6h6v-4H28v10zm4-22v-6h-4v10h10v-4h-6z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-play-circle">\n
<path d="M20 33l12-9-12-9v18zm4-29C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24 8s16 7.18 16 16-7.18 16-16 16z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-volume-mute">\n <path d="M33 24c0-3.53-2.04-6.58-5-8.05v4.42l4.91 4.91c.06-.42.09-.85.09-1.28zm5 0c0 1.88-.41 3.65-1.08 5.28l3.03 3.03C41.25 29.82 42 27 42 24c0-8.56-5.99-15.72-14-17.54v4.13c5.78 1.72 10 7.07 10 13.41zM8.55 6L6 8.55 15.45 18H6v12h8l10 10V26.55l8.51 8.51c-1.34 1.03-2.85 1.86-4.51 2.36v4.13a17.94 17.94 0 0 0 7.37-3.62L39.45 42 42 39.45l-18-18L8.55 6zM24 8l-4.18 4.18L24 16.36V8z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-volume-low">\n <path d="M14 18v12h8l10 10V8L22 18h-8z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-volume-medium">\n <path d="M37 24c0-3.53-2.04-6.58-5-8.05v16.11c2.96-1.48 5-4.53 5-8.06zm-27-6v12h8l10 10V8L18 18h-8z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id
="vjs-icon-volume-high">\n <path d="M6 18v12h8l10 10V8L14 18H6zm27 6c0-3.53-2.04-6.58-5-8.05v16.11c2.96-1.48 5-4.53 5-8.06zM28 6.46v4.13c5.78 1.72 10 7.07 10 13.41s-4.22 11.69-10 13.41v4.13c8.01-1.82 14-8.97 14-17.54S36.01 8.28 28 6.46z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-spinner">\n <path d="M18.8 21l9.53-16.51C26.94 4.18 25.49 4 24 4c-4.8 0-9.19 1.69-12.64 4.51l7.33 12.69.11-.2zm24.28-3c-1.84-5.85-6.3-10.52-11.99-12.68L23.77 18h19.31zm.52 2H28.62l.58 1 9.53 16.5C41.99 33.94 44 29.21 44 24c0-1.37-.14-2.71-.4-4zm-26.53 4l-7.8-13.5C6.01 14.06 4 18.79 4 24c0 1.37.14 2.71.4 4h14.98l-2.31-4zM4.92 30c1.84 5.85 6.3 10.52 11.99 12.68L24.23 30H4.92zm22.54 0l-7.8 13.51c1.4.31 2.85.49 4.34.49 4.8 0 9.19-1.69 12.64-4.51L29.31 26.8 27.46 30z"></path>\n </symbol>\n <symbol viewBox="0 0 24 24" id="vjs-icon-hd">\n <path d="M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-8 12H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm2-6h4c.55 0 1 .45 1 1v4c0 .55-.45
1-1 1h-4V9zm1.5 4.5h2v-3h-2v3z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-chapters">\n <path d="M6 26h4v-4H6v4zm0 8h4v-4H6v4zm0-16h4v-4H6v4zm8 8h28v-4H14v4zm0 8h28v-4H14v4zm0-20v4h28v-4H14z"></path>\n </symbol>\n <symbol viewBox="0 0 40 40" id="vjs-icon-downloading">\n <path d="M18.208 36.875q-3.208-.292-5.979-1.729-2.771-1.438-4.812-3.729-2.042-2.292-3.188-5.229-1.146-2.938-1.146-6.23 0-6.583 4.334-11.416 4.333-4.834 10.833-5.5v3.166q-5.167.75-8.583 4.646Q6.25 14.75 6.25 19.958q0 5.209 3.396 9.104 3.396 3.896 8.562 4.646zM20 28.417L11.542 20l2.083-2.083 4.917 4.916v-11.25h2.916v11.25l4.875-4.916L28.417 20zm1.792 8.458v-3.167q1.833-.25 3.541-.958 1.709-.708 3.167-1.875l2.333 2.292q-1.958 1.583-4.25 2.541-2.291.959-4.791 1.167zm6.791-27.792q-1.541-1.125-3.25-1.854-1.708-.729-3.541-1.021V3.042q2.5.25 4.77 1.208 2.271.958 4.271 2.5zm4.584 21.584l-2.25-2.25q1.166-1.5 1.854-3.209.687-1.708.937-3.541h3.209q-.292 2.5-1.229 4.791-.938 2.292-2.521 4.209zm.541-12.417q-.291-1
.833-.958-3.562-.667-1.73-1.833-3.188l2.375-2.208q1.541 1.916 2.458 4.208.917 2.292 1.167 4.75z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-file-download">\n <path d="M10.8 40.55q-1.35 0-2.375-1T7.4 37.15v-7.7h3.4v7.7h26.35v-7.7h3.4v7.7q0 1.4-1 2.4t-2.4 1zM24 32.1L13.9 22.05l2.45-2.45 5.95 5.95V7.15h3.4v18.4l5.95-5.95 2.45 2.45z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-file-download-done">\n <path d="M9.8 40.5v-3.45h28.4v3.45zm9.2-9.05L7.4 19.85l2.45-2.35L19 26.65l19.2-19.2 2.4 2.4z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-file-download-off">\n <path d="M4.9 4.75L43.25 43.1 41 45.3l-4.75-4.75q-.05.05-.075.025-.025-.025-.075-.025H10.8q-1.35 0-2.375-1T7.4 37.15v-7.7h3.4v7.7h22.05l-7-7-1.85 1.8L13.9 21.9l1.85-1.85L2.7 7zm26.75 14.7l2.45 2.45-3.75 3.8-2.45-2.5zM25.7 7.15V21.1l-3.4-3.45V7.15z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-share">\n <path d="M36 32.17c-1.52 0-2.89.59-3.93
1.54L17.82 25.4c.11-.45.18-.92.18-1.4s-.07-.95-.18-1.4l14.1-8.23c1.07 1 2.5 1.62 4.08 1.62 3.31 0 6-2.69 6-6s-2.69-6-6-6-6 2.69-6 6c0 .48.07.95.18 1.4l-14.1 8.23c-1.07-1-2.5-1.62-4.08-1.62-3.31 0-6 2.69-6 6s2.69 6 6 6c1.58 0 3.01-.62 4.08-1.62l14.25 8.31c-.1.42-.16.86-.16 1.31A5.83 5.83 0 1 0 36 32.17z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-cog">\n <path d="M38.86 25.95c.08-.64.14-1.29.14-1.95s-.06-1.31-.14-1.95l4.23-3.31c.38-.3.49-.84.24-1.28l-4-6.93c-.25-.43-.77-.61-1.22-.43l-4.98 2.01c-1.03-.79-2.16-1.46-3.38-1.97L29 4.84c-.09-.47-.5-.84-1-.84h-8c-.5 0-.91.37-.99.84l-.75 5.3a14.8 14.8 0 0 0-3.38 1.97L9.9 10.1a1 1 0 0 0-1.22.43l-4 6.93c-.25.43-.14.97.24 1.28l4.22 3.31C9.06 22.69 9 23.34 9 24s.06 1.31.14 1.95l-4.22 3.31c-.38.3-.49.84-.24 1.28l4 6.93c.25.43.77.61 1.22.43l4.98-2.01c1.03.79 2.16 1.46 3.38 1.97l.75 5.3c.08.47.49.84.99.84h8c.5 0 .91-.37.99-.84l.75-5.3a14.8 14.8 0 0 0 3.38-1.97l4.98 2.01a1 1 0 0 0 1.22-.43l4-6.93c.25-.43.14-.97-.24-1.28l-4.22-3.31zM24 31c-3.87
0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-square">\n <path d="M36 8H12c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h24c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zm0 28H12V12h24v24z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-circle">\n <circle cx="24" cy="24" r="20"></circle>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-circle-outline">\n <path d="M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24 8s16 7.18 16 16-7.18 16-16 16z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-circle-inner-circle">\n <path d="M24 4C12.97 4 4 12.97 4 24s8.97 20 20 20 20-8.97 20-20S35.03 4 24 4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24 8s16 7.18 16 16-7.18 16-16 16zm6-16c0 3.31-2.69 6-6 6s-6-2.69-6-6 2.69-6 6-6 6 2.69 6 6z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-cancel">\n <path d="M24 4C12.95 4
4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm10 27.17L31.17 34 24 26.83 16.83 34 14 31.17 21.17 24 14 16.83 16.83 14 24 21.17 31.17 14 34 16.83 26.83 24 34 31.17z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-replay">\n <path d="M24 10V2L14 12l10 10v-8c6.63 0 12 5.37 12 12s-5.37 12-12 12-12-5.37-12-12H8c0 8.84 7.16 16 16 16s16-7.16 16-16-7.16-16-16-16z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-repeat">\n <path d="M14 14h20v6l8-8-8-8v6H10v12h4v-8zm20 20H14v-6l-8 8 8 8v-6h24V26h-4v8z"></path>\n </symbol>\n <symbol viewBox="0 96 48 48" id="vjs-icon-replay-5">\n <path d="M17.689 98l-8.697 8.696 8.697 8.697 2.486-2.485-4.32-4.319h1.302c4.93 0 9.071 1.722 12.424 5.165 3.352 3.443 5.029 7.638 5.029 12.584h3.55c0-2.958-.553-5.73-1.658-8.313-1.104-2.583-2.622-4.841-4.555-6.774-1.932-1.932-4.19-3.45-6.773-4.555-2.584-1.104-5.355-1.657-8.313-1.657H15.5l4.615-4.615zm-8.08 21.659v13.861h11.357v5.008H9.609V143h12.7c.834 0 1.55-.298 2.146-.
894.596-.597.895-1.31.895-2.145v-7.781c0-.835-.299-1.55-.895-2.147a2.929 2.929 0 0 0-2.147-.894h-8.227v-5.096H25.35v-4.384z"></path>\n </symbol>\n <symbol viewBox="0 96 48 48" id="vjs-icon-replay-10">\n <path d="M42.315 125.63c0-4.997-1.694-9.235-5.08-12.713-3.388-3.479-7.571-5.218-12.552-5.218h-1.315l4.363 4.363-2.51 2.51-8.787-8.786L25.221 97l2.45 2.45-4.662 4.663h1.375c2.988 0 5.788.557 8.397 1.673 2.61 1.116 4.892 2.65 6.844 4.602 1.953 1.953 3.487 4.234 4.602 6.844 1.116 2.61 1.674 5.41 1.674 8.398zM8.183 142v-19.657H3.176V117.8h9.643V142zm13.63 0c-1.156 0-2.127-.393-2.912-1.178-.778-.778-1.168-1.746-1.168-2.902v-16.04c0-1.156.393-2.127 1.178-2.912.779-.779 1.746-1.168 2.902-1.168h7.696c1.156 0 2.126.392 2.911 1.177.779.78 1.168 1.747 1.168 2.903v16.04c0 1.156-.392 2.127-1.177 2.912-.779.779-1.746 1.168-2.902 1.168zm.556-4.636h6.583v-15.02H22.37z"></path>\n </symbol>\n <symbol viewBox="0 96 48 48" id="vjs-icon-replay-30">\n <path d="M26.047 97l-8.733 8.732 8.733 8.733 2.496-2.494-4
.336-4.338h1.307c4.95 0 9.108 1.73 12.474 5.187 3.367 3.458 5.051 7.668 5.051 12.635h3.565c0-2.97-.556-5.751-1.665-8.346-1.109-2.594-2.633-4.862-4.574-6.802-1.94-1.941-4.208-3.466-6.803-4.575-2.594-1.109-5.375-1.664-8.345-1.664H23.85l4.634-4.634zM2.555 117.531v4.688h10.297v5.25H5.873v4.687h6.979v5.156H2.555V142H13.36c1.061 0 1.95-.395 2.668-1.186.718-.79 1.076-1.772 1.076-2.94v-16.218c0-1.168-.358-2.149-1.076-2.94-.717-.79-1.607-1.185-2.668-1.185zm22.482.14c-1.149 0-2.11.39-2.885 1.165-.78.78-1.172 1.744-1.172 2.893v15.943c0 1.149.388 2.11 1.163 2.885.78.78 1.745 1.172 2.894 1.172h7.649c1.148 0 2.11-.388 2.884-1.163.78-.78 1.17-1.745 1.17-2.894v-15.943c0-1.15-.386-2.111-1.16-2.885-.78-.78-1.746-1.172-2.894-1.172zm.553 4.518h6.545v14.93H25.59z"></path>\n </symbol>\n <symbol viewBox="0 96 48 48" id="vjs-icon-forward-5">\n <path d="M29.508 97l-2.431 2.43 4.625 4.625h-1.364c-2.965 0-5.742.554-8.332 1.66-2.589 1.107-4.851 2.629-6.788 4.566-1.937 1.937-3.458 4.2-4.565 6.788-1.107 2.59-1.66 5.367-1.66 8.
331h3.557c0-4.957 1.68-9.16 5.04-12.611 3.36-3.45 7.51-5.177 12.451-5.177h1.304l-4.326 4.33 2.49 2.49 8.715-8.716zm-9.783 21.61v13.89h11.382v5.018H19.725V142h12.727a2.93 2.93 0 0 0 2.15-.896 2.93 2.93 0 0 0 .896-2.15v-7.798c0-.837-.299-1.554-.896-2.152a2.93 2.93 0 0 0-2.15-.896h-8.245V123h11.29v-4.392z"></path>\n </symbol>\n <symbol viewBox="0 96 48 48" id="vjs-icon-forward-10">\n <path d="M23.119 97l-2.386 2.383 4.538 4.538h-1.339c-2.908 0-5.633.543-8.173 1.63-2.54 1.085-4.76 2.577-6.66 4.478-1.9 1.9-3.392 4.12-4.478 6.66-1.085 2.54-1.629 5.264-1.629 8.172h3.49c0-4.863 1.648-8.986 4.944-12.372 3.297-3.385 7.368-5.078 12.216-5.078h1.279l-4.245 4.247 2.443 2.442 8.55-8.55zm-9.52 21.45v4.42h4.871V142h4.513v-23.55zm18.136 0c-1.125 0-2.066.377-2.824 1.135-.764.764-1.148 1.709-1.148 2.834v15.612c0 1.124.38 2.066 1.139 2.824.764.764 1.708 1.145 2.833 1.145h7.489c1.125 0 2.066-.378 2.824-1.136.764-.764 1.145-1.709 1.145-2.833v-15.612c0-1.125-.378-2.067-1.136-2.825-.764-.764-1.708-1.145-2.833-1.145zm.54 4
.42h6.408v14.617h-6.407z"></path>\n </symbol>\n <symbol viewBox="0 96 48 48" id="vjs-icon-forward-30">\n <path d="M25.549 97l-2.437 2.434 4.634 4.635H26.38c-2.97 0-5.753.555-8.347 1.664-2.594 1.109-4.861 2.633-6.802 4.574-1.94 1.94-3.465 4.207-4.574 6.802-1.109 2.594-1.664 5.377-1.664 8.347h3.565c0-4.967 1.683-9.178 5.05-12.636 3.366-3.458 7.525-5.187 12.475-5.187h1.307l-4.335 4.338 2.495 2.494 8.732-8.732zm-11.553 20.53v4.689h10.297v5.249h-6.978v4.688h6.978v5.156H13.996V142h10.808c1.06 0 1.948-.395 2.666-1.186.718-.79 1.077-1.771 1.077-2.94v-16.217c0-1.169-.36-2.15-1.077-2.94-.718-.79-1.605-1.186-2.666-1.186zm21.174.168c-1.149 0-2.11.389-2.884 1.163-.78.78-1.172 1.745-1.172 2.894v15.942c0 1.15.388 2.11 1.162 2.885.78.78 1.745 1.17 2.894 1.17h7.649c1.149 0 2.11-.386 2.885-1.16.78-.78 1.17-1.746 1.17-2.895v-15.942c0-1.15-.387-2.11-1.161-2.885-.78-.78-1.745-1.172-2.894-1.172zm.552 4.516h6.542v14.931h-6.542z"></path>\n </symbol>\n <symbol viewBox="0 0 512 512" id="vjs-icon-audio-description">\n
<g fill-rule="evenodd"><path d="M227.29 381.351V162.993c50.38-1.017 89.108-3.028 117.631 17.126 27.374 19.342 48.734 56.965 44.89 105.325-4.067 51.155-41.335 94.139-89.776 98.475-24.085 2.155-71.972 0-71.972 0s-.84-1.352-.773-2.568m48.755-54.804c31.43 1.26 53.208-16.633 56.495-45.386 4.403-38.51-21.188-63.552-58.041-60.796v103.612c-.036 1.466.575 2.22 1.546 2.57"></path><path d="M383.78 381.328c13.336 3.71 17.387-11.06 23.215-21.408 12.722-22.571 22.294-51.594 22.445-84.774.221-47.594-18.343-82.517-35.6-106.182h-8.51c-.587 3.874 2.226 7.315 3.865 10.276 13.166 23.762 25.367 56.553 25.54 94.194.2 43.176-14.162 79.278-30.955 107.894"></path><path d="M425.154 381.328c13.336 3.71 17.384-11.061 23.215-21.408 12.721-22.571 22.291-51.594 22.445-84.774.221-47.594-18.343-82.517-35.6-106.182h-8.511c-.586 3.874 2.226 7.315 3.866 10.276 13.166 23.762 25.367 56.553 25.54 94.194.2 43.176-14.162 79.278-30.955 107.894"></path><path d="M466.26 381.328c13.337 3.71 17.385-11.061 23.216-21.408 12.722-22.571 22.292-51.594
22.445-84.774.221-47.594-18.343-82.517-35.6-106.182h-8.51c-.587 3.874 2.225 7.315 3.865 10.276 13.166 23.762 25.367 56.553 25.54 94.194.2 43.176-14.162 79.278-30.955 107.894M4.477 383.005H72.58l18.573-28.484 64.169-.135s.065 19.413.065 28.62h48.756V160.307h-58.816c-5.653 9.537-140.85 222.697-140.85 222.697zm152.667-145.282v71.158l-40.453-.27 40.453-70.888z"></path></g>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-next-item">\n <path d="M12 36l17-12-17-12v24zm20-24v24h4V12h-4z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-previous-item">\n <path d="M12 12h4v24h-4zm7 12l17 12V12z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-shuffle">\n <path d="M21.17 18.34L10.83 8 8 10.83l10.34 10.34 2.83-2.83zM29 8l4.09 4.09L8 37.17 10.83 40l25.09-25.09L40 19V8H29zm.66 18.83l-2.83 2.83 6.26 6.26L29 40h11V29l-4.09 4.09-6.25-6.26z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-cast">\n <path d="M42 6H6c-2.21 0-4 1.79-4 4
v6h4v-6h36v28H28v4h14c2.21 0 4-1.79 4-4V10c0-2.21-1.79-4-4-4zM2 36v6h6c0-3.31-2.69-6-6-6zm0-8v4c5.52 0 10 4.48 10 10h4c0-7.73-6.27-14-14-14zm0-8v4c9.94 0 18 8.06 18 18h4c0-12.15-9.85-22-22-22z"></path>\n </symbol>\n <symbol viewBox="0 0 48 48" id="vjs-icon-picture-in-picture-enter">\n <path d="M38 22H22v11.99h16V22zm8 16V9.96C46 7.76 44.2 6 42 6H6C3.8 6 2 7.76 2 9.96V38c0 2.2 1.8 4 4 4h36c2.2 0 4-1.8 4-4zm-4 .04H6V9.94h36v28.1z"></path>\n </symbol>\n <symbol viewBox="0 0 22 18" id="vjs-icon-picture-in-picture-exit">\n <path d="M18 4H4v10h14V4zm4 12V1.98C22 .88 21.1 0 20 0H2C.9 0 0 .88 0 1.98V16c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2zm-2 .02H2V1.97h18v14.05z"></path>\n <path fill="none" d="M-1-3h24v24H-1z"></path>\n </symbol>\n <symbol viewBox="0 0 1792 1792" id="vjs-icon-facebook">\n <path d="M1343 12v264h-157q-86 0-116 36t-30 108v189h293l-39 296h-254v759H734V905H479V609h255V391q0-186 104-288.5T1115 0q147 0 228 12z"></path>\n </symbol>\n <symbol viewBox="0 0 1792 1792" id
="vjs-icon-linkedin">\n <path d="M477 625v991H147V625h330zm21-306q1 73-50.5 122T312 490h-2q-82 0-132-49t-50-122q0-74 51.5-122.5T314 148t133 48.5T498 319zm1166 729v568h-329v-530q0-105-40.5-164.5T1168 862q-63 0-105.5 34.5T999 982q-11 30-11 81v553H659q2-399 2-647t-1-296l-1-48h329v144h-2q20-32 41-56t56.5-52 87-43.5T1285 602q171 0 275 113.5t104 332.5z"></path>\n </symbol>\n <symbol viewBox="0 0 1792 1792" id="vjs-icon-twitter">\n <path d="M1684 408q-67 98-162 167 1 14 1 42 0 130-38 259.5T1369.5 1125 1185 1335.5t-258 146-323 54.5q-271 0-496-145 35 4 78 4 225 0 401-138-105-2-188-64.5T285 1033q33 5 61 5 43 0 85-11-112-23-185.5-111.5T172 710v-4q68 38 146 41-66-44-105-115t-39-154q0-88 44-163 121 149 294.5 238.5T884 653q-8-38-8-74 0-134 94.5-228.5T1199 256q140 0 236 102 109-21 205-78-37 115-142 178 93-10 186-50z"></path>\n </symbol>\n <symbol viewBox="0 0 1792 1792" id="vjs-icon-tumblr">\n <path d="M1328 1329l80 237q-23 35-111 66t-177 32q-104 2-190.5-26T787 1564t-95-106-55.5-120-16.5-118V676H
452V461q72-26 129-69.5t91-90 58-102 34-99T779 12q1-5 4.5-8.5T791 0h244v424h333v252h-334v518q0 30 6.5 56t22.5 52.5 49.5 41.5 81.5 14q78-2 134-29z"></path>\n </symbol>\n <symbol viewBox="0 0 1792 1792" id="vjs-icon-pinterest">\n <path d="M1664 896q0 209-103 385.5T1281.5 1561 896 1664q-111 0-218-32 59-93 78-164 9-34 54-211 20 39 73 67.5t114 28.5q121 0 216-68.5t147-188.5 52-270q0-114-59.5-214T1180 449t-255-63q-105 0-196 29t-154.5 77-109 110.5-67 129.5T377 866q0 104 40 183t117 111q30 12 38-20 2-7 8-31t8-30q6-23-11-43-51-61-51-151 0-151 104.5-259.5T904 517q151 0 235.5 82t84.5 213q0 170-68.5 289T980 1220q-61 0-98-43.5T859 1072q8-35 26.5-93.5t30-103T927 800q0-50-27-83t-77-33q-62 0-105 57t-43 142q0 73 25 122l-99 418q-17 70-13 177-206-91-333-281T128 896q0-209 103-385.5T510.5 231 896 128t385.5 103T1561 510.5 1664 896z"></path>\n </symbol>\n </defs>\n</svg>',"image/svg+xml");if(parsedSVG.querySelector("parsererror"))log$1.warn("Failed to load SVG Icons. Falling back to Font Icons."),this.options_.experime
ntalSvgIcons=null;else{const sprite=parsedSVG.documentElement;sprite.style.display="none",this.el_.appendChild(sprite),this.addClass("vjs-svg-icons-enabled")}}this.initChildren(),this.isAudio("audio"===tag.nodeName.toLowerCase()),this.controls()?this.addClass("vjs-controls-enabled"):this.addClass("vjs-controls-disabled"),this.el_.setAttribute("role","region"),this.isAudio()?this.el_.setAttribute("aria-label",this.localize("Audio Player")):this.el_.setAttribute("aria-label",this.localize("Video Player")),this.isAudio()&&this.addClass("vjs-audio"),TOUCH_ENABLED&&this.addClass("vjs-touch-enabled"),IS_IOS||this.addClass("vjs-workinghover"),Player.players[this.id_]=this;const majorVersion="8.10.0".split(".")[0];this.addClass("vjs-v".concat(majorVersion)),this.userActive(!0),this.reportUserActivity(),this.one("play",(e=>this.listenForUserActivity_(e))),this.on("keydown",(e=>this.handleKeyDown(e))),this.on("languagechange",(e=>this.handleLanguagechange(e))),this.breakpoints(this.options_.breakpoints),this.responsiv
e(this.options_.responsive),this.on("ready",(()=>{this.audioPosterMode(this.options_.audioPosterMode),this.audioOnlyMode(this.options_.audioOnlyMode)}))}dispose(){this.trigger("dispose"),this.off("dispose"),off(document,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),off(document,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),Player.players[this.id_]=null,this.tag&&this.tag.player&&(this.tag.player=null),this.el_&&this.el_.player&&(this.el_.player=null),this.tech_&&(this.tech_.dispose(),this.isPosterFromTech_=!1,this.poster_=""),this.playerElIngest_&&(this.playerElIngest_=null),this.tag&&(this.tag=null),middlewareInstances[this.id()]=null,ALL.names.forEach((name=>{const list=this[ALL[name].getterName]();list&&list.off&&list.off()})),super.dispose({restoreEl:this.options_.restoreEl})}createEl(){let el,tag=this.tag,playerElIngest=this.playerElIngest_=tag.parentNode&&tag.parentNode.hasAt
tribute&&tag.parentNode.hasAttribute("data-vjs-player");const divEmbed="video-js"===this.tag.tagName.toLowerCase();playerElIngest?el=this.el_=tag.parentNode:divEmbed||(el=this.el_=super.createEl("div"));const attrs=getAttributes(tag);if(divEmbed){for(el=this.el_=tag,tag=this.tag=document.createElement("video");el.children.length;)tag.appendChild(el.firstChild);hasClass(el,"video-js")||addClass(el,"video-js"),el.appendChild(tag),playerElIngest=this.playerElIngest_=el,Object.keys(el).forEach((k=>{try{tag[k]=el[k]}catch(e){}}))}if(tag.setAttribute("tabindex","-1"),attrs.tabindex="-1",IS_CHROME&&IS_WINDOWS&&(tag.setAttribute("role","application"),attrs.role="application"),tag.removeAttribute("width"),tag.removeAttribute("height"),"width"in attrs&&delete attrs.width,"height"in attrs&&delete attrs.height,Object.getOwnPropertyNames(attrs).forEach((function(attr){divEmbed&&"class"===attr||el.setAttribute(attr,attrs[attr]),divEmbed&&tag.setAttribute(attr,attrs[attr])})),tag.playerId=tag.id,tag.id+="_html5_api",tag.cl
assName="vjs-tech",tag.player=el.player=this,this.addClass("vjs-paused"),!0!==window.VIDEOJS_NO_DYNAMIC_STYLE){this.styleEl_=createStyleElement("vjs-styles-dimensions");const defaultsStyleEl=$(".vjs-styles-defaults"),head=$("head");head.insertBefore(this.styleEl_,defaultsStyleEl?defaultsStyleEl.nextSibling:head.firstChild)}this.fill_=!1,this.fluid_=!1,this.width(this.options_.width),this.height(this.options_.height),this.fill(this.options_.fill),this.fluid(this.options_.fluid),this.aspectRatio(this.options_.aspectRatio),this.crossOrigin(this.options_.crossOrigin||this.options_.crossorigin);const links=tag.getElementsByTagName("a");for(let i=0;i<links.length;i++){const linkEl=links.item(i);addClass(linkEl,"vjs-hidden"),linkEl.setAttribute("hidden","hidden")}return tag.initNetworkState_=tag.networkState,tag.parentNode&&!playerElIngest&&tag.parentNode.insertBefore(el,tag),prependTo(tag,el),this.children_.unshift(tag),this.el_.setAttribute("lang",this.language_),this.el_.setAttribute("translate","no"),this.el_=e
l,el}crossOrigin(value){if(void 0===value)return this.techGet_("crossOrigin");null===value||"anonymous"===value||"use-credentials"===value?(this.techCall_("setCrossOrigin",value),this.posterImage&&this.posterImage.crossOrigin(value)):log$1.warn('crossOrigin must be null, "anonymous" or "use-credentials", given "'.concat(value,'"'))}width(value){return this.dimension("width",value)}height(value){return this.dimension("height",value)}dimension(dimension,value){const privDimension=dimension+"_";if(void 0===value)return this[privDimension]||0;if(""===value||"auto"===value)return this[privDimension]=void 0,void this.updateStyleEl_();const parsedVal=parseFloat(value);isNaN(parsedVal)?log$1.error('Improper value "'.concat(value,'" supplied for for ').concat(dimension)):(this[privDimension]=parsedVal,this.updateStyleEl_())}fluid(bool){if(void 0===bool)return!!this.fluid_;var target,callback;this.fluid_=!!bool,isEvented(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),bool?(this.addClass("vjs-fluid
"),this.fill(!1),callback=()=>{this.on(["playerreset","resize"],this.boundUpdateStyleEl_)},isEvented(target=this)?callback():(target.eventedCallbacks||(target.eventedCallbacks=[]),target.eventedCallbacks.push(callback))):this.removeClass("vjs-fluid"),this.updateStyleEl_()}fill(bool){if(void 0===bool)return!!this.fill_;this.fill_=!!bool,bool?(this.addClass("vjs-fill"),this.fluid(!1)):this.removeClass("vjs-fill")}aspectRatio(ratio){if(void 0===ratio)return this.aspectRatio_;if(!/^\d+\:\d+$/.test(ratio))throw new Error("Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.");this.aspectRatio_=ratio,this.fluid(!0),this.updateStyleEl_()}updateStyleEl_(){if(!0===window.VIDEOJS_NO_DYNAMIC_STYLE){const width="number"==typeof this.width_?this.width_:this.options_.width,height="number"==typeof this.height_?this.height_:this.options_.height,techEl=this.tech_&&this.tech_.el();return void(techEl&&(width>=0&&(techEl.width=width),height>=0&&(techEl.height=height)))}let width,height,
aspectRatio,idClass;aspectRatio=void 0!==this.aspectRatio_&&"auto"!==this.aspectRatio_?this.aspectRatio_:this.videoWidth()>0?this.videoWidth()+":"+this.videoHeight():"16:9";const ratioParts=aspectRatio.split(":"),ratioMultiplier=ratioParts[1]/ratioParts[0];width=void 0!==this.width_?this.width_:void 0!==this.height_?this.height_/ratioMultiplier:this.videoWidth()||300,height=void 0!==this.height_?this.height_:width*ratioMultiplier,idClass=/^[^a-zA-Z]/.test(this.id())?"dimensions-"+this.id():this.id()+"-dimensions",this.addClass(idClass),setTextContent(this.styleEl_,"\n .".concat(idClass," {\n width: ").concat(width,"px;\n height: ").concat(height,"px;\n }\n\n .").concat(idClass,".vjs-fluid:not(.vjs-audio-only-mode) {\n padding-top: ").concat(100*ratioMultiplier,"%;\n }\n "))}loadTech_(techName,source){this.tech_&&this.unloadTech_();const titleTechName=toTitleCase$1(techName),camelTechName=techName.charAt(0).toLowerCase()+techName.slice(1);"Html5"!==titleTechName&&th
is.tag&&(Tech.getTech("Html5").disposeMediaElement(this.tag),this.tag.player=null,this.tag=null),this.techName_=titleTechName,this.isReady_=!1;let autoplay=this.autoplay();("string"==typeof this.autoplay()||!0===this.autoplay()&&this.options_.normalizeAutoplay)&&(autoplay=!1);const techOptions={source:source,autoplay:autoplay,nativeControlsForTouch:this.options_.nativeControlsForTouch,playerId:this.id(),techId:"".concat(this.id(),"_").concat(camelTechName,"_api"),playsinline:this.options_.playsinline,preload:this.options_.preload,loop:this.options_.loop,disablePictureInPicture:this.options_.disablePictureInPicture,muted:this.options_.muted,poster:this.poster(),language:this.language(),playerElIngest:this.playerElIngest_||!1,"vtt.js":this.options_["vtt.js"],canOverridePoster:!!this.options_.techCanOverridePoster,enableSourceset:this.options_.enableSourceset};ALL.names.forEach((name=>{const props=ALL[name];techOptions[props.getterName]=this[props.privateName]})),Object.assign(techOptions,this.options_[titleTec
hName]),Object.assign(techOptions,this.options_[camelTechName]),Object.assign(techOptions,this.options_[techName.toLowerCase()]),this.tag&&(techOptions.tag=this.tag),source&&source.src===this.cache_.src&&this.cache_.currentTime>0&&(techOptions.startTime=this.cache_.currentTime);const TechClass=Tech.getTech(techName);if(!TechClass)throw new Error("No Tech named '".concat(titleTechName,"' exists! '").concat(titleTechName,"' should be registered using videojs.registerTech()'"));this.tech_=new TechClass(techOptions),this.tech_.ready(bind_(this,this.handleTechReady_),!0),textTrackConverter_jsonToTextTracks(this.textTracksJson_||[],this.tech_),TECH_EVENTS_RETRIGGER.forEach((event=>{this.on(this.tech_,event,(e=>this["handleTech".concat(toTitleCase$1(event),"_")](e)))})),Object.keys(TECH_EVENTS_QUEUE).forEach((event=>{this.on(this.tech_,event,(eventObj=>{0===this.tech_.playbackRate()&&this.tech_.seeking()?this.queuedCallbacks_.push({callback:this["handleTech".concat(TECH_EVENTS_QUEUE[event],"_")].bind(this),event:ev
entObj}):this["handleTech".concat(TECH_EVENTS_QUEUE[event],"_")](eventObj)}))})),this.on(this.tech_,"loadstart",(e=>this.handleTechLoadStart_(e))),this.on(this.tech_,"sourceset",(e=>this.handleTechSourceset_(e))),this.on(this.tech_,"waiting",(e=>this.handleTechWaiting_(e))),this.on(this.tech_,"ended",(e=>this.handleTechEnded_(e))),this.on(this.tech_,"seeking",(e=>this.handleTechSeeking_(e))),this.on(this.tech_,"play",(e=>this.handleTechPlay_(e))),this.on(this.tech_,"pause",(e=>this.handleTechPause_(e))),this.on(this.tech_,"durationchange",(e=>this.handleTechDurationChange_(e))),this.on(this.tech_,"fullscreenchange",((e,data)=>this.handleTechFullscreenChange_(e,data))),this.on(this.tech_,"fullscreenerror",((e,err)=>this.handleTechFullscreenError_(e,err))),this.on(this.tech_,"enterpictureinpicture",(e=>this.handleTechEnterPictureInPicture_(e))),this.on(this.tech_,"leavepictureinpicture",(e=>this.handleTechLeavePictureInPicture_(e))),this.on(this.tech_,"error",(e=>this.handleTechError_(e))),this.on(this.tech_,"
posterchange",(e=>this.handleTechPosterChange_(e))),this.on(this.tech_,"textdata",(e=>this.handleTechTextData_(e))),this.on(this.tech_,"ratechange",(e=>this.handleTechRateChange_(e))),this.on(this.tech_,"loadedmetadata",this.boundUpdateStyleEl_),this.usingNativeControls(this.techGet_("controls")),this.controls()&&!this.usingNativeControls()&&this.addTechControlsListeners_(),this.tech_.el().parentNode===this.el()||"Html5"===titleTechName&&this.tag||prependTo(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){ALL.names.forEach((name=>{const props=ALL[name];this[props.privateName]=this[props.getterName]()})),this.textTracksJson_=textTrackConverter_textTracksToJson(this.tech_),this.isReady_=!1,this.tech_.dispose(),this.tech_=!1,this.isPosterFromTech_&&(this.poster_="",this.trigger("posterchange")),this.isPosterFromTech_=!1}tech(safety){return void 0===safety&&log$1.warn("Using the tech directly can be dangerous. I hope you know what you're doing.\nSee https://github.com/video
js/video.js/issues/2617 for more info.\n"),this.tech_}version(){return{"video.js":"8.10.0"}}addTechControlsListeners_(){this.removeTechControlsListeners_(),this.on(this.tech_,"click",this.boundHandleTechClick_),this.on(this.tech_,"dblclick",this.boundHandleTechDoubleClick_),this.on(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.on(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.on(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.on(this.tech_,"tap",this.boundHandleTechTap_)}removeTechControlsListeners_(){this.off(this.tech_,"tap",this.boundHandleTechTap_),this.off(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.off(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.off(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.off(this.tech_,"click",this.boundHandleTechClick_),this.off(this.tech_,"dblclick",this.boundHandleTechDoubleClick_)}handleTechReady_(){this.triggerReady(),this.cache_.volume&&this.techCall_("setVolume",this.cache_.volume),this.h
andleTechPosterChange_(),this.handleTechDurationChange_()}handleTechLoadStart_(){this.removeClass("vjs-ended","vjs-seeking"),this.error(null),this.handleTechDurationChange_(),this.paused()?(this.hasStarted(!1),this.trigger("loadstart")):this.trigger("loadstart"),this.manualAutoplay_(!0===this.autoplay()&&this.options_.normalizeAutoplay?"play":this.autoplay())}manualAutoplay_(type){if(!this.tech_||"string"!=typeof type)return;const resolveMuted=()=>{const previouslyMuted=this.muted();this.muted(!0);const restoreMuted=()=>{this.muted(previouslyMuted)};this.playTerminatedQueue_.push(restoreMuted);const mutedPromise=this.play();if(isPromise(mutedPromise))return mutedPromise.catch((err=>{throw restoreMuted(),new Error("Rejection at manualAutoplay. Restoring muted value. ".concat(err||""))}))};let promise;return"any"!==type||this.muted()?promise="muted"!==type||this.muted()?this.play():resolveMuted():(promise=this.play(),isPromise(promise)&&(promise=promise.catch(resolveMuted))),isPromise(promise)?promise.then((()
=>{this.trigger({type:"autoplay-success",autoplay:type})})).catch((()=>{this.trigger({type:"autoplay-failure",autoplay:type})})):void 0}updateSourceCaches_(){let srcObj=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",src=srcObj,type="";"string"!=typeof src&&(src=srcObj.src,type=srcObj.type),this.cache_.source=this.cache_.source||{},this.cache_.sources=this.cache_.sources||[],src&&!type&&(type=((player,src)=>{if(!src)return"";if(player.cache_.source.src===src&&player.cache_.source.type)return player.cache_.source.type;const matchingSources=player.cache_.sources.filter((s=>s.src===src));if(matchingSources.length)return matchingSources[0].type;const sources=player.$$("source");for(let i=0;i<sources.length;i++){const s=sources[i];if(s.type&&s.src&&s.src===src)return s.type}return getMimetype(src)})(this,src)),this.cache_.source=merge$2({},srcObj,{src:src,type:type});const matchingSources=this.cache_.sources.filter((s=>s.src&&s.src===src)),sourceElSources=[],sourceEls=this.$$("source"),matchingSourceEls
=[];for(let i=0;i<sourceEls.length;i++){const sourceObj=getAttributes(sourceEls[i]);sourceElSources.push(sourceObj),sourceObj.src&&sourceObj.src===src&&matchingSourceEls.push(sourceObj.src)}matchingSourceEls.length&&!matchingSources.length?this.cache_.sources=sourceElSources:matchingSources.length||(this.cache_.sources=[this.cache_.source]),this.cache_.src=src}handleTechSourceset_(event){if(!this.changingSrc_){let updateSourceCaches=src=>this.updateSourceCaches_(src);const playerSrc=this.currentSource().src,eventSrc=event.src;playerSrc&&!/^blob:/.test(playerSrc)&&/^blob:/.test(eventSrc)&&(!this.lastSource_||this.lastSource_.tech!==eventSrc&&this.lastSource_.player!==playerSrc)&&(updateSourceCaches=()=>{}),updateSourceCaches(eventSrc),event.src||this.tech_.any(["sourceset","loadstart"],(e=>{if("sourceset"===e.type)return;const techSrc=this.techGet_("currentSrc");this.lastSource_.tech=techSrc,this.updateSourceCaches_(techSrc)}))}this.lastSource_={player:this.currentSource().src,tech:event.src},this.trigger({sr
c:event.src,type:"sourceset"})}hasStarted(request){if(void 0===request)return this.hasStarted_;request!==this.hasStarted_&&(this.hasStarted_=request,this.hasStarted_?this.addClass("vjs-has-started"):this.removeClass("vjs-has-started"))}handleTechPlay_(){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.hasStarted(!0),this.trigger("play")}handleTechRateChange_(){this.tech_.playbackRate()>0&&0===this.cache_.lastPlaybackRate&&(this.queuedCallbacks_.forEach((queued=>queued.callback(queued.event))),this.queuedCallbacks_=[]),this.cache_.lastPlaybackRate=this.tech_.playbackRate(),this.trigger("ratechange")}handleTechWaiting_(){this.addClass("vjs-waiting"),this.trigger("waiting");const timeWhenWaiting=this.currentTime(),timeUpdateListener=()=>{timeWhenWaiting!==this.currentTime()&&(this.removeClass("vjs-waiting"),this.off("timeupdate",timeUpdateListener))};this.on("timeupdate",timeUpdateListener)}handleTechCanPlay_(){this.removeClass("vjs-waiting"),this.trigger("canplay")}handleTechCanPlay
Through_(){this.removeClass("vjs-waiting"),this.trigger("canplaythrough")}handleTechPlaying_(){this.removeClass("vjs-waiting"),this.trigger("playing")}handleTechSeeking_(){this.addClass("vjs-seeking"),this.trigger("seeking")}handleTechSeeked_(){this.removeClass("vjs-seeking","vjs-ended"),this.trigger("seeked")}handleTechPause_(){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.trigger("pause")}handleTechEnded_(){this.addClass("vjs-ended"),this.removeClass("vjs-waiting"),this.options_.loop?(this.currentTime(0),this.play()):this.paused()||this.pause(),this.trigger("ended")}handleTechDurationChange_(){this.duration(this.techGet_("duration"))}handleTechClick_(event){this.controls_&&(void 0!==this.options_&&void 0!==this.options_.userActions&&void 0!==this.options_.userActions.click&&!1===this.options_.userActions.click||(void 0!==this.options_&&void 0!==this.options_.userActions&&"function"==typeof this.options_.userActions.click?this.options_.userActions.click.call(this,event):this.paused()?sile
ncePromise(this.play()):this.pause()))}handleTechDoubleClick_(event){if(!this.controls_)return;Array.prototype.some.call(this.$$(".vjs-control-bar, .vjs-modal-dialog"),(el=>el.contains(event.target)))||void 0!==this.options_&&void 0!==this.options_.userActions&&void 0!==this.options_.userActions.doubleClick&&!1===this.options_.userActions.doubleClick||(void 0!==this.options_&&void 0!==this.options_.userActions&&"function"==typeof this.options_.userActions.doubleClick?this.options_.userActions.doubleClick.call(this,event):this.isFullscreen()?this.exitFullscreen():this.requestFullscreen())}handleTechTap_(){this.userActive(!this.userActive())}handleTechTouchStart_(){this.userWasActive=this.userActive()}handleTechTouchMove_(){this.userWasActive&&this.reportUserActivity()}handleTechTouchEnd_(event){event.cancelable&&event.preventDefault()}toggleFullscreenClass_(){this.isFullscreen()?this.addClass("vjs-fullscreen"):this.removeClass("vjs-fullscreen")}documentFullscreenChange_(e){const targetPlayer=e.target.player;i
f(targetPlayer&&targetPlayer!==this)return;const el=this.el();let isFs=document[this.fsApi_.fullscreenElement]===el;!isFs&&el.matches&&(isFs=el.matches(":"+this.fsApi_.fullscreen)),this.isFullscreen(isFs)}handleTechFullscreenChange_(event,data){data&&(data.nativeIOSFullscreen&&(this.addClass("vjs-ios-native-fs"),this.tech_.one("webkitendfullscreen",(()=>{this.removeClass("vjs-ios-native-fs")}))),this.isFullscreen(data.isFullscreen))}handleTechFullscreenError_(event,err){this.trigger("fullscreenerror",err)}togglePictureInPictureClass_(){this.isInPictureInPicture()?this.addClass("vjs-picture-in-picture"):this.removeClass("vjs-picture-in-picture")}handleTechEnterPictureInPicture_(event){this.isInPictureInPicture(!0)}handleTechLeavePictureInPicture_(event){this.isInPictureInPicture(!1)}handleTechError_(){const error=this.tech_.error();error&&this.error(error)}handleTechTextData_(){let data=null;arguments.length>1&&(data=arguments[1]),this.trigger("textdata",data)}getCache(){return this.cache_}resetCache_(){this.
cache_={currentTime:0,initTime:0,inactivityTimeout:this.options_.inactivityTimeout,duration:NaN,lastVolume:1,lastPlaybackRate:this.defaultPlaybackRate(),media:null,src:"",source:{},sources:[],playbackRates:[],volume:1}}techCall_(method,arg){this.ready((function(){if(method in allowedSetters)return function(middleware,tech,method,arg){return tech[method](middleware.reduce(middlewareIterator(method),arg))}(this.middleware_,this.tech_,method,arg);if(method in allowedMediators)return mediate(this.middleware_,this.tech_,method,arg);try{this.tech_&&this.tech_[method](arg)}catch(e){throw log$1(e),e}}),!0)}techGet_(method){if(this.tech_&&this.tech_.isReady_){if(method in allowedGetters)return function(middleware,tech,method){return middleware.reduceRight(middlewareIterator(method),tech[method]())}(this.middleware_,this.tech_,method);if(method in allowedMediators)return mediate(this.middleware_,this.tech_,method);try{return this.tech_[method]()}catch(e){if(void 0===this.tech_[method])throw log$1("Video.js: ".concat(m
ethod," method not defined for ").concat(this.techName_," playback technology."),e),e;if("TypeError"===e.name)throw log$1("Video.js: ".concat(method," unavailable on ").concat(this.techName_," playback technology element."),e),this.tech_.isReady_=!1,e;throw log$1(e),e}}}play(){return new Promise((resolve=>{this.play_(resolve)}))}play_(){let callback=arguments.length>0&&void 0!==arguments[0]?arguments[0]:silencePromise;this.playCallbacks_.push(callback);const isSrcReady=Boolean(!this.changingSrc_&&(this.src()||this.currentSrc())),isSafariOrIOS=Boolean(IS_ANY_SAFARI||IS_IOS);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!isSrcReady)return this.waitToPlay_=e=>{this.play_()},this.one(["ready","loadstart"],this.waitToPlay_),void(!isSrcReady&&isSafariOrIOS&&this.load());const val=this.techGet_("play");isSafariOrIOS&&this.hasClass("vjs-ended")&&this.resetProgressBar_(),null===val?this.runPlayTerminatedQueue_():this.runPlayCallbacks_(val)}runPlayTermina
tedQueue_(){const queue=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[],queue.forEach((function(q){q()}))}runPlayCallbacks_(val){const callbacks=this.playCallbacks_.slice(0);this.playCallbacks_=[],this.playTerminatedQueue_=[],callbacks.forEach((function(cb){cb(val)}))}pause(){this.techCall_("pause")}paused(){return!1!==this.techGet_("paused")}played(){return this.techGet_("played")||createTimeRanges$1(0,0)}scrubbing(isScrubbing){if(void 0===isScrubbing)return this.scrubbing_;this.scrubbing_=!!isScrubbing,this.techCall_("setScrubbing",this.scrubbing_),isScrubbing?this.addClass("vjs-scrubbing"):this.removeClass("vjs-scrubbing")}currentTime(seconds){return void 0===seconds?(this.cache_.currentTime=this.techGet_("currentTime")||0,this.cache_.currentTime):(seconds<0&&(seconds=0),this.isReady_&&!this.changingSrc_&&this.tech_&&this.tech_.isReady_?(this.techCall_("setCurrentTime",seconds),this.cache_.initTime=0,void(isFinite(seconds)&&(this.cache_.currentTime=Number(seconds)))):(this.cache_.initTime=
seconds,this.off("canplay",this.boundApplyInitTime_),void this.one("canplay",this.boundApplyInitTime_)))}applyInitTime_(){this.currentTime(this.cache_.initTime)}duration(seconds){if(void 0===seconds)return void 0!==this.cache_.duration?this.cache_.duration:NaN;(seconds=parseFloat(seconds))<0&&(seconds=1/0),seconds!==this.cache_.duration&&(this.cache_.duration=seconds,seconds===1/0?this.addClass("vjs-live"):this.removeClass("vjs-live"),isNaN(seconds)||this.trigger("durationchange"))}remainingTime(){return this.duration()-this.currentTime()}remainingTimeDisplay(){return Math.floor(this.duration())-Math.floor(this.currentTime())}buffered(){let buffered=this.techGet_("buffered");return buffered&&buffered.length||(buffered=createTimeRanges$1(0,0)),buffered}seekable(){let seekable=this.techGet_("seekable");return seekable&&seekable.length||(seekable=createTimeRanges$1(0,0)),seekable}seeking(){return this.techGet_("seeking")}ended(){return this.techGet_("ended")}networkState(){return this.techGet_("networkState")}r
eadyState(){return this.techGet_("readyState")}bufferedPercent(){return bufferedPercent(this.buffered(),this.duration())}bufferedEnd(){const buffered=this.buffered(),duration=this.duration();let end=buffered.end(buffered.length-1);return end>duration&&(end=duration),end}volume(percentAsDecimal){let vol;return void 0!==percentAsDecimal?(vol=Math.max(0,Math.min(1,percentAsDecimal)),this.cache_.volume=vol,this.techCall_("setVolume",vol),void(vol>0&&this.lastVolume_(vol))):(vol=parseFloat(this.techGet_("volume")),isNaN(vol)?1:vol)}muted(muted){if(void 0===muted)return this.techGet_("muted")||!1;this.techCall_("setMuted",muted)}defaultMuted(defaultMuted){return void 0!==defaultMuted&&this.techCall_("setDefaultMuted",defaultMuted),this.techGet_("defaultMuted")||!1}lastVolume_(percentAsDecimal){if(void 0===percentAsDecimal||0===percentAsDecimal)return this.cache_.lastVolume;this.cache_.lastVolume=percentAsDecimal}supportsFullScreen(){return this.techGet_("supportsFullScreen")||!1}isFullscreen(isFS){if(void 0!==isFS
){const oldValue=this.isFullscreen_;return this.isFullscreen_=Boolean(isFS),this.isFullscreen_!==oldValue&&this.fsApi_.prefixed&&this.trigger("fullscreenchange"),void this.toggleFullscreenClass_()}return this.isFullscreen_}requestFullscreen(fullscreenOptions){this.isInPictureInPicture()&&this.exitPictureInPicture();const self=this;return new Promise(((resolve,reject)=>{function offHandler(){self.off("fullscreenerror",errorHandler),self.off("fullscreenchange",changeHandler)}function changeHandler(){offHandler(),resolve()}function errorHandler(e,err){offHandler(),reject(err)}self.one("fullscreenchange",changeHandler),self.one("fullscreenerror",errorHandler);const promise=self.requestFullscreenHelper_(fullscreenOptions);promise&&(promise.then(offHandler,offHandler),promise.then(resolve,reject))}))}requestFullscreenHelper_(fullscreenOptions){let fsOptions;if(this.fsApi_.prefixed||(fsOptions=this.options_.fullscreen&&this.options_.fullscreen.options||{},void 0!==fullscreenOptions&&(fsOptions=fullscreenOptions)),t
his.fsApi_.requestFullscreen){const promise=this.el_[this.fsApi_.requestFullscreen](fsOptions);return promise&&promise.then((()=>this.isFullscreen(!0)),(()=>this.isFullscreen(!1))),promise}this.tech_.supportsFullScreen()&&!0==!this.options_.preferFullWindow?this.techCall_("enterFullScreen"):this.enterFullWindow()}exitFullscreen(){const self=this;return new Promise(((resolve,reject)=>{function offHandler(){self.off("fullscreenerror",errorHandler),self.off("fullscreenchange",changeHandler)}function changeHandler(){offHandler(),resolve()}function errorHandler(e,err){offHandler(),reject(err)}self.one("fullscreenchange",changeHandler),self.one("fullscreenerror",errorHandler);const promise=self.exitFullscreenHelper_();promise&&(promise.then(offHandler,offHandler),promise.then(resolve,reject))}))}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){const promise=document[this.fsApi_.exitFullscreen]();return promise&&silencePromise(promise.then((()=>this.isFullscreen(!1)))),promise}this.tech_.supportsFullScreen
()&&!0==!this.options_.preferFullWindow?this.techCall_("exitFullScreen"):this.exitFullWindow()}enterFullWindow(){this.isFullscreen(!0),this.isFullWindow=!0,this.docOrigOverflow=document.documentElement.style.overflow,on(document,"keydown",this.boundFullWindowOnEscKey_),document.documentElement.style.overflow="hidden",addClass(document.body,"vjs-full-window"),this.trigger("enterFullWindow")}fullWindowOnEscKey(event){keycode.isEventKey(event,"Esc")&&!0===this.isFullscreen()&&(this.isFullWindow?this.exitFullWindow():this.exitFullscreen())}exitFullWindow(){this.isFullscreen(!1),this.isFullWindow=!1,off(document,"keydown",this.boundFullWindowOnEscKey_),document.documentElement.style.overflow=this.docOrigOverflow,removeClass(document.body,"vjs-full-window"),this.trigger("exitFullWindow")}disablePictureInPicture(value){if(void 0===value)return this.techGet_("disablePictureInPicture");this.techCall_("setDisablePictureInPicture",value),this.options_.disablePictureInPicture=value,this.trigger("disablepictureinpicturec
hanged")}isInPictureInPicture(isPiP){return void 0!==isPiP?(this.isInPictureInPicture_=!!isPiP,void this.togglePictureInPictureClass_()):!!this.isInPictureInPicture_}requestPictureInPicture(){if(this.options_.enableDocumentPictureInPicture&&window.documentPictureInPicture){const pipContainer=document.createElement(this.el().tagName);return pipContainer.classList=this.el().classList,pipContainer.classList.add("vjs-pip-container"),this.posterImage&&pipContainer.appendChild(this.posterImage.el().cloneNode(!0)),this.titleBar&&pipContainer.appendChild(this.titleBar.el().cloneNode(!0)),pipContainer.appendChild(createEl("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),window.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then((pipWindow=>(copyStyleSheetsToWindow(pipWindow),this.el_.parentNode.insertBefore(pipContainer,this.el_),pipWindow.document.body.appendChild(this.el_),pipWindow.document.body.classList.add("vjs-pip-window"),this.play
er_.isInPictureInPicture(!0),this.player_.trigger("enterpictureinpicture"),pipWindow.addEventListener("pagehide",(event=>{const pipVideo=event.target.querySelector(".video-js");pipContainer.parentNode.replaceChild(pipVideo,pipContainer),this.player_.isInPictureInPicture(!1),this.player_.trigger("leavepictureinpicture")})),pipWindow)))}return"pictureInPictureEnabled"in document&&!1===this.disablePictureInPicture()?this.techGet_("requestPictureInPicture"):Promise.reject("No PiP mode is available")}exitPictureInPicture(){return window.documentPictureInPicture&&window.documentPictureInPicture.window?(window.documentPictureInPicture.window.close(),Promise.resolve()):"pictureInPictureEnabled"in document?document.exitPictureInPicture():void 0}handleKeyDown(event){const{userActions:userActions}=this.options_;if(!userActions||!userActions.hotkeys)return;(el=>{const tagName=el.tagName.toLowerCase();if(el.isContentEditable)return!0;if("input"===tagName)return-1===["button","checkbox","hidden","radio","reset","submit"].
indexOf(el.type);return-1!==["textarea"].indexOf(tagName)})(this.el_.ownerDocument.activeElement)||("function"==typeof userActions.hotkeys?userActions.hotkeys.call(this,event):this.handleHotkeys(event))}handleHotkeys(event){const hotkeys=this.options_.userActions?this.options_.userActions.hotkeys:{},{fullscreenKey:fullscreenKey=(keydownEvent=>keycode.isEventKey(keydownEvent,"f")),muteKey:muteKey=(keydownEvent=>keycode.isEventKey(keydownEvent,"m")),playPauseKey:playPauseKey=(keydownEvent=>keycode.isEventKey(keydownEvent,"k")||keycode.isEventKey(keydownEvent,"Space"))}=hotkeys;if(fullscreenKey.call(this,event)){event.preventDefault(),event.stopPropagation();const FSToggle=Component$1.getComponent("FullscreenToggle");!1!==document[this.fsApi_.fullscreenEnabled]&&FSToggle.prototype.handleClick.call(this,event)}else if(muteKey.call(this,event)){event.preventDefault(),event.stopPropagation();Component$1.getComponent("MuteToggle").prototype.handleClick.call(this,event)}else if(playPauseKey.call(this,event)){event.p
reventDefault(),event.stopPropagation();Component$1.getComponent("PlayToggle").prototype.handleClick.call(this,event)}}canPlayType(type){let can;for(let i=0,j=this.options_.techOrder;i<j.length;i++){const techName=j[i];let tech=Tech.getTech(techName);if(tech||(tech=Component$1.getComponent(techName)),tech){if(tech.isSupported()&&(can=tech.canPlayType(type),can))return can}else log$1.error('The "'.concat(techName,'" tech is undefined. Skipped browser support check for that tech.'))}return""}selectSource(sources){const techs=this.options_.techOrder.map((techName=>[techName,Tech.getTech(techName)])).filter((_ref6=>{let[techName,tech]=_ref6;return tech?tech.isSupported():(log$1.error('The "'.concat(techName,'" tech is undefined. Skipped browser support check for that tech.')),!1)})),findFirstPassingTechSourcePair=function(outerArray,innerArray,tester){let found;return outerArray.some((outerChoice=>innerArray.some((innerChoice=>{if(found=tester(outerChoice,innerChoice),found)return!0})))),found};let foundSourceAn
dTech;const finder=(_ref7,source)=>{let[techName,tech]=_ref7;if(tech.canPlaySource(source,this.options_[techName.toLowerCase()]))return{source:source,tech:techName}};var fn;return foundSourceAndTech=this.options_.sourceOrder?findFirstPassingTechSourcePair(sources,techs,(fn=finder,(a,b)=>fn(b,a))):findFirstPassingTechSourcePair(techs,sources,finder),foundSourceAndTech||!1}handleSrc_(source,isRetry){if(void 0===source)return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();const sources=filterSource(source);if(sources.length){if(this.changingSrc_=!0,isRetry||(this.cache_.sources=sources),this.updateSourceCaches_(sources[0]),setSource(this,sources[0],((middlewareSource,mws)=>{this.middleware_=mws,isRetry||(this.cache_.sources=sources),this.updateSourceCaches_(middlewareSource);if(this.src_(middlewareSource))return sources.length>1?this.handleSrc_(sources.slice(1)):(this.changingSrc_=!1,this.setTimeout((function(){this.error({code:4,message:this.options_.notSupportedMessage})}),0),void this
.triggerReady());var middleware,tech;middleware=mws,tech=this.tech_,middleware.forEach((mw=>mw.setTech&&mw.setTech(tech)))})),sources.length>1){const retry=()=>{this.error(null),this.handleSrc_(sources.slice(1),!0)},stopListeningForErrors=()=>{this.off("error",retry)};this.one("error",retry),this.one("playing",stopListeningForErrors),this.resetRetryOnError_=()=>{this.off("error",retry),this.off("playing",stopListeningForErrors)}}}else this.setTimeout((function(){this.error({code:4,message:this.options_.notSupportedMessage})}),0)}src(source){return this.handleSrc_(source,!1)}src_(source){const sourceTech=this.selectSource([source]);return!sourceTech||(titleCaseEquals(sourceTech.tech,this.techName_)?(this.ready((function(){this.tech_.constructor.prototype.hasOwnProperty("setSource")?this.techCall_("setSource",source):this.techCall_("src",source.src),this.changingSrc_=!1}),!0),!1):(this.changingSrc_=!0,this.loadTech_(sourceTech.tech,sourceTech.source),this.tech_.ready((()=>{this.changingSrc_=!1})),!1))}load(){t
his.tech_&&this.tech_.vhs?this.src(this.currentSource()):this.techCall_("load")}reset(){if(this.paused())this.doReset_();else{silencePromise(this.play().then((()=>this.doReset_())))}}doReset_(){this.tech_&&this.tech_.clearTracks("text"),this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.resetCache_(),this.poster(""),this.loadTech_(this.options_.techOrder[0],null),this.techCall_("reset"),this.resetControlBarUI_(),this.error(null),this.titleBar&&this.titleBar.update({title:void 0,description:void 0}),isEvented(this)&&this.trigger("playerreset")}resetControlBarUI_(){this.resetProgressBar_(),this.resetPlaybackRate_(),this.resetVolumeBar_()}resetProgressBar_(){this.currentTime(0);const{currentTimeDisplay:currentTimeDisplay,durationDisplay:durationDisplay,progressControl:progressControl,remainingTimeDisplay:remainingTimeDisplay}=this.controlBar||{},{seekBar:seekBar}=progressControl||{};currentTimeDisplay&¤tTimeDisplay.updateContent(),durationDisplay&&durationDisplay.updateContent(),remainingTim
eDisplay&&remainingTimeDisplay.updateContent(),seekBar&&(seekBar.update(),seekBar.loadProgressBar&&seekBar.loadProgressBar.update())}resetPlaybackRate_(){this.playbackRate(this.defaultPlaybackRate()),this.handleTechRateChange_()}resetVolumeBar_(){this.volume(1),this.trigger("volumechange")}currentSources(){const source=this.currentSource(),sources=[];return 0!==Object.keys(source).length&&sources.push(source),this.cache_.sources||sources}currentSource(){return this.cache_.source||{}}currentSrc(){return this.currentSource()&&this.currentSource().src||""}currentType(){return this.currentSource()&&this.currentSource().type||""}preload(value){return void 0!==value?(this.techCall_("setPreload",value),void(this.options_.preload=value)):this.techGet_("preload")}autoplay(value){if(void 0===value)return this.options_.autoplay||!1;let techAutoplay;"string"==typeof value&&/(any|play|muted)/.test(value)||!0===value&&this.options_.normalizeAutoplay?(this.options_.autoplay=value,this.manualAutoplay_("string"==typeof value
?value:"play"),techAutoplay=!1):this.options_.autoplay=!!value,techAutoplay=void 0===techAutoplay?this.options_.autoplay:techAutoplay,this.tech_&&this.techCall_("setAutoplay",techAutoplay)}playsinline(value){return void 0!==value&&(this.techCall_("setPlaysinline",value),this.options_.playsinline=value),this.techGet_("playsinline")}loop(value){return void 0!==value?(this.techCall_("setLoop",value),void(this.options_.loop=value)):this.techGet_("loop")}poster(src){if(void 0===src)return this.poster_;src||(src=""),src!==this.poster_&&(this.poster_=src,this.techCall_("setPoster",src),this.isPosterFromTech_=!1,this.trigger("posterchange"))}handleTechPosterChange_(){if((!this.poster_||this.options_.techCanOverridePoster)&&this.tech_&&this.tech_.poster){const newPoster=this.tech_.poster()||"";newPoster!==this.poster_&&(this.poster_=newPoster,this.isPosterFromTech_=!0,this.trigger("posterchange"))}}controls(bool){if(void 0===bool)return!!this.controls_;bool=!!bool,this.controls_!==bool&&(this.controls_=bool,this.usin
gNativeControls()&&this.techCall_("setControls",bool),this.controls_?(this.removeClass("vjs-controls-disabled"),this.addClass("vjs-controls-enabled"),this.trigger("controlsenabled"),this.usingNativeControls()||this.addTechControlsListeners_()):(this.removeClass("vjs-controls-enabled"),this.addClass("vjs-controls-disabled"),this.trigger("controlsdisabled"),this.usingNativeControls()||this.removeTechControlsListeners_()))}usingNativeControls(bool){if(void 0===bool)return!!this.usingNativeControls_;bool=!!bool,this.usingNativeControls_!==bool&&(this.usingNativeControls_=bool,this.usingNativeControls_?(this.addClass("vjs-using-native-controls"),this.trigger("usingnativecontrols")):(this.removeClass("vjs-using-native-controls"),this.trigger("usingcustomcontrols")))}error(err){if(void 0===err)return this.error_||null;if(hooks("beforeerror").forEach((hookFunction=>{const newErr=hookFunction(this,err);isObject$1(newErr)&&!Array.isArray(newErr)||"string"==typeof newErr||"number"==typeof newErr||null===newErr?err=newE
rr:this.log.error("please return a value that MediaError expects in beforeerror hooks")})),this.options_.suppressNotSupportedError&&err&&4===err.code){const triggerSuppressedError=function(){this.error(err)};return this.options_.suppressNotSupportedError=!1,this.any(["click","touchstart"],triggerSuppressedError),void this.one("loadstart",(function(){this.off(["click","touchstart"],triggerSuppressedError)}))}if(null===err)return this.error_=null,this.removeClass("vjs-error"),void(this.errorDisplay&&this.errorDisplay.close());this.error_=new MediaError(err),this.addClass("vjs-error"),log$1.error("(CODE:".concat(this.error_.code," ").concat(MediaError.errorTypes[this.error_.code],")"),this.error_.message,this.error_),this.trigger("error"),hooks("error").forEach((hookFunction=>hookFunction(this,this.error_)))}reportUserActivity(event){this.userActivity_=!0}userActive(bool){if(void 0===bool)return this.userActive_;if((bool=!!bool)!==this.userActive_){if(this.userActive_=bool,this.userActive_)return this.userActiv
ity_=!0,this.removeClass("vjs-user-inactive"),this.addClass("vjs-user-active"),void this.trigger("useractive");this.tech_&&this.tech_.one("mousemove",(function(e){e.stopPropagation(),e.preventDefault()})),this.userActivity_=!1,this.removeClass("vjs-user-active"),this.addClass("vjs-user-inactive"),this.trigger("userinactive")}}listenForUserActivity_(){let mouseInProgress,lastMoveX,lastMoveY;const handleActivity=bind_(this,this.reportUserActivity),handleMouseUpAndMouseLeave=function(event){handleActivity(),this.clearInterval(mouseInProgress)};this.on("mousedown",(function(){handleActivity(),this.clearInterval(mouseInProgress),mouseInProgress=this.setInterval(handleActivity,250)})),this.on("mousemove",(function(e){e.screenX===lastMoveX&&e.screenY===lastMoveY||(lastMoveX=e.screenX,lastMoveY=e.screenY,handleActivity())})),this.on("mouseup",handleMouseUpAndMouseLeave),this.on("mouseleave",handleMouseUpAndMouseLeave);const controlBar=this.getChild("controlBar");let inactivityTimeout;!controlBar||IS_IOS||IS_ANDROID|
|(controlBar.on("mouseenter",(function(event){0!==this.player().options_.inactivityTimeout&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0})),controlBar.on("mouseleave",(function(event){this.player().options_.inactivityTimeout=this.player().cache_.inactivityTimeout}))),this.on("keydown",handleActivity),this.on("keyup",handleActivity);this.setInterval((function(){if(!this.userActivity_)return;this.userActivity_=!1,this.userActive(!0),this.clearTimeout(inactivityTimeout);const timeout=this.options_.inactivityTimeout;timeout<=0||(inactivityTimeout=this.setTimeout((function(){this.userActivity_||this.userActive(!1)}),timeout))}),250)}playbackRate(rate){if(void 0===rate)return this.tech_&&this.tech_.featuresPlaybackRate?this.cache_.lastPlaybackRate||this.techGet_("playbackRate"):1;this.techCall_("setPlaybackRate",rate)}defaultPlaybackRate(rate){return void 0!==rate?this.techCall_("setDefaultPlaybackRate",rate):this.tech_&&this.tech_.fea
turesPlaybackRate?this.techGet_("defaultPlaybackRate"):1}isAudio(bool){if(void 0===bool)return!!this.isAudio_;this.isAudio_=!!bool}enableAudioOnlyUI_(){this.addClass("vjs-audio-only-mode");const playerChildren=this.children(),controlBar=this.getChild("ControlBar"),controlBarHeight=controlBar&&controlBar.currentHeight();playerChildren.forEach((child=>{child!==controlBar&&child.el_&&!child.hasClass("vjs-hidden")&&(child.hide(),this.audioOnlyCache_.hiddenChildren.push(child))})),this.audioOnlyCache_.playerHeight=this.currentHeight(),this.height(controlBarHeight),this.trigger("audioonlymodechange")}disableAudioOnlyUI_(){this.removeClass("vjs-audio-only-mode"),this.audioOnlyCache_.hiddenChildren.forEach((child=>child.show())),this.height(this.audioOnlyCache_.playerHeight),this.trigger("audioonlymodechange")}audioOnlyMode(value){if("boolean"!=typeof value||value===this.audioOnlyMode_)return this.audioOnlyMode_;if(this.audioOnlyMode_=value,value){const exitPromises=[];return this.isInPictureInPicture()&&exitPromise
s.push(this.exitPictureInPicture()),this.isFullscreen()&&exitPromises.push(this.exitFullscreen()),this.audioPosterMode()&&exitPromises.push(this.audioPosterMode(!1)),Promise.all(exitPromises).then((()=>this.enableAudioOnlyUI_()))}return Promise.resolve().then((()=>this.disableAudioOnlyUI_()))}enablePosterModeUI_(){(this.tech_&&this.tech_).hide(),this.addClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}disablePosterModeUI_(){(this.tech_&&this.tech_).show(),this.removeClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}audioPosterMode(value){if("boolean"!=typeof value||value===this.audioPosterMode_)return this.audioPosterMode_;if(this.audioPosterMode_=value,value){if(this.audioOnlyMode()){return this.audioOnlyMode(!1).then((()=>{this.enablePosterModeUI_()}))}return Promise.resolve().then((()=>{this.enablePosterModeUI_()}))}return Promise.resolve().then((()=>{this.disablePosterModeUI_()}))}addTextTrack(kind,label,language){if(this.tech_)return this.tech_.addTextTrack(kind,la
bel,language)}addRemoteTextTrack(options,manualCleanup){if(this.tech_)return this.tech_.addRemoteTextTrack(options,manualCleanup)}removeRemoteTextTrack(){let obj=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{track:track}=obj;if(track||(track=obj),this.tech_)return this.tech_.removeRemoteTextTrack(track)}getVideoPlaybackQuality(){return this.techGet_("getVideoPlaybackQuality")}videoWidth(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0}videoHeight(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0}language(code){if(void 0===code)return this.language_;this.language_!==String(code).toLowerCase()&&(this.language_=String(code).toLowerCase(),isEvented(this)&&this.trigger("languagechange"))}languages(){return merge$2(Player.prototype.options_.languages,this.languages_)}toJSON(){const options=merge$2(this.options_),tracks=options.tracks;options.tracks=[];for(let i=0;i<tracks.length;i++){let track=tracks[i];track=merge$2(track),track.player=void 0,options.track
s[i]=track}return options}createModal(content,options){(options=options||{}).content=content||"";const modal=new ModalDialog(this,options);return this.addChild(modal),modal.on("dispose",(()=>{this.removeChild(modal)})),modal.open(),modal}updateCurrentBreakpoint_(){if(!this.responsive())return;const currentBreakpoint=this.currentBreakpoint(),currentWidth=this.currentWidth();for(let i=0;i<BREAKPOINT_ORDER.length;i++){const candidateBreakpoint=BREAKPOINT_ORDER[i];if(currentWidth<=this.breakpoints_[candidateBreakpoint]){if(currentBreakpoint===candidateBreakpoint)return;currentBreakpoint&&this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]),this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]),this.breakpoint_=candidateBreakpoint;break}}}removeCurrentBreakpoint_(){const className=this.currentBreakpointClass();this.breakpoint_="",className&&this.removeClass(className)}breakpoints(breakpoints){return void 0===breakpoints||(this.breakpoint_="",this.breakpoints_=Object.assign({},DEFAULT_BREAKPOINTS,breakpoints),t
his.updateCurrentBreakpoint_()),Object.assign(this.breakpoints_)}responsive(value){if(void 0===value)return this.responsive_;return(value=Boolean(value))!==this.responsive_?(this.responsive_=value,value?(this.on("playerresize",this.boundUpdateCurrentBreakpoint_),this.updateCurrentBreakpoint_()):(this.off("playerresize",this.boundUpdateCurrentBreakpoint_),this.removeCurrentBreakpoint_()),value):void 0}currentBreakpoint(){return this.breakpoint_}currentBreakpointClass(){return BREAKPOINT_CLASSES[this.breakpoint_]||""}loadMedia(media,ready){if(!media||"object"!=typeof media)return;const crossOrigin=this.crossOrigin();this.reset(),this.cache_.media=merge$2(media);const{artist:artist,artwork:artwork,description:description,poster:poster,src:src,textTracks:textTracks,title:title}=this.cache_.media;!artwork&&poster&&(this.cache_.media.artwork=[{src:poster,type:getMimetype(poster)}]),crossOrigin&&this.crossOrigin(crossOrigin),src&&this.src(src),poster&&this.poster(poster),Array.isArray(textTracks)&&textTracks.forEac
h((tt=>this.addRemoteTextTrack(tt,!1))),this.titleBar&&this.titleBar.update({title:title,description:description||artist||""}),this.ready(ready)}getMedia(){if(!this.cache_.media){const poster=this.poster(),media={src:this.currentSources(),textTracks:Array.prototype.map.call(this.remoteTextTracks(),(tt=>({kind:tt.kind,label:tt.label,language:tt.language,src:tt.src})))};return poster&&(media.poster=poster,media.artwork=[{src:media.poster,type:getMimetype(media.poster)}]),media}return merge$2(this.cache_.media)}static getTagSettings(tag){const baseOptions={sources:[],tracks:[]},tagOptions=getAttributes(tag),dataSetup=tagOptions["data-setup"];if(hasClass(tag,"vjs-fill")&&(tagOptions.fill=!0),hasClass(tag,"vjs-fluid")&&(tagOptions.fluid=!0),null!==dataSetup){const[err,data]=tuple(dataSetup||"{}");err&&log$1.error(err),Object.assign(tagOptions,data)}if(Object.assign(baseOptions,tagOptions),tag.hasChildNodes()){const children=tag.childNodes;for(let i=0,j=children.length;i<j;i++){const child=children[i],childName=ch
ild.nodeName.toLowerCase();"source"===childName?baseOptions.sources.push(getAttributes(child)):"track"===childName&&baseOptions.tracks.push(getAttributes(child))}}return baseOptions}debug(enabled){if(void 0===enabled)return this.debugEnabled_;enabled?(this.trigger("debugon"),this.previousLogLevel_=this.log.level,this.log.level("debug"),this.debugEnabled_=!0):(this.trigger("debugoff"),this.log.level(this.previousLogLevel_),this.previousLogLevel_=void 0,this.debugEnabled_=!1)}playbackRates(newRates){if(void 0===newRates)return this.cache_.playbackRates;Array.isArray(newRates)&&newRates.every((rate=>"number"==typeof rate))&&(this.cache_.playbackRates=newRates,this.trigger("playbackrateschange"))}}ALL.names.forEach((function(name){const props=ALL[name];Player.prototype[props.getterName]=function(){return this.tech_?this.tech_[props.getterName]():(this[props.privateName]=this[props.privateName]||new props.ListClass,this[props.privateName])}})),Player.prototype.crossorigin=Player.prototype.crossOrigin,Player.playe
rs={};const navigator=window.navigator;Player.prototype.options_={techOrder:Tech.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","titleBar","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:navigator&&(navigator.languages&&navigator.languages[0]||navigator.userLanguage||navigator.language)||"en",languages:{},notSupportedMessage:"No compatible source was found for this media.",normalizeAutoplay:!1,fullscreen:{options:{navigationUI:"hide"}},breakpoints:{},responsive:!1,audioOnlyMode:!1,audioPosterMode:!1,enableSmoothSeeking:!1},TECH_EVENTS_RETRIGGER.forEach((function(event){Player.prototype["handleTech".concat(toTitleCase$1(event),"_")]=function(){return this.trigger(event)}})),Component$1.registerComponent("Player",Player);const pluginStorage={},pluginExists=name=>pluginStorage.hasOwnProperty(name),getPlugin=name=>pluginExists(name)?plug
inStorage[name]:void 0,markPluginAsActive=(player,name)=>{player.activePlugins_=player.activePlugins_||{},player.activePlugins_[name]=!0},triggerSetupEvent=(player,hash,before)=>{const eventName=(before?"before":"")+"pluginsetup";player.trigger(eventName,hash),player.trigger(eventName+":"+hash.name,hash)},createPluginFactory=(name,PluginSubClass)=>(PluginSubClass.prototype.name=name,function(){triggerSetupEvent(this,{name:name,plugin:PluginSubClass,instance:null},!0);for(var _len21=arguments.length,args=new Array(_len21),_key21=0;_key21<_len21;_key21++)args[_key21]=arguments[_key21];const instance=new PluginSubClass(...[this,...args]);return this[name]=()=>instance,triggerSetupEvent(this,instance.getEventHash()),instance});class Plugin{constructor(player){if(this.constructor===Plugin)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=player,this.log||(this.log=this.player.log.createLogger(this.name)),evented(this),delete this.trigger,stateful(this,this.constructor.defaultSt
ate),markPluginAsActive(player,this.name),this.dispose=this.dispose.bind(this),player.on("dispose",this.dispose)}version(){return this.constructor.VERSION}getEventHash(){let hash=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return hash.name=this.name,hash.plugin=this.constructor,hash.instance=this,hash}trigger(event){let hash=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return trigger(this.eventBusEl_,event,this.getEventHash(hash))}handleStateChanged(e){}dispose(){const{name:name,player:player}=this;this.trigger("dispose"),this.off(),player.off("dispose",this.dispose),player.activePlugins_[name]=!1,this.player=this.state=null,player[name]=createPluginFactory(name,pluginStorage[name])}static isBasic(plugin){const p="string"==typeof plugin?getPlugin(plugin):plugin;return"function"==typeof p&&!Plugin.prototype.isPrototypeOf(p.prototype)}static registerPlugin(name,plugin){if("string"!=typeof name)throw new Error('Illegal plugin name, "'.concat(name,'", must be a string, was ').concat(ty
peof name,"."));if(pluginExists(name))log$1.warn('A plugin named "'.concat(name,'" already exists. You may want to avoid re-registering plugins!'));else if(Player.prototype.hasOwnProperty(name))throw new Error('Illegal plugin name, "'.concat(name,'", cannot share a name with an existing player method!'));if("function"!=typeof plugin)throw new Error('Illegal plugin for "'.concat(name,'", must be a function, was ').concat(typeof plugin,"."));return pluginStorage[name]=plugin,"plugin"!==name&&(Plugin.isBasic(plugin)?Player.prototype[name]=function(name,plugin){const basicPluginWrapper=function(){triggerSetupEvent(this,{name:name,plugin:plugin,instance:null},!0);const instance=plugin.apply(this,arguments);return markPluginAsActive(this,name),triggerSetupEvent(this,{name:name,plugin:plugin,instance:instance}),instance};return Object.keys(plugin).forEach((function(prop){basicPluginWrapper[prop]=plugin[prop]})),basicPluginWrapper}(name,plugin):Player.prototype[name]=createPluginFactory(name,plugin)),plugin}static d
eregisterPlugin(name){if("plugin"===name)throw new Error("Cannot de-register base plugin.");pluginExists(name)&&(delete pluginStorage[name],delete Player.prototype[name])}static getPlugins(){let result;return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:Object.keys(pluginStorage)).forEach((name=>{const plugin=getPlugin(name);plugin&&(result=result||{},result[name]=plugin)})),result}static getPluginVersion(name){const plugin=getPlugin(name);return plugin&&plugin.VERSION||""}}function deprecateForMajor(major,oldName,newName,fn){return function(message,fn){let warned=!1;return function(){warned||log$1.warn(message),warned=!0;for(var _len22=arguments.length,args=new Array(_len22),_key22=0;_key22<_len22;_key22++)args[_key22]=arguments[_key22];return fn.apply(this,args)}}("".concat(oldName," is deprecated and will be removed in ").concat(major,".0; please use ").concat(newName," instead."),fn)}Plugin.getPlugin=getPlugin,Plugin.BASE_PLUGIN_NAME="plugin",Plugin.registerPlugin("plugin",Plugin),Player.protot
ype.usingPlugin=function(name){return!!this.activePlugins_&&!0===this.activePlugins_[name]},Player.prototype.hasPlugin=function(name){return!!pluginExists(name)};const normalizeId=id=>0===id.indexOf("#")?id.slice(1):id;function videojs(id,options,ready){let player=videojs.getPlayer(id);if(player)return options&&log$1.warn('Player "'.concat(id,'" is already initialised. Options will not be applied.')),ready&&player.ready(ready),player;const el="string"==typeof id?$("#"+normalizeId(id)):id;if(!isEl(el))throw new TypeError("The element or ID supplied is not valid. (videojs)");const rootNode="getRootNode"in el&&el.getRootNode()instanceof window.ShadowRoot?el.getRootNode():el.ownerDocument.body;el.ownerDocument.defaultView&&rootNode.contains(el)||log$1.warn("The element supplied is not included in the DOM"),!0===(options=options||{}).restoreEl&&(options.restoreEl=(el.parentNode&&el.parentNode.hasAttribute("data-vjs-player")?el.parentNode:el).cloneNode(!0)),hooks("beforesetup").forEach((hookFunction=>{const opts=h
ookFunction(el,merge$2(options));isObject$1(opts)&&!Array.isArray(opts)?options=merge$2(options,opts):log$1.error("please return an object in beforesetup hooks")}));const PlayerComponent=Component$1.getComponent("Player");return player=new PlayerComponent(el,options,ready),hooks("setup").forEach((hookFunction=>hookFunction(player))),player}if(videojs.hooks_=hooks_,videojs.hooks=hooks,videojs.hook=function(type,fn){hooks(type,fn)},videojs.hookOnce=function(type,fn){hooks(type,[].concat(fn).map((original=>{const wrapper=function(){return removeHook(type,wrapper),original(...arguments)};return wrapper})))},videojs.removeHook=removeHook,!0!==window.VIDEOJS_NO_DYNAMIC_STYLE&&isReal()){let style=$(".vjs-styles-defaults");if(!style){style=createStyleElement("vjs-styles-defaults");const head=$("head");head&&head.insertBefore(style,head.firstChild),setTextContent(style,"\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid:not(.vjs-audio-only-mode) {\n padding-top: 56.
25%\n }\n ")}}autoSetupTimeout(1,videojs),videojs.VERSION="8.10.0",videojs.options=Player.prototype.options_,videojs.getPlayers=()=>Player.players,videojs.getPlayer=id=>{const players=Player.players;let tag;if("string"==typeof id){const nId=normalizeId(id),player=players[nId];if(player)return player;tag=$("#"+nId)}else tag=id;if(isEl(tag)){const{player:player,playerId:playerId}=tag;if(player||players[playerId])return player||players[playerId]}},videojs.getAllPlayers=()=>Object.keys(Player.players).map((k=>Player.players[k])).filter(Boolean),videojs.players=Player.players,videojs.getComponent=Component$1.getComponent,videojs.registerComponent=(name,comp)=>(Tech.isTech(comp)&&log$1.warn("The ".concat(name," tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)")),Component$1.registerComponent.call(Component$1,name,comp)),videojs.getTech=Tech.getTech,videojs.registerTech=Tech.registerTech,videojs.use=function(type,middleware){middlewares[type]=middlew
ares[type]||[],middlewares[type].push(middleware)},Object.defineProperty(videojs,"middleware",{value:{},writeable:!1,enumerable:!0}),Object.defineProperty(videojs.middleware,"TERMINATOR",{value:TERMINATOR,writeable:!1,enumerable:!0}),videojs.browser=browser,videojs.obj=Obj,videojs.mergeOptions=deprecateForMajor(9,"videojs.mergeOptions","videojs.obj.merge",merge$2),videojs.defineLazyProperty=deprecateForMajor(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",defineLazyProperty),videojs.bind=deprecateForMajor(9,"videojs.bind","native Function.prototype.bind",bind_),videojs.registerPlugin=Plugin.registerPlugin,videojs.deregisterPlugin=Plugin.deregisterPlugin,videojs.plugin=(name,plugin)=>(log$1.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),Plugin.registerPlugin(name,plugin)),videojs.getPlugins=Plugin.getPlugins,videojs.getPlugin=Plugin.getPlugin,videojs.getPluginVersion=Plugin.getPluginVersion,videojs.addLanguage=function(code,data){return code=(""+code).toLowerCase(
),videojs.options.languages=merge$2(videojs.options.languages,{[code]:data}),videojs.options.languages[code]},videojs.log=log$1,videojs.createLogger=createLogger,videojs.time=Time,videojs.createTimeRange=deprecateForMajor(9,"videojs.createTimeRange","videojs.time.createTimeRanges",createTimeRanges$1),videojs.createTimeRanges=deprecateForMajor(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",createTimeRanges$1),videojs.formatTime=deprecateForMajor(9,"videojs.formatTime","videojs.time.formatTime",formatTime),videojs.setFormatTime=deprecateForMajor(9,"videojs.setFormatTime","videojs.time.setFormatTime",setFormatTime),videojs.resetFormatTime=deprecateForMajor(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",resetFormatTime),videojs.parseUrl=deprecateForMajor(9,"videojs.parseUrl","videojs.url.parseUrl",parseUrl),videojs.isCrossOrigin=deprecateForMajor(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",isCrossOrigin),videojs.EventTarget=EventTarget$2,videojs.any=any,videojs.on=on,videojs.o
ne=one,videojs.off=off,videojs.trigger=trigger,videojs.xhr=lib,videojs.TextTrack=TextTrack,videojs.AudioTrack=AudioTrack,videojs.VideoTrack=VideoTrack,["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach((k=>{videojs[k]=function(){return log$1.warn("videojs.".concat(k,"() is deprecated; use videojs.dom.").concat(k,"() instead")),Dom[k].apply(null,arguments)}})),videojs.computedStyle=deprecateForMajor(9,"videojs.computedStyle","videojs.dom.computedStyle",computedStyle),videojs.dom=Dom,videojs.fn=Fn,videojs.num=Num,videojs.str=Str,videojs.url=Url,createCommonjsModule((function(module,exports){
/*! @name videojs-contrib-quality-levels @version 4.0.0 @license Apache-2.0 */
module.exports=function(videojs){function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var videojs__default=_interopDefaultLegacy(videojs);class QualityLevel{constructor(representation){let level=this;return level.id=representation.id,level.label=level.id,level.width=representation.width,level.height=representation.height,level.bitrate=representation.bandwidth,level.frameRate=representation.frameRate,level.enabled_=representation.enabled,Object.defineProperty(level,"enabled",{get:()=>level.enabled_(),set(enable){level.enabled_(enable)}}),level}}class QualityLevelList extends videojs__default.default.EventTarget{constructor(){super();let list=this;return list.levels_=[],list.selectedIndex_=-1,Object.defineProperty(list,"selectedIndex",{get:()=>list.selectedIndex_}),Object.defineProperty(list,"length",{get:()=>list.levels_.length}),list[Symbol.iterator]=()=>list.levels_.values(),list}addQualityLevel(representation){let qualityLevel=this.getQualityLevelById(representation.i
d);if(qualityLevel)return qualityLevel;const index=this.levels_.length;return qualityLevel=new QualityLevel(representation),""+index in this||Object.defineProperty(this,index,{get(){return this.levels_[index]}}),this.levels_.push(qualityLevel),this.trigger({qualityLevel:qualityLevel,type:"addqualitylevel"}),qualityLevel}removeQualityLevel(qualityLevel){let removed=null;for(let i=0,l=this.length;i<l;i++)if(this[i]===qualityLevel){removed=this.levels_.splice(i,1)[0],this.selectedIndex_===i?this.selectedIndex_=-1:this.selectedIndex_>i&&this.selectedIndex_--;break}return removed&&this.trigger({qualityLevel:qualityLevel,type:"removequalitylevel"}),removed}getQualityLevelById(id){for(let i=0,l=this.length;i<l;i++){const level=this[i];if(level.id===id)return level}return null}dispose(){this.selectedIndex_=-1,this.levels_.length=0}}QualityLevelList.prototype.allowedEvents_={change:"change",addqualitylevel:"addqualitylevel",removequalitylevel:"removequalitylevel"};for(const event in QualityLevelList.prototype.allowed
Events_)QualityLevelList.prototype["on"+event]=null;var version="4.0.0";const initPlugin=function(player,options){const originalPluginFn=player.qualityLevels,qualityLevelList=new QualityLevelList,disposeHandler=function(){qualityLevelList.dispose(),player.qualityLevels=originalPluginFn,player.off("dispose",disposeHandler)};return player.on("dispose",disposeHandler),player.qualityLevels=()=>qualityLevelList,player.qualityLevels.VERSION=version,qualityLevelList},qualityLevels=function(options){return initPlugin(this,videojs__default.default.obj.merge({},options))};return videojs__default.default.registerPlugin("qualityLevels",qualityLevels),qualityLevels.VERSION=version,qualityLevels}(videojs)}));var urlToolkit=createCommonjsModule((function(module,exports){var 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(baseURL,relativeURL,opts){if(opts=opts||{},baseURL=baseURL.trim(),!(relativeURL=relativeURL.trim())){if(!opts.alwaysNormalize)return baseURL;var basePartsForNormalise=URLToolkit.parseURL(baseURL);if(!basePartsForNormalise)throw new Error("Error trying to parse base URL.");return basePartsForNormalise.path=URLToolkit.normalizePath(basePartsForNormalise.path),URLToolkit.buildURLFromParts(basePartsForNormalise)}var relativeParts=URLToolkit.parseURL(relativeURL);if(!relativeParts)throw new Error("Error trying to parse relative URL.");if(relativeParts.scheme)return opts.alwaysNormalize?(relativeParts.path=URLToolkit.normalizePath(relativeParts.path),URLToolkit.buildURLFromParts(relativeParts)):relativeURL;var baseParts=URLToolkit.parseURL(baseURL);if(!baseParts)throw new Error("Error trying to parse base URL.");if(!baseParts.netLoc&&baseParts.path&&"/"!==baseParts.path[0]
){var pathParts=FIRST_SEGMENT_REGEX.exec(baseParts.path);baseParts.netLoc=pathParts[1],baseParts.path=pathParts[2]}baseParts.netLoc&&!baseParts.path&&(baseParts.path="/");var builtParts={scheme:baseParts.scheme,netLoc:relativeParts.netLoc,path:null,params:relativeParts.params,query:relativeParts.query,fragment:relativeParts.fragment};if(!relativeParts.netLoc&&(builtParts.netLoc=baseParts.netLoc,"/"!==relativeParts.path[0]))if(relativeParts.path){var baseURLPath=baseParts.path,newPath=baseURLPath.substring(0,baseURLPath.lastIndexOf("/")+1)+relativeParts.path;builtParts.path=URLToolkit.normalizePath(newPath)}else builtParts.path=baseParts.path,relativeParts.params||(builtParts.params=baseParts.params,relativeParts.query||(builtParts.query=baseParts.query));return null===builtParts.path&&(builtParts.path=opts.alwaysNormalize?URLToolkit.normalizePath(relativeParts.path):relativeParts.path),URLToolkit.buildURLFromParts(builtParts)},parseURL:function(url){var parts=URL_REGEX.exec(url);return parts?{scheme:parts[1]
||"",netLoc:parts[2]||"",path:parts[3]||"",params:parts[4]||"",query:parts[5]||"",fragment:parts[6]||""}:null},normalizePath:function(path){for(path=path.split("").reverse().join("").replace(SLASH_DOT_REGEX,"");path.length!==(path=path.replace(SLASH_DOT_DOT_REGEX,"")).length;);return path.split("").reverse().join("")},buildURLFromParts:function(parts){return parts.scheme+parts.netLoc+parts.path+parts.params+parts.query+parts.fragment}},module.exports=URLToolkit})),resolveUrl$1=function(baseUrl,relativeUrl){if(/^[a-z]+:/i.test(relativeUrl))return relativeUrl;/^data:/.test(baseUrl)&&(baseUrl=window.location&&window.location.href||"");var nativeURL="function"==typeof window.URL,protocolLess=/^\/\//.test(baseUrl),removeLocation=!window.location&&!/\/\//i.test(baseUrl);if(nativeURL?baseUrl=new window.URL(baseUrl,window.location||"http://example.com"):/\/\//i.test(baseUrl)||(baseUrl=urlToolkit.buildAbsoluteURL(window.location&&window.location.href||"",baseUrl)),nativeURL){var newUrl=new URL(relativeUrl,baseUrl);re
turn removeLocation?newUrl.href.slice("http://example.com".length):protocolLess?newUrl.href.slice(newUrl.protocol.length):newUrl.href}return urlToolkit.buildAbsoluteURL(baseUrl,relativeUrl)},Stream=function(){function Stream(){this.listeners={}}var _proto=Stream.prototype;return _proto.on=function(type,listener){this.listeners[type]||(this.listeners[type]=[]),this.listeners[type].push(listener)},_proto.off=function(type,listener){if(!this.listeners[type])return!1;var index=this.listeners[type].indexOf(listener);return this.listeners[type]=this.listeners[type].slice(0),this.listeners[type].splice(index,1),index>-1},_proto.trigger=function(type){var callbacks=this.listeners[type];if(callbacks)if(2===arguments.length)for(var length=callbacks.length,i=0;i<length;++i)callbacks[i].call(this,arguments[1]);else for(var args=Array.prototype.slice.call(arguments,1),_length=callbacks.length,_i=0;_i<_length;++_i)callbacks[_i].apply(this,args)},_proto.dispose=function(){this.listeners={}},_proto.pipe=function(destination
){this.on("data",(function(data){destination.push(data)}))},Stream}();function decodeB64ToUint8Array$1(b64Text){for(var s,decodedString=(s=b64Text,window.atob?window.atob(s):Buffer.from(s,"base64").toString("binary")),array=new Uint8Array(decodedString.length),i=0;i<decodedString.length;i++)array[i]=decodedString.charCodeAt(i);return array}
/*! @name m3u8-parser @version 7.1.0 @license Apache-2.0 */class LineStream extends Stream{constructor(){super(),this.buffer=""}push(data){let nextNewline;for(this.buffer+=data,nextNewline=this.buffer.indexOf("\n");nextNewline>-1;nextNewline=this.buffer.indexOf("\n"))this.trigger("data",this.buffer.substring(0,nextNewline)),this.buffer=this.buffer.substring(nextNewline+1)}}const TAB=String.fromCharCode(9),parseByterange=function(byterangeString){const match=/([0-9.]*)?@?([0-9.]*)?/.exec(byterangeString||""),result={};return match[1]&&(result.length=parseInt(match[1],10)),match[2]&&(result.offset=parseInt(match[2],10)),result},parseAttributes$1=function(attributes){const result={};if(!attributes)return result;const attrs=attributes.split(new RegExp('(?:^|,)((?:[^=]*)=(?:"[^"]*"|[^,]*))'));let attr,i=attrs.length;for(;i--;)""!==attrs[i]&&(attr=/([^=]*)=(.*)/.exec(attrs[i]).slice(1),attr[0]=attr[0].replace(/^\s+|\s+$/g,""),attr[1]=attr[1].replace(/^\s+|\s+$/g,""),attr[1]=attr[1].replace(/^['"](.*)['"]$/g,"$1"),
result[attr[0]]=attr[1]);return result};class ParseStream extends Stream{constructor(){super(),this.customParsers=[],this.tagMappers=[]}push(line){let match,event;if(0===(line=line.trim()).length)return;if("#"!==line[0])return void this.trigger("data",{type:"uri",uri:line});this.tagMappers.reduce(((acc,mapper)=>{const mappedLine=mapper(line);return mappedLine===line?acc:acc.concat([mappedLine])}),[line]).forEach((newLine=>{for(let i=0;i<this.customParsers.length;i++)if(this.customParsers[i].call(this,newLine))return;if(0===newLine.indexOf("#EXT"))if(newLine=newLine.replace("\r",""),match=/^#EXTM3U/.exec(newLine),match)this.trigger("data",{type:"tag",tagType:"m3u"});else{if(match=/^#EXTINF:([0-9\.]*)?,?(.*)?$/.exec(newLine),match)return event={type:"tag",tagType:"inf"},match[1]&&(event.duration=parseFloat(match[1])),match[2]&&(event.title=match[2]),void this.trigger("data",event);if(match=/^#EXT-X-TARGETDURATION:([0-9.]*)?/.exec(newLine),match)return event={type:"tag",tagType:"targetduration"},match[1]&&(even
t.duration=parseInt(match[1],10)),void this.trigger("data",event);if(match=/^#EXT-X-VERSION:([0-9.]*)?/.exec(newLine),match)return event={type:"tag",tagType:"version"},match[1]&&(event.version=parseInt(match[1],10)),void this.trigger("data",event);if(match=/^#EXT-X-MEDIA-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine),match)return event={type:"tag",tagType:"media-sequence"},match[1]&&(event.number=parseInt(match[1],10)),void this.trigger("data",event);if(match=/^#EXT-X-DISCONTINUITY-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine),match)return event={type:"tag",tagType:"discontinuity-sequence"},match[1]&&(event.number=parseInt(match[1],10)),void this.trigger("data",event);if(match=/^#EXT-X-PLAYLIST-TYPE:(.*)?$/.exec(newLine),match)return event={type:"tag",tagType:"playlist-type"},match[1]&&(event.playlistType=match[1]),void this.trigger("data",event);if(match=/^#EXT-X-BYTERANGE:(.*)?$/.exec(newLine),match)return event=_extends$1(parseByterange(match[1]),{type:"tag",tagType:"byterange"}),void this.trigger("data",event);if(match=/
^#EXT-X-ALLOW-CACHE:(YES|NO)?/.exec(newLine),match)return event={type:"tag",tagType:"allow-cache"},match[1]&&(event.allowed=!/NO/.test(match[1])),void this.trigger("data",event);if(match=/^#EXT-X-MAP:(.*)$/.exec(newLine),match){if(event={type:"tag",tagType:"map"},match[1]){const attributes=parseAttributes$1(match[1]);attributes.URI&&(event.uri=attributes.URI),attributes.BYTERANGE&&(event.byterange=parseByterange(attributes.BYTERANGE))}this.trigger("data",event)}else if(match=/^#EXT-X-STREAM-INF:(.*)$/.exec(newLine),match){if(event={type:"tag",tagType:"stream-inf"},match[1]){if(event.attributes=parseAttributes$1(match[1]),event.attributes.RESOLUTION){const split=event.attributes.RESOLUTION.split("x"),resolution={};split[0]&&(resolution.width=parseInt(split[0],10)),split[1]&&(resolution.height=parseInt(split[1],10)),event.attributes.RESOLUTION=resolution}event.attributes.BANDWIDTH&&(event.attributes.BANDWIDTH=parseInt(event.attributes.BANDWIDTH,10)),event.attributes["FRAME-RATE"]&&(event.attributes["FRAME-RATE
"]=parseFloat(event.attributes["FRAME-RATE"])),event.attributes["PROGRAM-ID"]&&(event.attributes["PROGRAM-ID"]=parseInt(event.attributes["PROGRAM-ID"],10))}this.trigger("data",event)}else{if(match=/^#EXT-X-MEDIA:(.*)$/.exec(newLine),match)return event={type:"tag",tagType:"media"},match[1]&&(event.attributes=parseAttributes$1(match[1])),void this.trigger("data",event);if(match=/^#EXT-X-ENDLIST/.exec(newLine),match)this.trigger("data",{type:"tag",tagType:"endlist"});else if(match=/^#EXT-X-DISCONTINUITY/.exec(newLine),match)this.trigger("data",{type:"tag",tagType:"discontinuity"});else{if(match=/^#EXT-X-PROGRAM-DATE-TIME:(.*)$/.exec(newLine),match)return event={type:"tag",tagType:"program-date-time"},match[1]&&(event.dateTimeString=match[1],event.dateTimeObject=new Date(match[1])),void this.trigger("data",event);if(match=/^#EXT-X-KEY:(.*)$/.exec(newLine),match)return event={type:"tag",tagType:"key"},match[1]&&(event.attributes=parseAttributes$1(match[1]),event.attributes.IV&&("0x"===event.attributes.IV.substrin
g(0,2).toLowerCase()&&(event.attributes.IV=event.attributes.IV.substring(2)),event.attributes.IV=event.attributes.IV.match(/.{8}/g),event.attributes.IV[0]=parseInt(event.attributes.IV[0],16),event.attributes.IV[1]=parseInt(event.attributes.IV[1],16),event.attributes.IV[2]=parseInt(event.attributes.IV[2],16),event.attributes.IV[3]=parseInt(event.attributes.IV[3],16),event.attributes.IV=new Uint32Array(event.attributes.IV))),void this.trigger("data",event);if(match=/^#EXT-X-START:(.*)$/.exec(newLine),match)return event={type:"tag",tagType:"start"},match[1]&&(event.attributes=parseAttributes$1(match[1]),event.attributes["TIME-OFFSET"]=parseFloat(event.attributes["TIME-OFFSET"]),event.attributes.PRECISE=/YES/.test(event.attributes.PRECISE)),void this.trigger("data",event);if(match=/^#EXT-X-CUE-OUT-CONT:(.*)?$/.exec(newLine),match)return event={type:"tag",tagType:"cue-out-cont"},match[1]?event.data=match[1]:event.data="",void this.trigger("data",event);if(match=/^#EXT-X-CUE-OUT:(.*)?$/.exec(newLine),match)return
event={type:"tag",tagType:"cue-out"},match[1]?event.data=match[1]:event.data="",void this.trigger("data",event);if(match=/^#EXT-X-CUE-IN:(.*)?$/.exec(newLine),match)return event={type:"tag",tagType:"cue-in"},match[1]?event.data=match[1]:event.data="",void this.trigger("data",event);if(match=/^#EXT-X-SKIP:(.*)$/.exec(newLine),match&&match[1])return event={type:"tag",tagType:"skip"},event.attributes=parseAttributes$1(match[1]),event.attributes.hasOwnProperty("SKIPPED-SEGMENTS")&&(event.attributes["SKIPPED-SEGMENTS"]=parseInt(event.attributes["SKIPPED-SEGMENTS"],10)),event.attributes.hasOwnProperty("RECENTLY-REMOVED-DATERANGES")&&(event.attributes["RECENTLY-REMOVED-DATERANGES"]=event.attributes["RECENTLY-REMOVED-DATERANGES"].split(TAB)),void this.trigger("data",event);if(match=/^#EXT-X-PART:(.*)$/.exec(newLine),match&&match[1])return event={type:"tag",tagType:"part"},event.attributes=parseAttributes$1(match[1]),["DURATION"].forEach((function(key){event.attributes.hasOwnProperty(key)&&(event.attributes[key]=pars
eFloat(event.attributes[key]))})),["INDEPENDENT","GAP"].forEach((function(key){event.attributes.hasOwnProperty(key)&&(event.attributes[key]=/YES/.test(event.attributes[key]))})),event.attributes.hasOwnProperty("BYTERANGE")&&(event.attributes.byterange=parseByterange(event.attributes.BYTERANGE)),void this.trigger("data",event);if(match=/^#EXT-X-SERVER-CONTROL:(.*)$/.exec(newLine),match&&match[1])return event={type:"tag",tagType:"server-control"},event.attributes=parseAttributes$1(match[1]),["CAN-SKIP-UNTIL","PART-HOLD-BACK","HOLD-BACK"].forEach((function(key){event.attributes.hasOwnProperty(key)&&(event.attributes[key]=parseFloat(event.attributes[key]))})),["CAN-SKIP-DATERANGES","CAN-BLOCK-RELOAD"].forEach((function(key){event.attributes.hasOwnProperty(key)&&(event.attributes[key]=/YES/.test(event.attributes[key]))})),void this.trigger("data",event);if(match=/^#EXT-X-PART-INF:(.*)$/.exec(newLine),match&&match[1])return event={type:"tag",tagType:"part-inf"},event.attributes=parseAttributes$1(match[1]),["PART-T
ARGET"].forEach((function(key){event.attributes.hasOwnProperty(key)&&(event.attributes[key]=parseFloat(event.attributes[key]))})),void this.trigger("data",event);if(match=/^#EXT-X-PRELOAD-HINT:(.*)$/.exec(newLine),match&&match[1])return event={type:"tag",tagType:"preload-hint"},event.attributes=parseAttributes$1(match[1]),["BYTERANGE-START","BYTERANGE-LENGTH"].forEach((function(key){if(event.attributes.hasOwnProperty(key)){event.attributes[key]=parseInt(event.attributes[key],10);const subkey="BYTERANGE-LENGTH"===key?"length":"offset";event.attributes.byterange=event.attributes.byterange||{},event.attributes.byterange[subkey]=event.attributes[key],delete event.attributes[key]}})),void this.trigger("data",event);if(match=/^#EXT-X-RENDITION-REPORT:(.*)$/.exec(newLine),match&&match[1])return event={type:"tag",tagType:"rendition-report"},event.attributes=parseAttributes$1(match[1]),["LAST-MSN","LAST-PART"].forEach((function(key){event.attributes.hasOwnProperty(key)&&(event.attributes[key]=parseInt(event.attribute
s[key],10))})),void this.trigger("data",event);if(match=/^#EXT-X-DATERANGE:(.*)$/.exec(newLine),match&&match[1]){event={type:"tag",tagType:"daterange"},event.attributes=parseAttributes$1(match[1]),["ID","CLASS"].forEach((function(key){event.attributes.hasOwnProperty(key)&&(event.attributes[key]=String(event.attributes[key]))})),["START-DATE","END-DATE"].forEach((function(key){event.attributes.hasOwnProperty(key)&&(event.attributes[key]=new Date(event.attributes[key]))})),["DURATION","PLANNED-DURATION"].forEach((function(key){event.attributes.hasOwnProperty(key)&&(event.attributes[key]=parseFloat(event.attributes[key]))})),["END-ON-NEXT"].forEach((function(key){event.attributes.hasOwnProperty(key)&&(event.attributes[key]=/YES/i.test(event.attributes[key]))})),["SCTE35-CMD"," SCTE35-OUT","SCTE35-IN"].forEach((function(key){event.attributes.hasOwnProperty(key)&&(event.attributes[key]=event.attributes[key].toString(16))}));const clientAttributePattern=/^X-([A-Z]+-)+[A-Z]+$/;for(const key in event.attributes){if(
!clientAttributePattern.test(key))continue;const isHexaDecimal=/[0-9A-Fa-f]{6}/g.test(event.attributes[key]),isDecimalFloating=/^\d+(\.\d+)?$/.test(event.attributes[key]);event.attributes[key]=isHexaDecimal?event.attributes[key].toString(16):isDecimalFloating?parseFloat(event.attributes[key]):String(event.attributes[key])}this.trigger("data",event)}else if(match=/^#EXT-X-INDEPENDENT-SEGMENTS/.exec(newLine),match)this.trigger("data",{type:"tag",tagType:"independent-segments"});else{if(match=/^#EXT-X-CONTENT-STEERING:(.*)$/.exec(newLine),match)return event={type:"tag",tagType:"content-steering"},event.attributes=parseAttributes$1(match[1]),void this.trigger("data",event);this.trigger("data",{type:"tag",data:newLine.slice(4)})}}}}else this.trigger("data",{type:"comment",text:newLine.slice(1)})}))}addParser(_ref8){let{expression:expression,customType:customType,dataParser:dataParser,segment:segment}=_ref8;"function"!=typeof dataParser&&(dataParser=line=>line),this.customParsers.push((line=>{if(expression.exec(li
ne))return this.trigger("data",{type:"custom",data:dataParser(line),customType:customType,segment:segment}),!0}))}addTagMapper(_ref9){let{expression:expression,map:map}=_ref9;this.tagMappers.push((line=>expression.test(line)?map(line):line))}}const camelCaseKeys=function(attributes){const result={};return Object.keys(attributes).forEach((function(key){var str;result[(str=key,str.toLowerCase().replace(/-(\w)/g,(a=>a[1].toUpperCase())))]=attributes[key]})),result},setHoldBack=function(manifest){const{serverControl:serverControl,targetDuration:targetDuration,partTargetDuration:partTargetDuration}=manifest;if(!serverControl)return;const tag="#EXT-X-SERVER-CONTROL",hb="holdBack",phb="partHoldBack",minTargetDuration=targetDuration&&3*targetDuration,minPartDuration=partTargetDuration&&2*partTargetDuration;targetDuration&&!serverControl.hasOwnProperty(hb)&&(serverControl[hb]=minTargetDuration,this.trigger("info",{message:"".concat(tag," defaulting HOLD-BACK to targetDuration * 3 (").concat(minTargetDuration,").")}))
,minTargetDuration&&serverControl[hb]<minTargetDuration&&(this.trigger("warn",{message:"".concat(tag," clamping HOLD-BACK (").concat(serverControl[hb],") to targetDuration * 3 (").concat(minTargetDuration,")")}),serverControl[hb]=minTargetDuration),partTargetDuration&&!serverControl.hasOwnProperty(phb)&&(serverControl[phb]=3*partTargetDuration,this.trigger("info",{message:"".concat(tag," defaulting PART-HOLD-BACK to partTargetDuration * 3 (").concat(serverControl[phb],").")})),partTargetDuration&&serverControl[phb]<minPartDuration&&(this.trigger("warn",{message:"".concat(tag," clamping PART-HOLD-BACK (").concat(serverControl[phb],") to partTargetDuration * 2 (").concat(minPartDuration,").")}),serverControl[phb]=minPartDuration)};class Parser extends Stream{constructor(){super(),this.lineStream=new LineStream,this.parseStream=new ParseStream,this.lineStream.pipe(this.parseStream),this.lastProgramDateTime=null;const self=this,uris=[];let currentMap,key,currentUri={},hasParts=!1;const noop=function(){},defaultM
ediaGroups={AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}};let currentTimeline=0;this.manifest={allowCache:!0,discontinuityStarts:[],dateRanges:[],segments:[]};let lastByterangeEnd=0,lastPartByterangeEnd=0;const dateRangeTags={};this.on("end",(()=>{currentUri.uri||!currentUri.parts&&!currentUri.preloadHints||(!currentUri.map&¤tMap&&(currentUri.map=currentMap),!currentUri.key&&key&&(currentUri.key=key),currentUri.timeline||"number"!=typeof currentTimeline||(currentUri.timeline=currentTimeline),this.manifest.preloadSegment=currentUri)})),this.parseStream.on("data",(function(entry){let mediaGroup,rendition;({tag(){({version(){entry.version&&(this.manifest.version=entry.version)},"allow-cache"(){this.manifest.allowCache=entry.allowed,"allowed"in entry||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange(){const byterange={};"length"in entry&&(currentUri.byterange=byterange,byterange.length=entry.length,"offset"in entry||(entry.offset=lastByterangeEnd
)),"offset"in entry&&(currentUri.byterange=byterange,byterange.offset=entry.offset),lastByterangeEnd=byterange.offset+byterange.length},endlist(){this.manifest.endList=!0},inf(){"mediaSequence"in this.manifest||(this.manifest.mediaSequence=0,this.trigger("info",{message:"defaulting media sequence to zero"})),"discontinuitySequence"in this.manifest||(this.manifest.discontinuitySequence=0,this.trigger("info",{message:"defaulting discontinuity sequence to zero"})),entry.title&&(currentUri.title=entry.title),entry.duration>0&&(currentUri.duration=entry.duration),0===entry.duration&&(currentUri.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=uris},key(){if(entry.attributes)if("NONE"!==entry.attributes.METHOD)if(entry.attributes.URI){if("com.apple.streamingkeydelivery"===entry.attributes.KEYFORMAT)return this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:entry
.attributes});if("com.microsoft.playready"===entry.attributes.KEYFORMAT)return this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.microsoft.playready"]={uri:entry.attributes.URI});if("urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"===entry.attributes.KEYFORMAT){return-1===["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(entry.attributes.METHOD)?void this.trigger("warn",{message:"invalid key method provided for Widevine"}):("SAMPLE-AES-CENC"===entry.attributes.METHOD&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),"data:text/plain;base64,"!==entry.attributes.URI.substring(0,23)?void this.trigger("warn",{message:"invalid key URI provided for Widevine"}):entry.attributes.KEYID&&"0x"===entry.attributes.KEYID.substring(0,2)?(this.manifest.contentProtection=this.manifest.contentProtection||{},void(this.manifest.contentProtection["com.widevine.alpha"]={attributes:{schemeIdUri:entry.attributes.KEYFOR
MAT,keyId:entry.attributes.KEYID.substring(2)},pssh:decodeB64ToUint8Array$1(entry.attributes.URI.split(",")[1])})):void this.trigger("warn",{message:"invalid key ID provided for Widevine"}))}entry.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),key={method:entry.attributes.METHOD||"AES-128",uri:entry.attributes.URI},void 0!==entry.attributes.IV&&(key.iv=entry.attributes.IV)}else this.trigger("warn",{message:"ignoring key declaration without URI"});else key=null;else this.trigger("warn",{message:"ignoring key declaration without attribute list"})},"media-sequence"(){isFinite(entry.number)?this.manifest.mediaSequence=entry.number:this.trigger("warn",{message:"ignoring invalid media sequence: "+entry.number})},"discontinuity-sequence"(){isFinite(entry.number)?(this.manifest.discontinuitySequence=entry.number,currentTimeline=entry.number):this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+entry.number})},"playlist-type"(){/VOD|EVENT/.test(entry.playlistT
ype)?this.manifest.playlistType=entry.playlistType:this.trigger("warn",{message:"ignoring unknown playlist type: "+entry.playlist})},map(){currentMap={},entry.uri&&(currentMap.uri=entry.uri),entry.byterange&&(currentMap.byterange=entry.byterange),key&&(currentMap.key=key)},"stream-inf"(){this.manifest.playlists=uris,this.manifest.mediaGroups=this.manifest.mediaGroups||defaultMediaGroups,entry.attributes?(currentUri.attributes||(currentUri.attributes={}),_extends$1(currentUri.attributes,entry.attributes)):this.trigger("warn",{message:"ignoring empty stream-inf attributes"})},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||defaultMediaGroups,!(entry.attributes&&entry.attributes.TYPE&&entry.attributes["GROUP-ID"]&&entry.attributes.NAME))return void this.trigger("warn",{message:"ignoring incomplete or missing media group"});const mediaGroupType=this.manifest.mediaGroups[entry.attributes.TYPE];mediaGroupType[entry.attributes["GROUP-ID"]]=mediaGroupType[entry.attributes["GROUP-ID"]]||{},mediaGroup=
mediaGroupType[entry.attributes["GROUP-ID"]],rendition={default:/yes/i.test(entry.attributes.DEFAULT)},rendition.default?rendition.autoselect=!0:rendition.autoselect=/yes/i.test(entry.attributes.AUTOSELECT),entry.attributes.LANGUAGE&&(rendition.language=entry.attributes.LANGUAGE),entry.attributes.URI&&(rendition.uri=entry.attributes.URI),entry.attributes["INSTREAM-ID"]&&(rendition.instreamId=entry.attributes["INSTREAM-ID"]),entry.attributes.CHARACTERISTICS&&(rendition.characteristics=entry.attributes.CHARACTERISTICS),entry.attributes.FORCED&&(rendition.forced=/yes/i.test(entry.attributes.FORCED)),mediaGroup[entry.attributes.NAME]=rendition},discontinuity(){currentTimeline+=1,currentUri.discontinuity=!0,this.manifest.discontinuityStarts.push(uris.length)},"program-date-time"(){void 0===this.manifest.dateTimeString&&(this.manifest.dateTimeString=entry.dateTimeString,this.manifest.dateTimeObject=entry.dateTimeObject),currentUri.dateTimeString=entry.dateTimeString,currentUri.dateTimeObject=entry.dateTimeObject;c
onst{lastProgramDateTime:lastProgramDateTime}=this;this.lastProgramDateTime=new Date(entry.dateTimeString).getTime(),null===lastProgramDateTime&&this.manifest.segments.reduceRight(((programDateTime,segment)=>(segment.programDateTime=programDateTime-1e3*segment.duration,segment.programDateTime)),this.lastProgramDateTime)},targetduration(){!isFinite(entry.duration)||entry.duration<0?this.trigger("warn",{message:"ignoring invalid target duration: "+entry.duration}):(this.manifest.targetDuration=entry.duration,setHoldBack.call(this,this.manifest))},start(){entry.attributes&&!isNaN(entry.attributes["TIME-OFFSET"])?this.manifest.start={timeOffset:entry.attributes["TIME-OFFSET"],precise:entry.attributes.PRECISE}:this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"})},"cue-out"(){currentUri.cueOut=entry.data},"cue-out-cont"(){currentUri.cueOutCont=entry.data},"cue-in"(){currentUri.cueIn=entry.data},skip(){this.manifest.skip=camelCaseKeys(entry.attributes),this.warnOnMissingAtt
ributes_("#EXT-X-SKIP",entry.attributes,["SKIPPED-SEGMENTS"])},part(){hasParts=!0;const segmentIndex=this.manifest.segments.length,part=camelCaseKeys(entry.attributes);currentUri.parts=currentUri.parts||[],currentUri.parts.push(part),part.byterange&&(part.byterange.hasOwnProperty("offset")||(part.byterange.offset=lastPartByterangeEnd),lastPartByterangeEnd=part.byterange.offset+part.byterange.length);const partIndex=currentUri.parts.length-1;this.warnOnMissingAttributes_("#EXT-X-PART #".concat(partIndex," for segment #").concat(segmentIndex),entry.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach(((r,i)=>{r.hasOwnProperty("lastPart")||this.trigger("warn",{message:"#EXT-X-RENDITION-REPORT #".concat(i," lacks required attribute(s): LAST-PART")})}))},"server-control"(){const attrs=this.manifest.serverControl=camelCaseKeys(entry.attributes);attrs.hasOwnProperty("canBlockReload")||(attrs.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaul
ting CAN-BLOCK-RELOAD to false"})),setHoldBack.call(this,this.manifest),attrs.canSkipDateranges&&!attrs.hasOwnProperty("canSkipUntil")&&this.trigger("warn",{message:"#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set"})},"preload-hint"(){const segmentIndex=this.manifest.segments.length,hint=camelCaseKeys(entry.attributes),isPart=hint.type&&"PART"===hint.type;currentUri.preloadHints=currentUri.preloadHints||[],currentUri.preloadHints.push(hint),hint.byterange&&(hint.byterange.hasOwnProperty("offset")||(hint.byterange.offset=isPart?lastPartByterangeEnd:0,isPart&&(lastPartByterangeEnd=hint.byterange.offset+hint.byterange.length)));const index=currentUri.preloadHints.length-1;if(this.warnOnMissingAttributes_("#EXT-X-PRELOAD-HINT #".concat(index," for segment #").concat(segmentIndex),entry.attributes,["TYPE","URI"]),hint.type)for(let i=0;i<currentUri.preloadHints.length-1;i++){const otherHint=currentUri.preloadHints[i];otherHint.type&&(otherHint.type===
hint.type&&this.trigger("warn",{message:"#EXT-X-PRELOAD-HINT #".concat(index," for segment #").concat(segmentIndex," has the same TYPE ").concat(hint.type," as preload hint #").concat(i)}))}},"rendition-report"(){const report=camelCaseKeys(entry.attributes);this.manifest.renditionReports=this.manifest.renditionReports||[],this.manifest.renditionReports.push(report);const index=this.manifest.renditionReports.length-1,required=["LAST-MSN","URI"];hasParts&&required.push("LAST-PART"),this.warnOnMissingAttributes_("#EXT-X-RENDITION-REPORT #".concat(index),entry.attributes,required)},"part-inf"(){this.manifest.partInf=camelCaseKeys(entry.attributes),this.warnOnMissingAttributes_("#EXT-X-PART-INF",entry.attributes,["PART-TARGET"]),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),setHoldBack.call(this,this.manifest)},daterange(){this.manifest.dateRanges.push(camelCaseKeys(entry.attributes));const index=this.manifest.dateRanges.length-1;this.warnOnMissingAttributes
_("#EXT-X-DATERANGE #".concat(index),entry.attributes,["ID","START-DATE"]);const dateRange=this.manifest.dateRanges[index];dateRange.endDate&&dateRange.startDate&&new Date(dateRange.endDate)<new Date(dateRange.startDate)&&this.trigger("warn",{message:"EXT-X-DATERANGE END-DATE must be equal to or later than the value of the START-DATE"}),dateRange.duration&&dateRange.duration<0&&this.trigger("warn",{message:"EXT-X-DATERANGE DURATION must not be negative"}),dateRange.plannedDuration&&dateRange.plannedDuration<0&&this.trigger("warn",{message:"EXT-X-DATERANGE PLANNED-DURATION must not be negative"});const endOnNextYes=!!dateRange.endOnNext;if(endOnNextYes&&!dateRange.class&&this.trigger("warn",{message:"EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must have a CLASS attribute"}),endOnNextYes&&(dateRange.duration||dateRange.endDate)&&this.trigger("warn",{message:"EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must not contain DURATION or END-DATE attributes"}),dateRange.duration&&dateRange.endDate){const n
ewDateInSeconds=dateRange.startDate.getTime()+1e3*dateRange.duration;this.manifest.dateRanges[index].endDate=new Date(newDateInSeconds)}if(dateRangeTags[dateRange.id]){for(const attribute in dateRangeTags[dateRange.id])if(dateRange[attribute]&&JSON.stringify(dateRangeTags[dateRange.id][attribute])!==JSON.stringify(dateRange[attribute])){this.trigger("warn",{message:"EXT-X-DATERANGE tags with the same ID in a playlist must have the same attributes values"});break}const dateRangeWithSameId=this.manifest.dateRanges.findIndex((dateRangeToFind=>dateRangeToFind.id===dateRange.id));this.manifest.dateRanges[dateRangeWithSameId]=_extends$1(this.manifest.dateRanges[dateRangeWithSameId],dateRange),dateRangeTags[dateRange.id]=_extends$1(dateRangeTags[dateRange.id],dateRange),this.manifest.dateRanges.pop()}else dateRangeTags[dateRange.id]=dateRange},"independent-segments"(){this.manifest.independentSegments=!0},"content-steering"(){this.manifest.contentSteering=camelCaseKeys(entry.attributes),this.warnOnMissingAttributes
_("#EXT-X-CONTENT-STEERING",entry.attributes,["SERVER-URI"])}}[entry.tagType]||noop).call(self)},uri(){currentUri.uri=entry.uri,uris.push(currentUri),this.manifest.targetDuration&&!("duration"in currentUri)&&(this.trigger("warn",{message:"defaulting segment duration to the target duration"}),currentUri.duration=this.manifest.targetDuration),key&&(currentUri.key=key),currentUri.timeline=currentTimeline,currentMap&&(currentUri.map=currentMap),lastPartByterangeEnd=0,null!==this.lastProgramDateTime&&(currentUri.programDateTime=this.lastProgramDateTime,this.lastProgramDateTime+=1e3*currentUri.duration),currentUri={}},comment(){},custom(){entry.segment?(currentUri.custom=currentUri.custom||{},currentUri.custom[entry.customType]=entry.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[entry.customType]=entry.data)}})[entry.type].call(self)}))}warnOnMissingAttributes_(identifier,attributes,required){const missing=[];required.forEach((function(key){attributes.hasOwnProperty(key)||missing.push(k
ey)})),missing.length&&this.trigger("warn",{message:"".concat(identifier," lacks required attribute(s): ").concat(missing.join(", "))})}push(chunk){this.lineStream.push(chunk)}end(){this.lineStream.push("\n"),this.manifest.dateRanges.length&&null===this.lastProgramDateTime&&this.trigger("warn",{message:"A playlist with EXT-X-DATERANGE tag must contain atleast one EXT-X-PROGRAM-DATE-TIME tag"}),this.lastProgramDateTime=null,this.trigger("end")}addParser(options){this.parseStream.addParser(options)}addTagMapper(options){this.parseStream.addTagMapper(options)}}var a,b,regexs={mp4:/^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,webm:/^(vp0?[89]|av0?1|opus|vorbis)/,ogg:/^(vp0?[89]|theora|flac|opus|vorbis)/,video:/^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,audio:/^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,text:/^(stpp.ttml.im1t)/,muxerVideo:/^(avc0?1)/,muxerAudio:/^(mp4a)/,muxerText:/a^/},mediaTypes=["video","audio","text"],upperMediaTypes=["Video","Audio","Text"],trans
lateLegacyCodec=function(codec){return codec?codec.replace(/avc1\.(\d+)\.(\d+)/i,(function(orig,profile,avcLevel){return"avc1."+("00"+Number(profile).toString(16)).slice(-2)+"00"+("00"+Number(avcLevel).toString(16)).slice(-2)})):codec},parseCodecs=function(codecString){void 0===codecString&&(codecString="");var codecs=codecString.split(","),result=[];return codecs.forEach((function(codec){var codecType;codec=codec.trim(),mediaTypes.forEach((function(name){var match=regexs[name].exec(codec.toLowerCase());if(match&&!(match.length<=1)){codecType=name;var type=codec.substring(0,match[1].length),details=codec.replace(type,"");result.push({type:type,details:details,mediaType:name})}})),codecType||result.push({type:codec,details:"",mediaType:"unknown"})})),result},isAudioCodec=function(codec){return void 0===codec&&(codec=""),regexs.audio.test(codec.trim().toLowerCase())},getMimeForCodec=function(codecString){if(codecString&&"string"==typeof codecString){var codec,codecs=codecString.toLowerCase().split(",").map((fu
nction(c){return translateLegacyCodec(c.trim())})),type="video";1===codecs.length&&isAudioCodec(codecs[0])?type="audio":1===codecs.length&&(void 0===(codec=codecs[0])&&(codec=""),regexs.text.test(codec.trim().toLowerCase()))&&(type="application");var container="mp4";return codecs.every((function(c){return regexs.mp4.test(c)}))?container="mp4":codecs.every((function(c){return regexs.webm.test(c)}))?container="webm":codecs.every((function(c){return regexs.ogg.test(c)}))&&(container="ogg"),type+"/"+container+';codecs="'+codecString+'"'}},browserSupportsCodec=function(codecString){return void 0===codecString&&(codecString=""),window.MediaSource&&window.MediaSource.isTypeSupported&&window.MediaSource.isTypeSupported(getMimeForCodec(codecString))||!1},muxerSupportsCodec=function(codecString){return void 0===codecString&&(codecString=""),codecString.toLowerCase().split(",").every((function(codec){codec=codec.trim();for(var i=0;i<upperMediaTypes.length;i++){if(regexs["muxer"+upperMediaTypes[i]].test(codec))return!0}
return!1}))},MPEGURL_REGEX=/^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i,DASH_REGEX=/^application\/dash\+xml/i,simpleTypeFromSourceType=function(type){return MPEGURL_REGEX.test(type)?"hls":DASH_REGEX.test(type)?"dash":"application/vnd.videojs.vhs+json"===type?"vhs-json":null},isArrayBufferView=function(obj){return"function"===ArrayBuffer.isView?ArrayBuffer.isView(obj):obj&&obj.buffer instanceof ArrayBuffer},toUint8=function(bytes){return bytes instanceof Uint8Array?bytes:(Array.isArray(bytes)||isArrayBufferView(bytes)||bytes instanceof ArrayBuffer||(bytes="number"!=typeof bytes||"number"==typeof bytes&&bytes!=bytes?0:[bytes]),new Uint8Array(bytes&&bytes.buffer||bytes,bytes&&bytes.byteOffset||0,bytes&&bytes.byteLength||0))},BigInt=window.BigInt||Number,BYTE_TABLE=[BigInt("0x1"),BigInt("0x100"),BigInt("0x10000"),BigInt("0x1000000"),BigInt("0x100000000"),BigInt("0x10000000000"),BigInt("0x1000000000000"),BigInt("0x100000000000000"),BigInt("0x10000000000000000")];a=new Uint16Array([65484]),255===(b=new
Uint8Array(a.buffer,a.byteOffset,a.byteLength))[0]||b[0];var bytesToNumber=function(bytes,_temp){var _ref=void 0===_temp?{}:_temp,_ref$signed=_ref.signed,signed=void 0!==_ref$signed&&_ref$signed,_ref$le=_ref.le,le=void 0!==_ref$le&&_ref$le;bytes=toUint8(bytes);var fn=le?"reduce":"reduceRight",number=(bytes[fn]?bytes[fn]:Array.prototype[fn]).call(bytes,(function(total,byte,i){var exponent=le?i:Math.abs(i+1-bytes.length);return total+BigInt(byte)*BYTE_TABLE[exponent]}),BigInt(0));if(signed){var max=BYTE_TABLE[bytes.length]/BigInt(2)-BigInt(1);(number=BigInt(number))>max&&(number-=max,number-=max,number-=BigInt(2))}return Number(number)},numberToBytes=function(number,_temp2){var _ref2$le=(void 0===_temp2?{}:_temp2).le,le=void 0!==_ref2$le&&_ref2$le;("bigint"!=typeof number&&"number"!=typeof number||"number"==typeof number&&number!=number)&&(number=0);for(var byteCount=function(x){return Math.ceil(function(x){return x.toString(2).length}(x)/8)}(number=BigInt(number)),bytes=new Uint8Array(new ArrayBuffer(byteCou
nt)),i=0;i<byteCount;i++){var byteIndex=le?i:Math.abs(i+1-bytes.length);bytes[byteIndex]=Number(number/BYTE_TABLE[i]&BigInt(255)),number<0&&(bytes[byteIndex]=Math.abs(~bytes[byteIndex]),bytes[byteIndex]-=0===i?1:2)}return bytes},stringToBytes=function(string,stringIsBytes){if("string"!=typeof string&&string&&"function"==typeof string.toString&&(string=string.toString()),"string"!=typeof string)return new Uint8Array;stringIsBytes||(string=unescape(encodeURIComponent(string)));for(var view=new Uint8Array(string.length),i=0;i<string.length;i++)view[i]=string.charCodeAt(i);return view},bytesMatch=function(a,b,_temp3){var _ref3=void 0===_temp3?{}:_temp3,_ref3$offset=_ref3.offset,offset=void 0===_ref3$offset?0:_ref3$offset,_ref3$mask=_ref3.mask,mask=void 0===_ref3$mask?[]:_ref3$mask;a=toUint8(a);var fn=(b=toUint8(b)).every?b.every:Array.prototype.every;return b.length&&a.length-offset>=b.length&&fn.call(b,(function(bByte,i){return bByte===(mask[i]?mask[i]&a[offset+i]:a[offset+i])}))};function decodeB64ToUint8Array
(b64Text){for(var s,decodedString=(s=b64Text,window.atob?window.atob(s):Buffer.from(s,"base64").toString("binary")),array=new Uint8Array(decodedString.length),i=0;i<decodedString.length;i++)array[i]=decodedString.charCodeAt(i);return array}function freeze(object,oc){return void 0===oc&&(oc=Object),oc&&"function"==typeof oc.freeze?oc.freeze(object):object}var MIME_TYPE=freeze({HTML:"text/html",isHTML:function(value){return value===MIME_TYPE.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),NAMESPACE$3=freeze({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(uri){return uri===NAMESPACE$3.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),conventions={assign:function(target,source){if(null===target||"object"!=typeof target)throw new TypeError("target is not an object");for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]
=source[key]);return target},find:function(list,predicate,ac){if(void 0===ac&&(ac=Array.prototype),list&&"function"==typeof ac.find)return ac.find.call(list,predicate);for(var i=0;i<list.length;i++)if(Object.prototype.hasOwnProperty.call(list,i)){var item=list[i];if(predicate.call(void 0,item,i,list))return item}},freeze:freeze,MIME_TYPE:MIME_TYPE,NAMESPACE:NAMESPACE$3},find=conventions.find,NAMESPACE$2=conventions.NAMESPACE;function notEmptyString(input){return""!==input}function orderedSetReducer(current,element){return current.hasOwnProperty(element)||(current[element]=!0),current}function toOrderedSet(input){if(!input)return[];var list=function(input){return input?input.split(/[\t\n\f\r ]+/).filter(notEmptyString):[]}(input);return Object.keys(list.reduce(orderedSetReducer,{}))}function copy(src,dest){for(var p in src)Object.prototype.hasOwnProperty.call(src,p)&&(dest[p]=src[p])}function _extends(Class,Super){var pt=Class.prototype;if(!(pt instanceof Super)){function t(){}t.prototype=Super.prototype,copy
(pt,t=new t),Class.prototype=pt=t}pt.constructor!=Class&&("function"!=typeof Class&&console.error("unknown Class:"+Class),pt.constructor=Class)}var NodeType={},ELEMENT_NODE=NodeType.ELEMENT_NODE=1,ATTRIBUTE_NODE=NodeType.ATTRIBUTE_NODE=2,TEXT_NODE=NodeType.TEXT_NODE=3,CDATA_SECTION_NODE=NodeType.CDATA_SECTION_NODE=4,ENTITY_REFERENCE_NODE=NodeType.ENTITY_REFERENCE_NODE=5,ENTITY_NODE=NodeType.ENTITY_NODE=6,PROCESSING_INSTRUCTION_NODE=NodeType.PROCESSING_INSTRUCTION_NODE=7,COMMENT_NODE=NodeType.COMMENT_NODE=8,DOCUMENT_NODE=NodeType.DOCUMENT_NODE=9,DOCUMENT_TYPE_NODE=NodeType.DOCUMENT_TYPE_NODE=10,DOCUMENT_FRAGMENT_NODE=NodeType.DOCUMENT_FRAGMENT_NODE=11,NOTATION_NODE=NodeType.NOTATION_NODE=12,ExceptionCode={},ExceptionMessage={};ExceptionCode.INDEX_SIZE_ERR=(ExceptionMessage[1]="Index size error",1),ExceptionCode.DOMSTRING_SIZE_ERR=(ExceptionMessage[2]="DOMString size error",2);var HIERARCHY_REQUEST_ERR=ExceptionCode.HIERARCHY_REQUEST_ERR=(ExceptionMessage[3]="Hierarchy request error",3);ExceptionCode.WRONG_DOC
UMENT_ERR=(ExceptionMessage[4]="Wrong document",4),ExceptionCode.INVALID_CHARACTER_ERR=(ExceptionMessage[5]="Invalid character",5),ExceptionCode.NO_DATA_ALLOWED_ERR=(ExceptionMessage[6]="No data allowed",6),ExceptionCode.NO_MODIFICATION_ALLOWED_ERR=(ExceptionMessage[7]="No modification allowed",7);var NOT_FOUND_ERR=ExceptionCode.NOT_FOUND_ERR=(ExceptionMessage[8]="Not found",8);ExceptionCode.NOT_SUPPORTED_ERR=(ExceptionMessage[9]="Not supported",9);var INUSE_ATTRIBUTE_ERR=ExceptionCode.INUSE_ATTRIBUTE_ERR=(ExceptionMessage[10]="Attribute in use",10);function DOMException(code,message){if(message instanceof Error)var error=message;else error=this,Error.call(this,ExceptionMessage[code]),this.message=ExceptionMessage[code],Error.captureStackTrace&&Error.captureStackTrace(this,DOMException);return error.code=code,message&&(this.message=this.message+": "+message),error}function NodeList(){}function LiveNodeList(node,refresh){this._node=node,this._refresh=refresh,_updateLiveList(this)}function _updateLiveList(list
){var inc=list._node._inc||list._node.ownerDocument._inc;if(list._inc!==inc){var ls=list._refresh(list._node);if(__set__(list,"length",ls.length),!list.$$length||ls.length<list.$$length)for(var i=ls.length;i in list;i++)Object.prototype.hasOwnProperty.call(list,i)&&delete list[i];copy(ls,list),list._inc=inc}}function NamedNodeMap(){}function _findNodeIndex(list,node){for(var i=list.length;i--;)if(list[i]===node)return i}function _addNamedNode(el,list,newAttr,oldAttr){if(oldAttr?list[_findNodeIndex(list,oldAttr)]=newAttr:list[list.length++]=newAttr,el){newAttr.ownerElement=el;var doc=el.ownerDocument;doc&&(oldAttr&&_onRemoveAttribute(doc,el,oldAttr),function(doc,el,newAttr){doc&&doc._inc++,newAttr.namespaceURI===NAMESPACE$2.XMLNS&&(el._nsMap[newAttr.prefix?newAttr.localName:""]=newAttr.value)}(doc,el,newAttr))}}function _removeNamedNode(el,list,attr){var i=_findNodeIndex(list,attr);if(!(i>=0))throw new DOMException(NOT_FOUND_ERR,new Error(el.tagName+"@"+attr));for(var lastIndex=list.length-1;i<lastIndex;)list
[i]=list[++i];if(list.length=lastIndex,el){var doc=el.ownerDocument;doc&&(_onRemoveAttribute(doc,el,attr),attr.ownerElement=null)}}function DOMImplementation$1(){}function Node(){}function _xmlEncoder(c){return("<"==c?"<":">"==c&&">")||"&"==c&&"&"||'"'==c&&"""||"&#"+c.charCodeAt()+";"}function _visitNode(node,callback){if(callback(node))return!0;if(node=node.firstChild)do{if(_visitNode(node,callback))return!0}while(node=node.nextSibling)}function Document(){this.ownerDocument=this}function _onRemoveAttribute(doc,el,newAttr,remove){doc&&doc._inc++,newAttr.namespaceURI===NAMESPACE$2.XMLNS&&delete el._nsMap[newAttr.prefix?newAttr.localName:""]}function _onUpdateChild(doc,el,newChild){if(doc&&doc._inc){doc._inc++;var cs=el.childNodes;if(newChild)cs[cs.length++]=newChild;else{for(var child=el.firstChild,i=0;child;)cs[i++]=child,child=child.nextSibling;cs.length=i,delete cs[cs.length]}}}function _removeChild(parentNode,child){var previous=child.previousSibling,next=child.nextSibling;return previous?
previous.nextSibling=next:parentNode.firstChild=next,next?next.previousSibling=previous:parentNode.lastChild=previous,child.parentNode=null,child.previousSibling=null,child.nextSibling=null,_onUpdateChild(parentNode.ownerDocument,parentNode),child}function isDocTypeNode(node){return node&&node.nodeType===Node.DOCUMENT_TYPE_NODE}function isElementNode(node){return node&&node.nodeType===Node.ELEMENT_NODE}function isTextNode(node){return node&&node.nodeType===Node.TEXT_NODE}function isElementInsertionPossible(doc,child){var parentChildNodes=doc.childNodes||[];if(find(parentChildNodes,isElementNode)||isDocTypeNode(child))return!1;var docTypeNode=find(parentChildNodes,isDocTypeNode);return!(child&&docTypeNode&&parentChildNodes.indexOf(docTypeNode)>parentChildNodes.indexOf(child))}function isElementReplacementPossible(doc,child){var parentChildNodes=doc.childNodes||[];if(find(parentChildNodes,(function(node){return isElementNode(node)&&node!==child})))return!1;var docTypeNode=find(parentChildNodes,isDocTypeNode);r
eturn!(child&&docTypeNode&&parentChildNodes.indexOf(docTypeNode)>parentChildNodes.indexOf(child))}function assertPreInsertionValidity1to5(parent,node,child){if(!function(node){return node&&(node.nodeType===Node.DOCUMENT_NODE||node.nodeType===Node.DOCUMENT_FRAGMENT_NODE||node.nodeType===Node.ELEMENT_NODE)}(parent))throw new DOMException(HIERARCHY_REQUEST_ERR,"Unexpected parent node type "+parent.nodeType);if(child&&child.parentNode!==parent)throw new DOMException(NOT_FOUND_ERR,"child not in parent");if(!function(node){return node&&(isElementNode(node)||isTextNode(node)||isDocTypeNode(node)||node.nodeType===Node.DOCUMENT_FRAGMENT_NODE||node.nodeType===Node.COMMENT_NODE||node.nodeType===Node.PROCESSING_INSTRUCTION_NODE)}(node)||isDocTypeNode(node)&&parent.nodeType!==Node.DOCUMENT_NODE)throw new DOMException(HIERARCHY_REQUEST_ERR,"Unexpected node type "+node.nodeType+" for parent node type "+parent.nodeType)}function assertPreInsertionValidityInDocument(parent,node,child){var parentChildNodes=parent.childNodes||
[],nodeChildNodes=node.childNodes||[];if(node.nodeType===Node.DOCUMENT_FRAGMENT_NODE){var nodeChildElements=nodeChildNodes.filter(isElementNode);if(nodeChildElements.length>1||find(nodeChildNodes,isTextNode))throw new DOMException(HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(1===nodeChildElements.length&&!isElementInsertionPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(isElementNode(node)&&!isElementInsertionPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(isDocTypeNode(node)){if(find(parentChildNodes,isDocTypeNode))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var parentElementChild=find(parentChildNodes,isElementNode);if(child&&parentChildNodes.indexOf(parentElementChild)<parentChildNodes.indexOf(child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Doctype can only be inserted before an element"
);if(!child&&parentElementChild)throw new DOMException(HIERARCHY_REQUEST_ERR,"Doctype can not be appended since element is present")}}function assertPreReplacementValidityInDocument(parent,node,child){var parentChildNodes=parent.childNodes||[],nodeChildNodes=node.childNodes||[];if(node.nodeType===Node.DOCUMENT_FRAGMENT_NODE){var nodeChildElements=nodeChildNodes.filter(isElementNode);if(nodeChildElements.length>1||find(nodeChildNodes,isTextNode))throw new DOMException(HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(1===nodeChildElements.length&&!isElementReplacementPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(isElementNode(node)&&!isElementReplacementPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(isDocTypeNode(node)){function hasDoctypeChildThatIsNotChild(node){return isDocTypeNode(node)&&node!==child}if(find(parentChildNodes,
hasDoctypeChildThatIsNotChild))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var parentElementChild=find(parentChildNodes,isElementNode);if(child&&parentChildNodes.indexOf(parentElementChild)<parentChildNodes.indexOf(child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Doctype can only be inserted before an element")}}function _insertBefore(parent,node,child,_inDocumentAssertion){assertPreInsertionValidity1to5(parent,node,child),parent.nodeType===Node.DOCUMENT_NODE&&(_inDocumentAssertion||assertPreInsertionValidityInDocument)(parent,node,child);var cp=node.parentNode;if(cp&&cp.removeChild(node),node.nodeType===DOCUMENT_FRAGMENT_NODE){var newFirst=node.firstChild;if(null==newFirst)return node;var newLast=node.lastChild}else newFirst=newLast=node;var pre=child?child.previousSibling:parent.lastChild;newFirst.previousSibling=pre,newLast.nextSibling=child,pre?pre.nextSibling=newFirst:parent.firstChild=newFirst,null==child?parent.lastChild=newLast:child.previousSibling=newLast;do{newF
irst.parentNode=parent}while(newFirst!==newLast&&(newFirst=newFirst.nextSibling));return _onUpdateChild(parent.ownerDocument||parent,parent),node.nodeType==DOCUMENT_FRAGMENT_NODE&&(node.firstChild=node.lastChild=null),node}function Element(){this._nsMap={}}function Attr(){}function CharacterData(){}function Text(){}function Comment(){}function CDATASection(){}function DocumentType(){}function Notation(){}function Entity(){}function EntityReference(){}function DocumentFragment(){}function ProcessingInstruction(){}function XMLSerializer(){}function nodeSerializeToString(isHtml,nodeFilter){var buf=[],refNode=9==this.nodeType&&this.documentElement||this,prefix=refNode.prefix,uri=refNode.namespaceURI;if(uri&&null==prefix&&null==(prefix=refNode.lookupPrefix(uri)))var visibleNamespaces=[{namespace:uri,prefix:null}];return serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces),buf.join("")}function needNamespaceDefine(node,isHTML,visibleNamespaces){var prefix=node.prefix||"",uri=node.namespaceURI;if(!uri)re
turn!1;if("xml"===prefix&&uri===NAMESPACE$2.XML||uri===NAMESPACE$2.XMLNS)return!1;for(var i=visibleNamespaces.length;i--;){var ns=visibleNamespaces[i];if(ns.prefix===prefix)return ns.namespace!==uri}return!0}function addSerializedAttribute(buf,qualifiedName,value){buf.push(" ",qualifiedName,'="',value.replace(/[<>&"\t\n\r]/g,_xmlEncoder),'"')}function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){if(visibleNamespaces||(visibleNamespaces=[]),nodeFilter){if(!(node=nodeFilter(node)))return;if("string"==typeof node)return void buf.push(node)}switch(node.nodeType){case ELEMENT_NODE:var attrs=node.attributes,len=attrs.length,child=node.firstChild,nodeName=node.tagName,prefixedNodeName=nodeName;if(!(isHTML=NAMESPACE$2.isHTML(node.namespaceURI)||isHTML)&&!node.prefix&&node.namespaceURI){for(var defaultNS,ai=0;ai<attrs.length;ai++)if("xmlns"===attrs.item(ai).name){defaultNS=attrs.item(ai).value;break}if(!defaultNS)for(var nsi=visibleNamespaces.length-1;nsi>=0;nsi--){if(""===(namespace=visibleNamespa
ces[nsi]).prefix&&namespace.namespace===node.namespaceURI){defaultNS=namespace.namespace;break}}if(defaultNS!==node.namespaceURI)for(nsi=visibleNamespaces.length-1;nsi>=0;nsi--){var namespace;if((namespace=visibleNamespaces[nsi]).namespace===node.namespaceURI){namespace.prefix&&(prefixedNodeName=namespace.prefix+":"+nodeName);break}}}buf.push("<",prefixedNodeName);for(var i=0;i<len;i++){"xmlns"==(attr=attrs.item(i)).prefix?visibleNamespaces.push({prefix:attr.localName,namespace:attr.value}):"xmlns"==attr.nodeName&&visibleNamespaces.push({prefix:"",namespace:attr.value})}for(i=0;i<len;i++){var attr,prefix,uri;if(needNamespaceDefine(attr=attrs.item(i),0,visibleNamespaces))addSerializedAttribute(buf,(prefix=attr.prefix||"")?"xmlns:"+prefix:"xmlns",uri=attr.namespaceURI),visibleNamespaces.push({prefix:prefix,namespace:uri});serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces)}if(nodeName===prefixedNodeName&&needNamespaceDefine(node,0,visibleNamespaces))addSerializedAttribute(buf,(prefix=node.prefix||"
")?"xmlns:"+prefix:"xmlns",uri=node.namespaceURI),visibleNamespaces.push({prefix:prefix,namespace:uri});if(child||isHTML&&!/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){if(buf.push(">"),isHTML&&/^script$/i.test(nodeName))for(;child;)child.data?buf.push(child.data):serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces.slice()),child=child.nextSibling;else for(;child;)serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces.slice()),child=child.nextSibling;buf.push("</",prefixedNodeName,">")}else buf.push("/>");return;case DOCUMENT_NODE:case DOCUMENT_FRAGMENT_NODE:for(child=node.firstChild;child;)serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces.slice()),child=child.nextSibling;return;case ATTRIBUTE_NODE:return addSerializedAttribute(buf,node.name,node.value);case TEXT_NODE:return buf.push(node.data.replace(/[<&>]/g,_xmlEncoder));case CDATA_SECTION_NODE:return buf.push("<![CDATA[",node.data,"]]>");case COMMENT_NODE:return buf.push("\x3c!--",node.data,"--\x3e");case DOCUMENT_
TYPE_NODE:var pubid=node.publicId,sysid=node.systemId;if(buf.push("<!DOCTYPE ",node.name),pubid)buf.push(" PUBLIC ",pubid),sysid&&"."!=sysid&&buf.push(" ",sysid),buf.push(">");else if(sysid&&"."!=sysid)buf.push(" SYSTEM ",sysid,">");else{var sub=node.internalSubset;sub&&buf.push(" [",sub,"]"),buf.push(">")}return;case PROCESSING_INSTRUCTION_NODE:return buf.push("<?",node.target," ",node.data,"?>");case ENTITY_REFERENCE_NODE:return buf.push("&",node.nodeName,";");default:buf.push("??",node.nodeName)}}function importNode(doc,node,deep){var node2;switch(node.nodeType){case ELEMENT_NODE:(node2=node.cloneNode(!1)).ownerDocument=doc;case DOCUMENT_FRAGMENT_NODE:break;case ATTRIBUTE_NODE:deep=!0}if(node2||(node2=node.cloneNode(!1)),node2.ownerDocument=doc,node2.parentNode=null,deep)for(var child=node.firstChild;child;)node2.appendChild(importNode(doc,child,deep)),child=child.nextSibling;return node2}function cloneNode(doc,node,deep){var node2=new node.constructor;for(var n in node)if(Object.prototype.hasOwnProperty.
call(node,n)){var v=node[n];"object"!=typeof v&&v!=node2[n]&&(node2[n]=v)}switch(node.childNodes&&(node2.childNodes=new NodeList),node2.ownerDocument=doc,node2.nodeType){case ELEMENT_NODE:var attrs=node.attributes,attrs2=node2.attributes=new NamedNodeMap,len=attrs.length;attrs2._ownerElement=node2;for(var i=0;i<len;i++)node2.setAttributeNode(cloneNode(doc,attrs.item(i),!0));break;case ATTRIBUTE_NODE:deep=!0}if(deep)for(var child=node.firstChild;child;)node2.appendChild(cloneNode(doc,child,deep)),child=child.nextSibling;return node2}function __set__(object,key,value){object[key]=value}ExceptionCode.INVALID_STATE_ERR=(ExceptionMessage[11]="Invalid state",11),ExceptionCode.SYNTAX_ERR=(ExceptionMessage[12]="Syntax error",12),ExceptionCode.INVALID_MODIFICATION_ERR=(ExceptionMessage[13]="Invalid modification",13),ExceptionCode.NAMESPACE_ERR=(ExceptionMessage[14]="Invalid namespace",14),ExceptionCode.INVALID_ACCESS_ERR=(ExceptionMessage[15]="Invalid access",15),DOMException.prototype=Error.prototype,copy(ExceptionC
ode,DOMException),NodeList.prototype={length:0,item:function(index){return index>=0&&index<this.length?this[index]:null},toString:function(isHTML,nodeFilter){for(var buf=[],i=0;i<this.length;i++)serializeToString(this[i],buf,isHTML,nodeFilter);return buf.join("")},filter:function(predicate){return Array.prototype.filter.call(this,predicate)},indexOf:function(item){return Array.prototype.indexOf.call(this,item)}},LiveNodeList.prototype.item=function(i){return _updateLiveList(this),this[i]||null},_extends(LiveNodeList,NodeList),NamedNodeMap.prototype={length:0,item:NodeList.prototype.item,getNamedItem:function(key){for(var i=this.length;i--;){var attr=this[i];if(attr.nodeName==key)return attr}},setNamedItem:function(attr){var el=attr.ownerElement;if(el&&el!=this._ownerElement)throw new DOMException(INUSE_ATTRIBUTE_ERR);var oldAttr=this.getNamedItem(attr.nodeName);return _addNamedNode(this._ownerElement,this,attr,oldAttr),oldAttr},setNamedItemNS:function(attr){var oldAttr,el=attr.ownerElement;if(el&&el!=this._o
wnerElement)throw new DOMException(INUSE_ATTRIBUTE_ERR);return oldAttr=this.getNamedItemNS(attr.namespaceURI,attr.localName),_addNamedNode(this._ownerElement,this,attr,oldAttr),oldAttr},removeNamedItem:function(key){var attr=this.getNamedItem(key);return _removeNamedNode(this._ownerElement,this,attr),attr},removeNamedItemNS:function(namespaceURI,localName){var attr=this.getNamedItemNS(namespaceURI,localName);return _removeNamedNode(this._ownerElement,this,attr),attr},getNamedItemNS:function(namespaceURI,localName){for(var i=this.length;i--;){var node=this[i];if(node.localName==localName&&node.namespaceURI==namespaceURI)return node}return null}},DOMImplementation$1.prototype={hasFeature:function(feature,version){return!0},createDocument:function(namespaceURI,qualifiedName,doctype){var doc=new Document;if(doc.implementation=this,doc.childNodes=new NodeList,doc.doctype=doctype||null,doctype&&doc.appendChild(doctype),qualifiedName){var root=doc.createElementNS(namespaceURI,qualifiedName);doc.appendChild(root)}re
turn doc},createDocumentType:function(qualifiedName,publicId,systemId){var node=new DocumentType;return node.name=qualifiedName,node.nodeName=qualifiedName,node.publicId=publicId||"",node.systemId=systemId||"",node}},Node.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(newChild,refChild){return _insertBefore(this,newChild,refChild)},replaceChild:function(newChild,oldChild){_insertBefore(this,newChild,oldChild,assertPreReplacementValidityInDocument),oldChild&&this.removeChild(oldChild)},removeChild:function(oldChild){return _removeChild(this,oldChild)},appendChild:function(newChild){return this.insertBefore(newChild,null)},hasChildNodes:function(){return null!=this.firstChild},cloneNode:function(deep){return cloneNode(this.ownerDocument||this,this,deep)},normalize:function(){for(var child=this.firstChild;child;){var next=child.next
Sibling;next&&next.nodeType==TEXT_NODE&&child.nodeType==TEXT_NODE?(this.removeChild(next),child.appendData(next.data)):(child.normalize(),child=next)}},isSupported:function(feature,version){return this.ownerDocument.implementation.hasFeature(feature,version)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(namespaceURI){for(var el=this;el;){var map=el._nsMap;if(map)for(var n in map)if(Object.prototype.hasOwnProperty.call(map,n)&&map[n]===namespaceURI)return n;el=el.nodeType==ATTRIBUTE_NODE?el.ownerDocument:el.parentNode}return null},lookupNamespaceURI:function(prefix){for(var el=this;el;){var map=el._nsMap;if(map&&Object.prototype.hasOwnProperty.call(map,prefix))return map[prefix];el=el.nodeType==ATTRIBUTE_NODE?el.ownerDocument:el.parentNode}return null},isDefaultNamespace:function(namespaceURI){return null==this.lookupPrefix(namespaceURI)}},copy(NodeType,Node),copy(NodeType,Node.prototype),Document.prototype={nodeName:"#document",nodeType:DOCUMENT_NODE,doctype:null,documentEl
ement:null,_inc:1,insertBefore:function(newChild,refChild){if(newChild.nodeType==DOCUMENT_FRAGMENT_NODE){for(var child=newChild.firstChild;child;){var next=child.nextSibling;this.insertBefore(child,refChild),child=next}return newChild}return _insertBefore(this,newChild,refChild),newChild.ownerDocument=this,null===this.documentElement&&newChild.nodeType===ELEMENT_NODE&&(this.documentElement=newChild),newChild},removeChild:function(oldChild){return this.documentElement==oldChild&&(this.documentElement=null),_removeChild(this,oldChild)},replaceChild:function(newChild,oldChild){_insertBefore(this,newChild,oldChild,assertPreReplacementValidityInDocument),newChild.ownerDocument=this,oldChild&&this.removeChild(oldChild),isElementNode(newChild)&&(this.documentElement=newChild)},importNode:function(importedNode,deep){return importNode(this,importedNode,deep)},getElementById:function(id){var rtv=null;return _visitNode(this.documentElement,(function(node){if(node.nodeType==ELEMENT_NODE&&node.getAttribute("id")==id)retu
rn rtv=node,!0})),rtv},getElementsByClassName:function(classNames){var classNamesSet=toOrderedSet(classNames);return new LiveNodeList(this,(function(base){var ls=[];return classNamesSet.length>0&&_visitNode(base.documentElement,(function(node){if(node!==base&&node.nodeType===ELEMENT_NODE){var nodeClassNames=node.getAttribute("class");if(nodeClassNames){var matches=classNames===nodeClassNames;if(!matches){var nodeClassNamesSet=toOrderedSet(nodeClassNames);matches=classNamesSet.every((list=nodeClassNamesSet,function(element){return list&&-1!==list.indexOf(element)}))}matches&&ls.push(node)}}var list})),ls}))},createElement:function(tagName){var node=new Element;return node.ownerDocument=this,node.nodeName=tagName,node.tagName=tagName,node.localName=tagName,node.childNodes=new NodeList,(node.attributes=new NamedNodeMap)._ownerElement=node,node},createDocumentFragment:function(){var node=new DocumentFragment;return node.ownerDocument=this,node.childNodes=new NodeList,node},createTextNode:function(data){var node=
new Text;return node.ownerDocument=this,node.appendData(data),node},createComment:function(data){var node=new Comment;return node.ownerDocument=this,node.appendData(data),node},createCDATASection:function(data){var node=new CDATASection;return node.ownerDocument=this,node.appendData(data),node},createProcessingInstruction:function(target,data){var node=new ProcessingInstruction;return node.ownerDocument=this,node.tagName=node.nodeName=node.target=target,node.nodeValue=node.data=data,node},createAttribute:function(name){var node=new Attr;return node.ownerDocument=this,node.name=name,node.nodeName=name,node.localName=name,node.specified=!0,node},createEntityReference:function(name){var node=new EntityReference;return node.ownerDocument=this,node.nodeName=name,node},createElementNS:function(namespaceURI,qualifiedName){var node=new Element,pl=qualifiedName.split(":"),attrs=node.attributes=new NamedNodeMap;return node.childNodes=new NodeList,node.ownerDocument=this,node.nodeName=qualifiedName,node.tagName=qualifi
edName,node.namespaceURI=namespaceURI,2==pl.length?(node.prefix=pl[0],node.localName=pl[1]):node.localName=qualifiedName,attrs._ownerElement=node,node},createAttributeNS:function(namespaceURI,qualifiedName){var node=new Attr,pl=qualifiedName.split(":");return node.ownerDocument=this,node.nodeName=qualifiedName,node.name=qualifiedName,node.namespaceURI=namespaceURI,node.specified=!0,2==pl.length?(node.prefix=pl[0],node.localName=pl[1]):node.localName=qualifiedName,node}},_extends(Document,Node),Element.prototype={nodeType:ELEMENT_NODE,hasAttribute:function(name){return null!=this.getAttributeNode(name)},getAttribute:function(name){var attr=this.getAttributeNode(name);return attr&&attr.value||""},getAttributeNode:function(name){return this.attributes.getNamedItem(name)},setAttribute:function(name,value){var attr=this.ownerDocument.createAttribute(name);attr.value=attr.nodeValue=""+value,this.setAttributeNode(attr)},removeAttribute:function(name){var attr=this.getAttributeNode(name);attr&&this.removeAttributeNo
de(attr)},appendChild:function(newChild){return newChild.nodeType===DOCUMENT_FRAGMENT_NODE?this.insertBefore(newChild,null):function(parentNode,newChild){return newChild.parentNode&&newChild.parentNode.removeChild(newChild),newChild.parentNode=parentNode,newChild.previousSibling=parentNode.lastChild,newChild.nextSibling=null,newChild.previousSibling?newChild.previousSibling.nextSibling=newChild:parentNode.firstChild=newChild,parentNode.lastChild=newChild,_onUpdateChild(parentNode.ownerDocument,parentNode,newChild),newChild}(this,newChild)},setAttributeNode:function(newAttr){return this.attributes.setNamedItem(newAttr)},setAttributeNodeNS:function(newAttr){return this.attributes.setNamedItemNS(newAttr)},removeAttributeNode:function(oldAttr){return this.attributes.removeNamedItem(oldAttr.nodeName)},removeAttributeNS:function(namespaceURI,localName){var old=this.getAttributeNodeNS(namespaceURI,localName);old&&this.removeAttributeNode(old)},hasAttributeNS:function(namespaceURI,localName){return null!=this.getAtt
ributeNodeNS(namespaceURI,localName)},getAttributeNS:function(namespaceURI,localName){var attr=this.getAttributeNodeNS(namespaceURI,localName);return attr&&attr.value||""},setAttributeNS:function(namespaceURI,qualifiedName,value){var attr=this.ownerDocument.createAttributeNS(namespaceURI,qualifiedName);attr.value=attr.nodeValue=""+value,this.setAttributeNode(attr)},getAttributeNodeNS:function(namespaceURI,localName){return this.attributes.getNamedItemNS(namespaceURI,localName)},getElementsByTagName:function(tagName){return new LiveNodeList(this,(function(base){var ls=[];return _visitNode(base,(function(node){node===base||node.nodeType!=ELEMENT_NODE||"*"!==tagName&&node.tagName!=tagName||ls.push(node)})),ls}))},getElementsByTagNameNS:function(namespaceURI,localName){return new LiveNodeList(this,(function(base){var ls=[];return _visitNode(base,(function(node){node===base||node.nodeType!==ELEMENT_NODE||"*"!==namespaceURI&&node.namespaceURI!==namespaceURI||"*"!==localName&&node.localName!=localName||ls.push(node
)})),ls}))}},Document.prototype.getElementsByTagName=Element.prototype.getElementsByTagName,Document.prototype.getElementsByTagNameNS=Element.prototype.getElementsByTagNameNS,_extends(Element,Node),Attr.prototype.nodeType=ATTRIBUTE_NODE,_extends(Attr,Node),CharacterData.prototype={data:"",substringData:function(offset,count){return this.data.substring(offset,offset+count)},appendData:function(text){text=this.data+text,this.nodeValue=this.data=text,this.length=text.length},insertData:function(offset,text){this.replaceData(offset,0,text)},appendChild:function(newChild){throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])},deleteData:function(offset,count){this.replaceData(offset,count,"")},replaceData:function(offset,count,text){text=this.data.substring(0,offset)+text+this.data.substring(offset+count),this.nodeValue=this.data=text,this.length=text.length}},_extends(CharacterData,Node),Text.prototype={nodeName:"#text",nodeType:TEXT_NODE,splitText:function(offset){var text=this.data,newText=text.substring(of
fset);text=text.substring(0,offset),this.data=this.nodeValue=text,this.length=text.length;var newNode=this.ownerDocument.createTextNode(newText);return this.parentNode&&this.parentNode.insertBefore(newNode,this.nextSibling),newNode}},_extends(Text,CharacterData),Comment.prototype={nodeName:"#comment",nodeType:COMMENT_NODE},_extends(Comment,CharacterData),CDATASection.prototype={nodeName:"#cdata-section",nodeType:CDATA_SECTION_NODE},_extends(CDATASection,CharacterData),DocumentType.prototype.nodeType=DOCUMENT_TYPE_NODE,_extends(DocumentType,Node),Notation.prototype.nodeType=NOTATION_NODE,_extends(Notation,Node),Entity.prototype.nodeType=ENTITY_NODE,_extends(Entity,Node),EntityReference.prototype.nodeType=ENTITY_REFERENCE_NODE,_extends(EntityReference,Node),DocumentFragment.prototype.nodeName="#document-fragment",DocumentFragment.prototype.nodeType=DOCUMENT_FRAGMENT_NODE,_extends(DocumentFragment,Node),ProcessingInstruction.prototype.nodeType=PROCESSING_INSTRUCTION_NODE,_extends(ProcessingInstruction,Node),XML
Serializer.prototype.serializeToString=function(node,isHtml,nodeFilter){return nodeSerializeToString.call(node,isHtml,nodeFilter)},Node.prototype.toString=nodeSerializeToString;try{if(Object.defineProperty){function getTextContent(node){switch(node.nodeType){case ELEMENT_NODE:case DOCUMENT_FRAGMENT_NODE:var buf=[];for(node=node.firstChild;node;)7!==node.nodeType&&8!==node.nodeType&&buf.push(getTextContent(node)),node=node.nextSibling;return buf.join("");default:return node.nodeValue}}Object.defineProperty(LiveNodeList.prototype,"length",{get:function(){return _updateLiveList(this),this.$$length}}),Object.defineProperty(Node.prototype,"textContent",{get:function(){return getTextContent(this)},set:function(data){switch(this.nodeType){case ELEMENT_NODE:case DOCUMENT_FRAGMENT_NODE:for(;this.firstChild;)this.removeChild(this.firstChild);(data||String(data))&&this.appendChild(this.ownerDocument.createTextNode(data));break;default:this.data=data,this.value=data,this.nodeValue=data}}}),__set__=function(object,key,va
lue){object["$$"+key]=value}}}catch(e){}var dom={DocumentType:DocumentType,DOMException:DOMException,DOMImplementation:DOMImplementation$1,Element:Element,Node:Node,NodeList:NodeList,XMLSerializer:XMLSerializer},entities=createCommonjsModule((function(module,exports){var freeze=conventions.freeze;exports.XML_ENTITIES=freeze({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'}),exports.HTML_ENTITIES=freeze({Aacute:"Ã",aacute:"á",Abreve:"Ä‚",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"Ð",acy:"а",AElig:"Æ",aelig:"æ",af:"â¡",Afr:"ð”„",afr:"ð”ž",Agrave:"À",agrave:"à ",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ä€",amacr:"Ä",amalg:"⨿",AMP:"&",amp:"&",And:"â©“",and:"∧",andand:"â©•",andd:"â©œ",andslope:"⩘",andv:"â©š",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"â¦",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"â¦",angsph:"∢",angst:"Ã…",angzarr:"â¼",Aogo
n:"Ä„",aogon:"Ä…",Aopf:"ð”¸",aopf:"ð•’",ap:"≈",apacir:"⩯",apE:"â©°",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"â¡",approx:"≈",approxeq:"≊",Aring:"Ã…",aring:"Ã¥",Ascr:"ð’œ",ascr:"ð’¶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"â‰",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"â‹",Backslash:"∖",Barv:"⫧",barvee:"⊽",Barwed:"⌆",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",Because:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Î’",beta:"β",beth:"ℶ",between:"≬",Bfr:"ð”…",bfr:"ð”Ÿ",bigcap:"â‹‚",bigcirc:"â—¯",bigcup:"⋃",bigodot:"⨀",bigoplus:"â¨",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"â–½",bigtriangleup:"â–³",biguplus:"⨄",bigvee:"â‹",bigwedge:"â‹€",bkarow:"â¤",blacklozenge:"⧫",blacksquare:"â–ª",blacktriangle:"â–´",blacktriangledown:"â–¾",blacktriangleleft:"â—‚",
blacktriangleright:"â–¸",blank:"â£",blk12:"â–’",blk14:"â–‘",blk34:"â–“",block:"â–ˆ",bne:"=⃥",bnequiv:"≡⃥",bNot:"â«",bnot:"âŒ",Bopf:"ð”¹",bopf:"ð•“",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxDL:"â•—",boxDl:"â•–",boxdL:"â••",boxdl:"â”",boxDR:"â•”",boxDr:"â•“",boxdR:"â•’",boxdr:"┌",boxH:"â•",boxh:"─",boxHD:"╦",boxHd:"╤",boxhD:"â•¥",boxhd:"┬",boxHU:"â•©",boxHu:"╧",boxhU:"╨",boxhu:"â”´",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxUL:"â•",boxUl:"â•œ",boxuL:"â•›",boxul:"┘",boxUR:"â•š",boxUr:"â•™",boxuR:"╘",boxur:"â””",boxV:"â•‘",boxv:"│",boxVH:"╬",boxVh:"â•«",boxvH:"╪",boxvh:"┼",boxVL:"â•£",boxVl:"â•¢",boxvL:"â•¡",boxvl:"┤",boxVR:"â• ",boxVr:"â•Ÿ",boxvR:"â•ž",boxvr:"├",bprime:"‵",Breve:"˘",breve:"˘",brvbar:"¦",Bscr:"ℬ",bscr:"ð’·",bsemi:"â",bsim:"∽",bsime:"â‹",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"â‰",Bumpeq:"≎",bumpeq:"â‰",Cacute:"Ć",cacute:"ć",Cap:"â‹’",cap:"∩",capand:"â©„",capbrcup:"â
©‰",capcap:"â©‹",capcup:"⩇",capdot:"â©€",CapitalDifferentialD:"â……",caps:"∩︀",caret:"â",caron:"ˇ",Cayleys:"â„",ccaps:"â©",Ccaron:"ÄŒ",ccaron:"Ä",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"â©Œ",ccupssm:"â©",Cdot:"ÄŠ",cdot:"Ä‹",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",CenterDot:"·",centerdot:"·",Cfr:"â„",cfr:"ð” ",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",cir:"â—‹",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"âŠ",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cirE:"⧃",cire:"≗",cirfnint:"â¨",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"â€",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",Colon:"∷",colon:":",Colone:"â©´",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"âˆ",compfn:"∘",complement:"âˆ",complexes:"â„‚",cong:"≅",congdot:"â©",Congruent:"≡",Conint:"∯",
conint:"∮",ContourIntegral:"∮",Copf:"â„‚",copf:"ð•”",coprod:"âˆ",Coproduct:"âˆ",COPY:"©",copy:"©",copysr:"â„—",CounterClockwiseContourIntegral:"∳",crarr:"↵",Cross:"⨯",cross:"✗",Cscr:"ð’ž",cscr:"ð’¸",csub:"â«",csube:"â«‘",csup:"â«",csupe:"â«’",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"â‹ž",cuesc:"â‹Ÿ",cularr:"↶",cularrp:"⤽",Cup:"â‹“",cup:"∪",cupbrcap:"⩈",CupCap:"â‰",cupcap:"⩆",cupcup:"â©Š",cupdot:"âŠ",cupor:"â©…",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"â‹ž",curlyeqsucc:"â‹Ÿ",curlyvee:"â‹Ž",curlywedge:"â‹",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"â‹Ž",cuwed:"â‹",cwconint:"∲",cwint:"∱",cylcty:"âŒ",Dagger:"‡",dagger:"†",daleth:"ℸ",Darr:"↡",dArr:"⇓",darr:"↓",dash:"â€",Dashv:"⫤",dashv:"⊣",dbkarow:"â¤",dblac:"Ë",Dcaron:"ÄŽ",dcaron:"Ä",Dcy:"Д",dcy:"д",DD:"â……",dd:"â…†",ddagger:"‡",ddarr:"⇊",DDotrahd:"⤑",ddotseq:"â©·",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"ð”‡",dfr:"ð”¡",dHar
:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",Diamond:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",Downarrow:"⇓",downarrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",down
harpoonright:"⇂",DownLeftRightVector:"â¥",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"â‡",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",drbkarow:"â¤",drcorn:"⌟",drcrop:"⌌",Dscr:"ð’Ÿ",dscr:"ð’¹",DScy:"Ð…",dscy:"Ñ•",dsol:"⧶",Dstrok:"Ä",dstrok:"Ä‘",dtdot:"⋱",dtri:"â–¿",dtrif:"â–¾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Ð",dzcy:"ÑŸ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"â©®",Ecaron:"Äš",ecaron:"Ä›",ecir:"≖",Ecirc:"Ê",ecirc:"ê",ecolon:"≕",Ecy:"Ð",ecy:"Ñ",eDDot:"â©·",Edot:"Ä–",eDot:"≑",edot:"Ä—",ee:"â…‡",efDot:"≒",Efr:"ð”ˆ",efr:"ð”¢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"â§",ell:"â„“",els:"⪕",elsdot:"⪗",Emacr:"Ä’",emacr:"Ä“",empty:"∅",emptyset:"∅",EmptySmallSquare:"â—»",emptyv:"∅",EmptyVerySmallSquare:"â–«",emsp:" ",emsp13:" ",emsp14:" ",ENG:"ÅŠ",eng:"Å‹",ensp:" ",Eogon:"Ę",eogon:"Ä™",Eopf:"ð”¼",eopf:"ð•–",epar:"â‹•",epa
rsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",Escr:"â„°",escr:"ℯ",esdot:"â‰",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ã",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"â„°",ExponentialE:"â…‡",exponentiale:"â…‡",fallingdotseq:"≒",Fcy:"Ф",fcy:"Ñ„",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"ð”‰",ffr:"ð”£",filig:"ï¬",FilledSmallSquare:"â—¼",FilledVerySmallSquare:"â–ª",fjlig:"fj",flat:"â™",fllig:"fl",fltns:"â–±",fnof:"Æ’",Fopf:"ð”½",fopf:"ð•—",ForAll:"∀",forall:"∀",fork:"â‹”",forkv:"â«™",Fouriertrf:"ℱ",fpartint:"â¨",frac12:"½",frac13:"â…“",frac14:"¼",frac15:"â…•",frac16:"â…™",frac18:"â…›",frac23:"â…”",frac25:"â…–",frac34:"¾",frac35:"â…—",frac38:"â…œ",frac45:"â…˜",frac56:"â…š",frac58:"â…",frac78:"â…ž",fra
sl:"â„",frown:"⌢",Fscr:"ℱ",fscr:"ð’»",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ïœ",gammad:"Ï",gap:"⪆",Gbreve:"Äž",gbreve:"ÄŸ",Gcedil:"Ä¢",Gcirc:"Äœ",gcirc:"Ä",Gcy:"Г",gcy:"г",Gdot:"Ä ",gdot:"Ä¡",gE:"≧",ge:"≥",gEl:"⪌",gel:"â‹›",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"ð”Š",gfr:"ð”¤",Gg:"â‹™",gg:"≫",ggg:"â‹™",gimel:"â„·",GJcy:"Ѓ",gjcy:"Ñ“",gl:"≷",gla:"⪥",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gnE:"≩",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"ð”¾",gopf:"ð•˜",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"â‹›",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"ð’¢",gscr:"â„Š",gsim:"≳",gsime:"⪎",gsiml:"âª",Gt:"≫",GT:">",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"â‹—",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"â‹—",gtreqless:"â‹›",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvn
E:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"â„‹",HARDcy:"Ъ",hardcy:"ÑŠ",hArr:"⇔",harr:"↔",harrcir:"⥈",harrw:"â†",Hat:"^",hbar:"â„",Hcirc:"Ĥ",hcirc:"Ä¥",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",Hfr:"â„Œ",hfr:"ð”¥",HilbertSpace:"â„‹",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",Hopf:"â„",hopf:"ð•™",horbar:"―",HorizontalLine:"─",Hscr:"â„‹",hscr:"ð’½",hslash:"â„",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"â‰",hybull:"âƒ",hyphen:"â€",Iacute:"Ã",iacute:"Ã",ic:"â£",Icirc:"ÃŽ",icirc:"î",Icy:"И",icy:"и",Idot:"Ä°",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",Ifr:"â„‘",ifr:"ð”¦",Igrave:"ÃŒ",igrave:"ì",ii:"â…ˆ",iiiint:"⨌",iiint:"âˆ",iinfin:"⧜",iiota:"â„©",IJlig:"IJ",ijlig:"ij",Im:"â„‘",Imacr:"Ī",imacr:"Ä«",image:"â„‘",ImaginaryI:"â…ˆ",imagline:"â„",imagpart:"â„‘",imath:"ı",imof:"⊷",imped:"Ƶ",Implies:"⇒",in:"∈",incare:"â„…",infin:"∞",infintie:"â§",inodot:"ı",Int:"∬",int:"∫",intcal:"⊺",in
tegers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"â‹‚",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"â£",InvisibleTimes:"â¢",IOcy:"Ð",iocy:"Ñ‘",Iogon:"Ä®",iogon:"į",Iopf:"ð•€",iopf:"ð•š",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",Iscr:"â„",iscr:"ð’¾",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"â‹´",isinsv:"⋳",isinv:"∈",it:"â¢",Itilde:"Ĩ",itilde:"Ä©",Iukcy:"І",iukcy:"Ñ–",Iuml:"Ã",iuml:"ï",Jcirc:"Ä´",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"ð”",jfr:"ð”§",jmath:"È·",Jopf:"ð•",jopf:"ð•›",Jscr:"ð’¥",jscr:"ð’¿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"Ñ”",Kappa:"Κ",kappa:"κ",kappav:"Ï°",Kcedil:"Ķ",kcedil:"Ä·",Kcy:"К",kcy:"к",Kfr:"ð”Ž",kfr:"ð”¨",kgreen:"ĸ",KHcy:"Ð¥",khcy:"Ñ…",KJcy:"ÐŒ",kjcy:"Ñœ",Kopf:"ð•‚",kopf:"ð•œ",Kscr:"ð’¦",kscr:"ð“€",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"â„’",Lambda:"Λ",lambda:"λ",Lang:"⟪",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"â„’",laquo:"«",Larr:"↞",lArr:"â‡",larr:"â†",larrb:"⇤",larrbfs:"⤟",larrfs:"â¤
",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",lAtail:"⤛",latail:"⤙",late:"âª",lates:"âªï¸€",lBarr:"⤎",lbarr:"⤌",lbbrk:"â²",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"â¦",lbrkslu:"â¦",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ä»",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",lE:"≦",le:"≤",LeftAngleBracket:"⟨",LeftArrow:"â†",Leftarrow:"â‡",leftarrow:"â†",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"â†",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",leftthreetimes:"â‹‹",LeftTriangle:"⊲",LeftTriangleBar:"â§",LeftTriangleEqua
l:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",lEg:"⪋",leg:"â‹š",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"â©¿",lesdoto:"âª",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"â‹–",lesseqgtr:"â‹š",lesseqqgtr:"⪋",LessEqualGreater:"â‹š",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"ð”",lfr:"ð”©",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"â–„",LJcy:"Љ",ljcy:"Ñ™",Ll:"⋘",ll:"≪",llarr:"⇇",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"â—º",Lmidot:"Ä¿",lmidot:"Å€",lmoust:"⎰",lmoustache:"⎰",lnap:"⪉",lnapprox:"⪉",lnE:"≨",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftarrow:"⟵",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longleftrightarrow:"⟷",
longmapsto:"⟼",LongRightArrow:"⟶",Longrightarrow:"⟹",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"ð•ƒ",lopf:"ð•",loplus:"â¨",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"â—Š",lozenge:"â—Š",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"â¥",lrm:"‎",lrtri:"⊿",lsaquo:"‹",Lscr:"â„’",lscr:"ð“",Lsh:"↰",lsh:"↰",lsim:"≲",lsime:"âª",lsimg:"âª",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Å",lstrok:"Å‚",Lt:"≪",LT:"<",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"â‹–",lthree:"â‹‹",ltimes:"⋉",ltlarr:"⥶",ltquest:"â©»",ltri:"â—ƒ",ltrie:"⊴",ltrif:"â—‚",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"â–®",mcomma:"⨩",Mcy:"Ðœ",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:"âŸ",Mellintrf:"ℳ",Mfr:"ð”",mfr:"ð”ª"
,mho:"℧",micro:"µ",mid:"∣",midast:"*",midcir:"â«°",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"â«›",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"ð•„",mopf:"ð•ž",mp:"∓",Mscr:"ℳ",mscr:"ð“‚",mstpos:"∾",Mu:"Îœ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"Å„",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"â™®",natural:"â™®",naturals:"â„•",nbsp:" ",nbump:"≎̸",nbumpe:"â‰Ì¸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Å…",ncedil:"ņ",ncong:"≇",ncongdot:"â©Ì¸",ncup:"â©‚",Ncy:"Ð",ncy:"н",ndash:"–",ne:"≠",nearhk:"⤤",neArr:"⇗",nearr:"↗",nearrow:"↗",nedot:"â‰Ì¸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",nexist:"∄",nexists:"∄",Nfr:"ð”‘",nfr:"ð”«",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",n
Gg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"Ñš",nlArr:"â‡",nlarr:"↚",nldr:"‥",nlE:"≦̸",nle:"≰",nLeftarrow:"â‡",nleftarrow:"↚",nLeftrightarrow:"⇎",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"â ",NonBreakingSpace:" ",Nopf:"â„•",nopf:"ð•Ÿ",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"â‰",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"â‰Ì¸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"â‹·",notinvc:"⋶",NotLeftTriangle:"⋪",NotLeftTriangleBar:"â§Ì¸",Not
LeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"â‹ ",NotReverseElement:"∌",NotRightTriangle:"â‹«",NotRightTriangleBar:"â§Ì¸",NotRightTriangleEqual:"â‹",NotSquareSubset:"âŠÌ¸",NotSquareSubsetEqual:"â‹¢",NotSquareSuperset:"âŠÌ¸",NotSquareSupersetEqual:"â‹£",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"âŠ",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"â‹¡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"â‰",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"â‹ ",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"â‡",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"â†Ì¸",nRightarrow:"â‡",n
rightarrow:"↛",nrtri:"â‹«",nrtrie:"â‹",nsc:"âŠ",nsccue:"â‹¡",nsce:"⪰̸",Nscr:"ð’©",nscr:"ð“ƒ",nshortmid:"∤",nshortparallel:"∦",nsim:"â‰",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"â‹¢",nsqsupe:"â‹£",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"âŠ",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"â‹«",ntrianglerighteq:"â‹",Nu:"Î",nu:"ν",num:"#",numero:"â„–",numsp:" ",nvap:"â‰âƒ’",nVDash:"⊯",nVdash:"⊮",nvDash:"âŠ",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwArr:"⇖",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",ocir:"⊚",Ocirc:"Ô",ocirc:"ô",Ocy:"О",ocy:"о",odash:"âŠ",Odblac:"Å",odblac:"Å‘",odi
v:"⨸",odot:"⊙",odsold:"⦼",OElig:"Å’",oelig:"Å“",ofcir:"⦿",Ofr:"ð”’",ofr:"ð”¬",ogon:"Ë›",Ograve:"Ã’",ograve:"ò",ogt:"â§",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"ÅŒ",omacr:"Å",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"ð•†",oopf:"ð• ",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",Or:"â©”",or:"∨",orarr:"↻",ord:"â©",order:"â„´",orderof:"â„´",ordf:"ª",ordm:"º",origof:"⊶",oror:"â©–",orslope:"â©—",orv:"â©›",oS:"Ⓢ",Oscr:"ð’ª",oscr:"â„´",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",Otimes:"⨷",otimes:"⊗",otimesas:"⨶",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"âž",OverBracket:"⎴",OverParenthesis:"âœ",par:"∥",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"ð”“",pfr:"ð”",Phi:"Φ",phi:"φ",phiv:"Ï•",phmmat:"ℳ",pho
ne:"☎",Pi:"Î ",pi:"Ï€",pitchfork:"â‹”",piv:"Ï–",planck:"â„",planckh:"â„Ž",plankv:"â„",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"â„Œ",pointint:"⨕",Popf:"â„™",popf:"ð•¡",pound:"£",Pr:"⪻",pr:"≺",prap:"⪷",prcue:"≼",prE:"⪳",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",Prime:"″",prime:"′",primes:"â„™",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"âˆ",Product:"âˆ",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"âˆ",Proportion:"∷",Proportional:"âˆ",propto:"âˆ",prsim:"≾",prurel:"⊰",Pscr:"ð’«",pscr:"ð“…",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"ð””",qfr:"ð”®",qint:"⨌",Qopf:"â„š",qopf:"ð•¢",qprime:"â—",Qscr:"ð’¬",qscr:"ð“†",quaternions:"â„",quatint:"⨖",quest:"?",questeq:"≟",QUOT:'"',quot:'"',r
Aarr:"⇛",race:"∽̱",Racute:"Å”",racute:"Å•",radic:"√",raemptyv:"⦳",Rang:"⟫",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",Rarr:"↠",rArr:"⇒",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"â†",rAtail:"⤜",ratail:"⤚",ratio:"∶",rationals:"â„š",RBarr:"â¤",rBarr:"â¤",rbarr:"â¤",rbbrk:"â³",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"â¦",Rcaron:"Ř",rcaron:"Å™",Rcedil:"Å–",rcedil:"Å—",rceil:"⌉",rcub:"}",Rcy:"Ð ",rcy:"Ñ€",rdca:"⤷",rdldhar:"⥩",rdquo:"â€",rdquor:"â€",rdsh:"↳",Re:"â„œ",real:"â„œ",realine:"â„›",realpart:"â„œ",reals:"â„",rect:"â–",REG:"®",reg:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",Rfr:"â„œ",rfr:"ð”¯",rHar:"⥤",rhard:"â‡",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"Ï",rhov:"ϱ",RightAngleBracket:"⟩",RightArrow:"→",Rightarrow:"⇒",rightarrow:"→",RightArrowBar:"â‡
¥",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"â¥",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",rightharpoondown:"â‡",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"â†",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",rightthreetimes:"â‹Œ",RightTriangle:"⊳",RightTriangleBar:"â§",RightTriangleEqual:"⊵",RightUpDownVector:"â¥",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",ring:"Ëš",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"â€",rmoust:"⎱",rmoustache:"⎱",rnmid:"â«®",roang:"âŸ",roarr:"⇾",robrk:"⟧",ropar:"⦆",Ropf:"â„",ropf:"ð•£",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",Rscr:"â„›",rscr:"ð“‡",Rsh:"↱",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"â‹Œ",rtimes:"â‹Š",rtri:"â–¹",rtrie:"⊵",rt
rif:"â–¸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"â„ž",Sacute:"Åš",sacute:"Å›",sbquo:"‚",Sc:"⪼",sc:"≻",scap:"⪸",Scaron:"Å ",scaron:"Å¡",sccue:"≽",scE:"⪴",sce:"⪰",Scedil:"Åž",scedil:"ÅŸ",Scirc:"Åœ",scirc:"Å",scnap:"⪺",scnE:"⪶",scnsim:"â‹©",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"Ñ",sdot:"â‹…",sdotb:"⊡",sdote:"⩦",searhk:"⤥",seArr:"⇘",searr:"↘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"ð”–",sfr:"ð”°",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"â†",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"Â",Sigma:"Σ",sigma:"σ",sigmaf:"Ï‚",sigmav:"Ï‚",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"âª",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"â†",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"
ÑŒ",sol:"/",solb:"⧄",solbar:"⌿",Sopf:"ð•Š",sopf:"ð•¤",spades:"â™ ",spadesuit:"â™ ",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"âŠ",sqsube:"⊑",sqsubset:"âŠ",sqsubseteq:"⊑",sqsup:"âŠ",sqsupe:"⊒",sqsupset:"âŠ",sqsupseteq:"⊒",squ:"â–¡",Square:"â–¡",square:"â–¡",SquareIntersection:"⊓",SquareSubset:"âŠ",SquareSubsetEqual:"⊑",SquareSuperset:"âŠ",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"â–ª",squf:"â–ª",srarr:"→",Sscr:"ð’®",sscr:"ð“ˆ",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"Ï•",strns:"¯",Sub:"â‹",sub:"⊂",subdot:"⪽",subE:"â«…",sube:"⊆",subedot:"⫃",submult:"â«",subnE:"â«‹",subne:"⊊",subplus:"⪿",subrarr:"⥹",Subset:"â‹",subset:"⊂",subseteq:"⊆",subseteqq:"â«…",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"â«‹",subsim:"⫇",subsub:"â«•",subsup:"â«“",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",Suc
ceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"â‹©",succsim:"≿",SuchThat:"∋",Sum:"∑",sum:"∑",sung:"♪",Sup:"â‹‘",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"â«„",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"â«—",suplarr:"⥻",supmult:"â«‚",supnE:"â«Œ",supne:"⊋",supplus:"â«€",Supset:"â‹‘",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"â«Œ",supsim:"⫈",supsub:"â«”",supsup:"â«–",swarhk:"⤦",swArr:"⇙",swarr:"↙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:"\t",target:"⌖",Tau:"Τ",tau:"Ï„",tbrk:"⎴",Tcaron:"Ť",tcaron:"Å¥",Tcedil:"Å¢",tcedil:"Å£",Tcy:"Т",tcy:"Ñ‚",tdot:"⃛",telrec:"⌕",Tfr:"ð”—",tfr:"ð”±",there4:"∴",Therefore:"∴",therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"Ï‘",thetav:"Ï‘",thickapprox:"≈",thicksim:"∼",ThickSpace:"âŸâ€Š",thinsp:" ",ThinSpace:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",Tilde:"∼",tilde:"Ëœ",TildeEqual:"≃",TildeFullEqual
:"≅",TildeTilde:"≈",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"âˆ",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",Topf:"ð•‹",topf:"ð•¥",topfork:"â«š",tosa:"⤩",tprime:"‴",TRADE:"â„¢",trade:"â„¢",triangle:"â–µ",triangledown:"â–¿",triangleleft:"â—ƒ",trianglelefteq:"⊴",triangleq:"≜",triangleright:"â–¹",trianglerighteq:"⊵",tridot:"â—¬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"â§",tritime:"⨻",trpezium:"â¢",Tscr:"ð’¯",tscr:"ð“‰",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"Ñ›",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",Uarr:"↟",uArr:"⇑",uarr:"↑",Uarrocir:"⥉",Ubrcy:"ÐŽ",ubrcy:"Ñž",Ubreve:"Ŭ",ubreve:"Å",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Å°",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"ð”˜",ufr:"ð”²",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"â–€",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"âŒ",ultri:"â—¸",Umacr:"Ū",umacr:"Å«",uml:"¨",UnderBar:"_",Und
erBrace:"âŸ",UnderBracket:"⎵",UnderParenthesis:"â",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"ð•Œ",uopf:"ð•¦",UpArrow:"↑",Uparrow:"⇑",uparrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",Updownarrow:"⇕",updownarrow:"↕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"Ï’",upsi:"Ï…",upsih:"Ï’",Upsilon:"Î¥",upsilon:"Ï…",UpTee:"⊥",UpTeeArrow:"↥",upuparrows:"⇈",urcorn:"âŒ",urcorner:"âŒ",urcrop:"⌎",Uring:"Å®",uring:"ů",urtri:"â—¹",Uscr:"ð’°",uscr:"ð“Š",utdot:"â‹°",Utilde:"Ũ",utilde:"Å©",utri:"â–µ",utrif:"â–´",uuarr:"⇈",Uuml:"Ãœ",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"Ï°",varnothing:"∅",varphi:"Ï•",varpi:"Ï–",varpropto:"âˆ",vArr:"⇕",varr:"↕",varrho:"ϱ",varsigma:"Ï‚",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"Ï‘",vartriangleleft:"⊲",vartriangleright:"⊳",Vbar:"â««",vBar:"⫨",vBarv:"â«©",Vcy:
"Ð’",vcy:"в",VDash:"⊫",Vdash:"⊩",vDash:"⊨",vdash:"⊢",Vdashl:"⫦",Vee:"â‹",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"â‹®",Verbar:"‖",verbar:"|",Vert:"‖",vert:"|",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"â˜",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"ð”™",vfr:"ð”³",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"ð•",vopf:"ð•§",vprop:"âˆ",vrtri:"⊳",Vscr:"ð’±",vscr:"ð“‹",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Å´",wcirc:"ŵ",wedbar:"â©Ÿ",Wedge:"â‹€",wedge:"∧",wedgeq:"≙",weierp:"℘",Wfr:"ð”š",wfr:"ð”´",Wopf:"ð•Ž",wopf:"ð•¨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"ð’²",wscr:"ð“Œ",xcap:"â‹‚",xcirc:"â—¯",xcup:"⋃",xdtri:"â–½",Xfr:"ð”›",xfr:"ð”µ",xhArr:"⟺",xharr:"⟷",Xi:"Ξ",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"â‹»",xodot:"⨀",Xopf:"ð•",xopf:"ð•©",xoplus:"â¨",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",Xscr:"ð’³",xscr:"ð“",xsqcup:"⨆",xuplus:"⨄",xutri:"â–³",xvee:"â‹",xwedge:"â‹€",Yacute:"
Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",Yuml:"Ÿ",yuml:"ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"",Zeta:"Ζ",zeta:"ζ",Zfr:"ℨ",zfr:"𝔷",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",Zopf:"ℤ",zopf:"𝕫",Zscr:"𝒵",zscr:"𝓏",zwj:"",zwnj:""}),exports.entityMap=exports.HTML_ENTITIES}));entities.XML_ENTITIES,entities.HTML_ENTITIES,entities.entityMap;var NAMESPACE$1=conventions.NAMESPACE,nameStartChar=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,nameChar=new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),tagNamePattern=new RegExp("^"+nameStartChar.source+nameChar.source+"*(?::"+nameStartChar.source+nameChar.source+"*)?$");function
ParseError$1(message,locator){this.message=message,this.locator=locator,Error.captureStackTrace&&Error.captureStackTrace(this,ParseError$1)}function XMLReader$1(){}function copyLocator(f,t){return t.lineNumber=f.lineNumber,t.columnNumber=f.columnNumber,t}function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){function addAttribute(qname,value,startIndex){el.attributeNames.hasOwnProperty(qname)&&errorHandler.fatalError("Attribute "+qname+" redefined"),el.addValue(qname,value.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,entityReplacer),startIndex)}for(var attrName,p=++start,s=0;;){var c=source.charAt(p);switch(c){case"=":if(1===s)attrName=source.slice(start,p),s=3;else{if(2!==s)throw new Error("attribute equal must after attrName");s=3}break;case"'":case'"':if(3===s||1===s){if(1===s&&(errorHandler.warning('attribute value must after "="'),attrName=source.slice(start,p)),start=p+1,!((p=source.indexOf(c,start))>0))throw new Error("attribute value no end '"+c+"' match");addAttribut
e(attrName,value=source.slice(start,p),start-1),s=5}else{if(4!=s)throw new Error('attribute value must after "="');addAttribute(attrName,value=source.slice(start,p),start),errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+")!!"),start=p+1,s=5}break;case"/":switch(s){case 0:el.setTagName(source.slice(start,p));case 5:case 6:case 7:s=7,el.closed=!0;case 4:case 1:break;case 2:el.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return errorHandler.error("unexpected end of input"),0==s&&el.setTagName(source.slice(start,p)),p;case">":switch(s){case 0:el.setTagName(source.slice(start,p));case 5:case 6:case 7:break;case 4:case 1:"/"===(value=source.slice(start,p)).slice(-1)&&(el.closed=!0,value=value.slice(0,-1));case 2:2===s&&(value=attrName),4==s?(errorHandler.warning('attribute "'+value+'" missed quot(")!'),addAttribute(attrName,value,start)):(NAMESPACE$1.isHTML(currentNSMap[""])&&value.match(/^(?:disabled|checked|selected)$/i)||errorHandler.warning('att
ribute "'+value+'" missed value!! "'+value+'" instead!!'),addAttribute(value,value,start));break;case 3:throw new Error("attribute value missed!!")}return p;case"€":c=" ";default:if(c<=" ")switch(s){case 0:el.setTagName(source.slice(start,p)),s=6;break;case 1:attrName=source.slice(start,p),s=2;break;case 4:var value=source.slice(start,p);errorHandler.warning('attribute "'+value+'" missed quot(")!!'),addAttribute(attrName,value,start);case 5:s=6}else switch(s){case 2:el.tagName,NAMESPACE$1.isHTML(currentNSMap[""])&&attrName.match(/^(?:disabled|checked|selected)$/i)||errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!'),addAttribute(attrName,attrName,start),start=p,s=1;break;case 5:errorHandler.warning('attribute space is required"'+attrName+'"!!');case 6:s=1,start=p;break;case 3:s=4,start=p;break;case 7:throw new Error("elements closed character '/' and '>' must be connected to")}}p++}}function appendElement$1(el,domBuilder,currentNSMap){for(var tagName=el.tagName,localNSM
ap=null,i=el.length;i--;){var a=el[i],qName=a.qName,value=a.value;if((nsp=qName.indexOf(":"))>0)var prefix=a.prefix=qName.slice(0,nsp),localName=qName.slice(nsp+1),nsPrefix="xmlns"===prefix&&localName;else localName=qName,prefix=null,nsPrefix="xmlns"===qName&&"";a.localName=localName,!1!==nsPrefix&&(null==localNSMap&&(localNSMap={},_copy(currentNSMap,currentNSMap={})),currentNSMap[nsPrefix]=localNSMap[nsPrefix]=value,a.uri=NAMESPACE$1.XMLNS,domBuilder.startPrefixMapping(nsPrefix,value))}for(i=el.length;i--;){(prefix=(a=el[i]).prefix)&&("xml"===prefix&&(a.uri=NAMESPACE$1.XML),"xmlns"!==prefix&&(a.uri=currentNSMap[prefix||""]))}var nsp;(nsp=tagName.indexOf(":"))>0?(prefix=el.prefix=tagName.slice(0,nsp),localName=el.localName=tagName.slice(nsp+1)):(prefix=null,localName=el.localName=tagName);var ns=el.uri=currentNSMap[prefix||""];if(domBuilder.startElement(ns,localName,tagName,el),!el.closed)return el.currentNSMap=currentNSMap,el.localNSMap=localNSMap,!0;if(domBuilder.endElement(ns,localName,tagName),localNSMap
)for(prefix in localNSMap)Object.prototype.hasOwnProperty.call(localNSMap,prefix)&&domBuilder.endPrefixMapping(prefix)}function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){if(/^(?:script|textarea)$/i.test(tagName)){var elEndStart=source.indexOf("</"+tagName+">",elStartEnd),text=source.substring(elStartEnd+1,elEndStart);if(/[&<]/.test(text))return/^script$/i.test(tagName)?(domBuilder.characters(text,0,text.length),elEndStart):(text=text.replace(/&#?\w+;/g,entityReplacer),domBuilder.characters(text,0,text.length),elEndStart)}return elStartEnd+1}function fixSelfClosed(source,elStartEnd,tagName,closeMap){var pos=closeMap[tagName];return null==pos&&((pos=source.lastIndexOf("</"+tagName+">"))<elStartEnd&&(pos=source.lastIndexOf("</"+tagName)),closeMap[tagName]=pos),pos<elStartEnd}function _copy(source,target){for(var n in source)Object.prototype.hasOwnProperty.call(source,n)&&(target[n]=source[n])}function parseDCC(source,start,domBuilder,errorHandler){if("-"===source.charAt(start+
2))return"-"===source.charAt(start+3)?(end=source.indexOf("--\x3e",start+4))>start?(domBuilder.comment(source,start+4,end-start-4),end+3):(errorHandler.error("Unclosed comment"),-1):-1;if("CDATA["==source.substr(start+3,6)){var end=source.indexOf("]]>",start+9);return domBuilder.startCDATA(),domBuilder.characters(source,start+9,end-start-9),domBuilder.endCDATA(),end+3}var matchs=function(source,start){var match,buf=[],reg=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;reg.lastIndex=start,reg.exec(source);for(;match=reg.exec(source);)if(buf.push(match),match[1])return buf}(source,start),len=matchs.length;if(len>1&&/!doctype/i.test(matchs[0][0])){var name=matchs[1][0],pubid=!1,sysid=!1;len>3&&(/^public$/i.test(matchs[2][0])?(pubid=matchs[3][0],sysid=len>4&&matchs[4][0]):/^system$/i.test(matchs[2][0])&&(sysid=matchs[3][0]));var lastMatch=matchs[len-1];return domBuilder.startDTD(name,pubid,sysid),domBuilder.endDTD(),lastMatch.index+lastMatch[0].length}return-1}function parseInstruction(source,start,domBuilder){var
end=source.indexOf("?>",start);if(end){var match=source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);return match?(match[0].length,domBuilder.processingInstruction(match[1],match[2]),end+2):-1}return-1}function ElementAttributes(){this.attributeNames={}}ParseError$1.prototype=new Error,ParseError$1.prototype.name=ParseError$1.name,XMLReader$1.prototype={parse:function(source,defaultNSMap,entityMap){var domBuilder=this.domBuilder;domBuilder.startDocument(),_copy(defaultNSMap,defaultNSMap={}),function(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){function fixedFromCharCode(code){if(code>65535){var surrogate1=55296+((code-=65536)>>10),surrogate2=56320+(1023&code);return String.fromCharCode(surrogate1,surrogate2)}return String.fromCharCode(code)}function entityReplacer(a){var k=a.slice(1,-1);return Object.hasOwnProperty.call(entityMap,k)?entityMap[k]:"#"===k.charAt(0)?fixedFromCharCode(parseInt(k.substr(1).replace("x","0x"))):(errorHandler.error("entity not found:"+a),a)}function append
Text(end){if(end>start){var xt=source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);locator&&position(start),domBuilder.characters(xt,0,end-start),start=end}}function position(p,m){for(;p>=lineEnd&&(m=linePattern.exec(source));)lineStart=m.index,lineEnd=lineStart+m[0].length,locator.lineNumber++;locator.columnNumber=p-lineStart+1}var lineStart=0,lineEnd=0,linePattern=/.*(?:\r\n?|\n)|.*$/g,locator=domBuilder.locator,parseStack=[{currentNSMap:defaultNSMapCopy}],closeMap={},start=0;for(;;){try{var tagStart=source.indexOf("<",start);if(tagStart<0){if(!source.substr(start).match(/^\s*$/)){var doc=domBuilder.doc,text=doc.createTextNode(source.substr(start));doc.appendChild(text),domBuilder.currentElement=text}return}switch(tagStart>start&&appendText(tagStart),source.charAt(tagStart+1)){case"/":var end=source.indexOf(">",tagStart+3),tagName=source.substring(tagStart+2,end).replace(/[ \t\n\r]+$/g,""),config=parseStack.pop();end<0?(tagName=source.substring(tagStart+2).replace(/[\s<].*/,""),errorHandler.erro
r("end tag name: "+tagName+" is not complete:"+config.tagName),end=tagStart+1+tagName.length):tagName.match(/\s</)&&(tagName=tagName.replace(/[\s<].*/,""),errorHandler.error("end tag name: "+tagName+" maybe not complete"),end=tagStart+1+tagName.length);var localNSMap=config.localNSMap,endMatch=config.tagName==tagName;if(endMatch||config.tagName&&config.tagName.toLowerCase()==tagName.toLowerCase()){if(domBuilder.endElement(config.uri,config.localName,tagName),localNSMap)for(var prefix in localNSMap)Object.prototype.hasOwnProperty.call(localNSMap,prefix)&&domBuilder.endPrefixMapping(prefix);endMatch||errorHandler.fatalError("end tag name: "+tagName+" is not match the current start tagName:"+config.tagName)}else parseStack.push(config);end++;break;case"?":locator&&position(tagStart),end=parseInstruction(source,tagStart,domBuilder);break;case"!":locator&&position(tagStart),end=parseDCC(source,tagStart,domBuilder,errorHandler);break;default:locator&&position(tagStart);var el=new ElementAttributes,currentNSMap=par
seStack[parseStack.length-1].currentNSMap,len=(end=parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler),el.length);if(!el.closed&&fixSelfClosed(source,end,el.tagName,closeMap)&&(el.closed=!0,entityMap.nbsp||errorHandler.warning("unclosed xml attribute")),locator&&len){for(var locator2=copyLocator(locator,{}),i=0;i<len;i++){var a=el[i];position(a.offset),a.locator=copyLocator(locator,{})}domBuilder.locator=locator2,appendElement$1(el,domBuilder,currentNSMap)&&parseStack.push(el),domBuilder.locator=locator}else appendElement$1(el,domBuilder,currentNSMap)&&parseStack.push(el);NAMESPACE$1.isHTML(el.uri)&&!el.closed?end=parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder):end++}}catch(e){if(e instanceof ParseError$1)throw e;errorHandler.error("element parse error: "+e),end=-1}end>start?start=end:appendText(Math.max(tagStart,start)+1)}}(source,defaultNSMap,entityMap,domBuilder,this.errorHandler),domBuilder.endDocument()}},ElementAttributes.prototype={setTagName:fun
ction(tagName){if(!tagNamePattern.test(tagName))throw new Error("invalid tagName:"+tagName);this.tagName=tagName},addValue:function(qName,value,offset){if(!tagNamePattern.test(qName))throw new Error("invalid attribute:"+qName);this.attributeNames[qName]=this.length,this[this.length++]={qName:qName,value:value,offset:offset}},length:0,getLocalName:function(i){return this[i].localName},getLocator:function(i){return this[i].locator},getQName:function(i){return this[i].qName},getURI:function(i){return this[i].uri},getValue:function(i){return this[i].value}};var sax={XMLReader:XMLReader$1,ParseError:ParseError$1},DOMImplementation=dom.DOMImplementation,NAMESPACE=conventions.NAMESPACE,ParseError=sax.ParseError,XMLReader=sax.XMLReader;function normalizeLineEndings(input){return input.replace(/\r[\n\u0085]/g,"\n").replace(/[\r\u0085\u2028]/g,"\n")}function DOMParser$1(options){this.options=options||{locator:{}}}function DOMHandler(){this.cdata=!1}function position(locator,node){node.lineNumber=locator.lineNumber,nod
e.columnNumber=locator.columnNumber}function _locator(l){if(l)return"\n@"+(l.systemId||"")+"#[line:"+l.lineNumber+",col:"+l.columnNumber+"]"}function _toString(chars,start,length){return"string"==typeof chars?chars.substr(start,length):chars.length>=start+length||start?new java.lang.String(chars,start,length)+"":chars}function appendElement(hander,node){hander.currentElement?hander.currentElement.appendChild(node):hander.doc.appendChild(node)}DOMParser$1.prototype.parseFromString=function(source,mimeType){var options=this.options,sax=new XMLReader,domBuilder=options.domBuilder||new DOMHandler,errorHandler=options.errorHandler,locator=options.locator,defaultNSMap=options.xmlns||{},isHTML=/\/x?html?$/.test(mimeType),entityMap=isHTML?entities.HTML_ENTITIES:entities.XML_ENTITIES;locator&&domBuilder.setDocumentLocator(locator),sax.errorHandler=function(errorImpl,domBuilder,locator){if(!errorImpl){if(domBuilder instanceof DOMHandler)return domBuilder;errorImpl=domBuilder}var errorHandler={},isCallback=errorImpl in
stanceof Function;function build(key){var fn=errorImpl[key];!fn&&isCallback&&(fn=2==errorImpl.length?function(msg){errorImpl(key,msg)}:errorImpl),errorHandler[key]=fn&&function(msg){fn("[xmldom "+key+"]\t"+msg+_locator(locator))}||function(){}}return locator=locator||{},build("warning"),build("error"),build("fatalError"),errorHandler}(errorHandler,domBuilder,locator),sax.domBuilder=options.domBuilder||domBuilder,isHTML&&(defaultNSMap[""]=NAMESPACE.HTML),defaultNSMap.xml=defaultNSMap.xml||NAMESPACE.XML;var normalize=options.normalizeLineEndings||normalizeLineEndings;return source&&"string"==typeof source?sax.parse(normalize(source),defaultNSMap,entityMap):sax.errorHandler.error("invalid doc source"),domBuilder.doc},DOMHandler.prototype={startDocument:function(){this.doc=(new DOMImplementation).createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(namespaceURI,localName,qName,attrs){var doc=this.doc,el=doc.createElementNS(namespaceURI,qName||localName)
,len=attrs.length;appendElement(this,el),this.currentElement=el,this.locator&&position(this.locator,el);for(var i=0;i<len;i++){namespaceURI=attrs.getURI(i);var value=attrs.getValue(i),attr=(qName=attrs.getQName(i),doc.createAttributeNS(namespaceURI,qName));this.locator&&position(attrs.getLocator(i),attr),attr.value=attr.nodeValue=value,el.setAttributeNode(attr)}},endElement:function(namespaceURI,localName,qName){var current=this.currentElement;current.tagName,this.currentElement=current.parentNode},startPrefixMapping:function(prefix,uri){},endPrefixMapping:function(prefix){},processingInstruction:function(target,data){var ins=this.doc.createProcessingInstruction(target,data);this.locator&&position(this.locator,ins),appendElement(this,ins)},ignorableWhitespace:function(ch,start,length){},characters:function(chars,start,length){if(chars=_toString.apply(this,arguments)){if(this.cdata)var charNode=this.doc.createCDATASection(chars);else charNode=this.doc.createTextNode(chars);this.currentElement?this.currentElem
ent.appendChild(charNode):/^\s*$/.test(chars)&&this.doc.appendChild(charNode),this.locator&&position(this.locator,charNode)}},skippedEntity:function(name){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(locator){(this.locator=locator)&&(locator.lineNumber=0)},comment:function(chars,start,length){chars=_toString.apply(this,arguments);var comm=this.doc.createComment(chars);this.locator&&position(this.locator,comm),appendElement(this,comm)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(name,publicId,systemId){var impl=this.doc.implementation;if(impl&&impl.createDocumentType){var dt=impl.createDocumentType(name,publicId,systemId);this.locator&&position(this.locator,dt),appendElement(this,dt),this.doc.doctype=dt}},warning:function(error){console.warn("[xmldom warning]\t"+error,_locator(this.locator))},error:function(error){console.error("[xmldom error]\t"+error,_locator(this.locator))},fatalError:function(error){throw new ParseError(error,this
.locator)}},"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,(function(key){DOMHandler.prototype[key]=function(){return null}}));var DOMParser={__DOMHandler:DOMHandler,normalizeLineEndings:normalizeLineEndings,DOMParser:DOMParser$1}.DOMParser;
/*! @name mpd-parser @version 1.3.0 @license Apache-2.0 */
const isObject=obj=>!!obj&&"object"==typeof obj,merge$1=function(){for(var _len23=arguments.length,objects=new Array(_len23),_key23=0;_key23<_len23;_key23++)objects[_key23]=arguments[_key23];return objects.reduce(((result,source)=>("object"!=typeof source||Object.keys(source).forEach((key=>{Array.isArray(result[key])&&Array.isArray(source[key])?result[key]=result[key].concat(source[key]):isObject(result[key])&&isObject(source[key])?result[key]=merge$1(result[key],source[key]):result[key]=source[key]})),result)),{})},values=o=>Object.keys(o).map((k=>o[k])),flatten=lists=>lists.reduce(((x,y)=>x.concat(y)),[]),from=list=>{if(!list.length)return[];const result=[];for(let i=0;i<list.length;i++)result.push(list[i]);return result};var errors_INVALID_NUMBER_OF_PERIOD="INVALID_NUMBER_OF_PERIOD",errors_DASH_EMPTY_MANIFEST="DASH_EMPTY_MANIFEST",errors_DASH_INVALID_XML="DASH_INVALID_XML",errors_NO_BASE_URL="NO_BASE_URL",errors_SEGMENT_TIME_UNSPECIFIED="SEGMENT_TIME_UNSPECIFIED",errors_UNSUPPORTED_UTC_TIMING_SCHEME="UNSU
PPORTED_UTC_TIMING_SCHEME";const urlTypeToSegment=_ref10=>{let{baseUrl:baseUrl="",source:source="",range:range="",indexRange:indexRange=""}=_ref10;const segment={uri:source,resolvedUri:resolveUrl$1(baseUrl||"",source)};if(range||indexRange){const ranges=(range||indexRange).split("-");let length,startRange=window.BigInt?window.BigInt(ranges[0]):parseInt(ranges[0],10),endRange=window.BigInt?window.BigInt(ranges[1]):parseInt(ranges[1],10);startRange<Number.MAX_SAFE_INTEGER&&"bigint"==typeof startRange&&(startRange=Number(startRange)),endRange<Number.MAX_SAFE_INTEGER&&"bigint"==typeof endRange&&(endRange=Number(endRange)),length="bigint"==typeof endRange||"bigint"==typeof startRange?window.BigInt(endRange)-window.BigInt(startRange)+window.BigInt(1):endRange-startRange+1,"bigint"==typeof length&&length<Number.MAX_SAFE_INTEGER&&(length=Number(length)),segment.byterange={length:length,offset:startRange}}return segment},parseEndNumber=endNumber=>(endNumber&&"number"!=typeof endNumber&&(endNumber=parseInt(endNumber,1
0)),isNaN(endNumber)?null:endNumber),segmentRange={static(attributes){const{duration:duration,timescale:timescale=1,sourceDuration:sourceDuration,periodDuration:periodDuration}=attributes,endNumber=parseEndNumber(attributes.endNumber),segmentDuration=duration/timescale;return"number"==typeof endNumber?{start:0,end:endNumber}:"number"==typeof periodDuration?{start:0,end:periodDuration/segmentDuration}:{start:0,end:sourceDuration/segmentDuration}},dynamic(attributes){const{NOW:NOW,clientOffset:clientOffset,availabilityStartTime:availabilityStartTime,timescale:timescale=1,duration:duration,periodStart:periodStart=0,minimumUpdatePeriod:minimumUpdatePeriod=0,timeShiftBufferDepth:timeShiftBufferDepth=1/0}=attributes,endNumber=parseEndNumber(attributes.endNumber),now=(NOW+clientOffset)/1e3,periodStartWC=availabilityStartTime+periodStart,periodDuration=now+minimumUpdatePeriod-periodStartWC,segmentCount=Math.ceil(periodDuration*timescale/duration),availableStart=Math.floor((now-periodStartWC-timeShiftBufferDepth)*tim
escale/duration),availableEnd=Math.floor((now-periodStartWC)*timescale/duration);return{start:Math.max(0,availableStart),end:"number"==typeof endNumber?endNumber:Math.min(segmentCount,availableEnd)}}},parseByDuration=attributes=>{const{type:type,duration:duration,timescale:timescale=1,periodDuration:periodDuration,sourceDuration:sourceDuration}=attributes,{start:start,end:end}=segmentRange[type](attributes),segments=((start,end)=>{const result=[];for(let i=start;i<end;i++)result.push(i);return result})(start,end).map((attributes=>number=>{const{duration:duration,timescale:timescale=1,periodStart:periodStart,startNumber:startNumber=1}=attributes;return{number:startNumber+number,duration:duration/timescale,timeline:periodStart,time:number*duration}})(attributes));if("static"===type){const index=segments.length-1,sectionDuration="number"==typeof periodDuration?periodDuration:sourceDuration;segments[index].duration=sectionDuration-duration/timescale*index}return segments},segmentsFromBase=attributes=>{const{base
Url:baseUrl,initialization:initialization={},sourceDuration:sourceDuration,indexRange:indexRange="",periodStart:periodStart,presentationTime:presentationTime,number:number=0,duration:duration}=attributes;if(!baseUrl)throw new Error(errors_NO_BASE_URL);const initSegment=urlTypeToSegment({baseUrl:baseUrl,source:initialization.sourceURL,range:initialization.range}),segment=urlTypeToSegment({baseUrl:baseUrl,source:baseUrl,indexRange:indexRange});if(segment.map=initSegment,duration){const segmentTimeInfo=parseByDuration(attributes);segmentTimeInfo.length&&(segment.duration=segmentTimeInfo[0].duration,segment.timeline=segmentTimeInfo[0].timeline)}else sourceDuration&&(segment.duration=sourceDuration,segment.timeline=periodStart);return segment.presentationTime=presentationTime||periodStart,segment.number=number,[segment]},addSidxSegmentsToPlaylist$1=(playlist,sidx,baseUrl)=>{const initSegment=playlist.sidx.map?playlist.sidx.map:null,sourceDuration=playlist.sidx.duration,timeline=playlist.timeline||0,sidxByteRange=
playlist.sidx.byterange,sidxEnd=sidxByteRange.offset+sidxByteRange.length,timescale=sidx.timescale,mediaReferences=sidx.references.filter((r=>1!==r.referenceType)),segments=[],type=playlist.endList?"static":"dynamic",periodStart=playlist.sidx.timeline;let startIndex,presentationTime=periodStart,number=playlist.mediaSequence||0;startIndex="bigint"==typeof sidx.firstOffset?window.BigInt(sidxEnd)+sidx.firstOffset:sidxEnd+sidx.firstOffset;for(let i=0;i<mediaReferences.length;i++){const reference=sidx.references[i],size=reference.referencedSize,duration=reference.subsegmentDuration;let endIndex;endIndex="bigint"==typeof startIndex?startIndex+window.BigInt(size)-window.BigInt(1):startIndex+size-1;const indexRange="".concat(startIndex,"-").concat(endIndex),segment=segmentsFromBase({baseUrl:baseUrl,timescale:timescale,timeline:timeline,periodStart:periodStart,presentationTime:presentationTime,number:number,duration:duration,sourceDuration:sourceDuration,indexRange:indexRange,type:type})[0];initSegment&&(segment.map=
initSegment),segments.push(segment),startIndex+="bigint"==typeof startIndex?window.BigInt(size):size,presentationTime+=duration/timescale,number++}return playlist.segments=segments,playlist},SUPPORTED_MEDIA_TYPES=["AUDIO","SUBTITLES"],getUniqueTimelineStarts=timelineStarts=>{return(lists=timelineStarts,keyFunction=_ref11=>{let{timeline:timeline}=_ref11;return timeline},values(lists.reduce(((acc,list)=>(list.forEach((el=>{acc[keyFunction(el)]=el})),acc)),{}))).sort(((a,b)=>a.timeline>b.timeline?1:-1));var lists,keyFunction},getMediaGroupPlaylists=manifest=>{let mediaGroupPlaylists=[];var master,callback;return master=manifest,callback=(properties,type,group,label)=>{mediaGroupPlaylists=mediaGroupPlaylists.concat(properties.playlists||[])},SUPPORTED_MEDIA_TYPES.forEach((function(mediaType){for(var groupKey in master.mediaGroups[mediaType])for(var labelKey in master.mediaGroups[mediaType][groupKey]){var mediaProperties=master.mediaGroups[mediaType][groupKey][labelKey];callback(mediaProperties,mediaType,groupKey
,labelKey)}})),mediaGroupPlaylists},updateMediaSequenceForPlaylist=_ref12=>{let{playlist:playlist,mediaSequence:mediaSequence}=_ref12;playlist.mediaSequence=mediaSequence,playlist.segments.forEach(((segment,index)=>{segment.number=playlist.mediaSequence+index}))},positionManifestOnTimeline=_ref15=>{let{oldManifest:oldManifest,newManifest:newManifest}=_ref15;const oldPlaylists=oldManifest.playlists.concat(getMediaGroupPlaylists(oldManifest)),newPlaylists=newManifest.playlists.concat(getMediaGroupPlaylists(newManifest));return newManifest.timelineStarts=getUniqueTimelineStarts([oldManifest.timelineStarts,newManifest.timelineStarts]),(_ref13=>{let{oldPlaylists:oldPlaylists,newPlaylists:newPlaylists,timelineStarts:timelineStarts}=_ref13;newPlaylists.forEach((playlist=>{playlist.discontinuitySequence=timelineStarts.findIndex((function(_ref14){let{timeline:timeline}=_ref14;return timeline===playlist.timeline}));const oldPlaylist=((playlists,name)=>{for(let i=0;i<playlists.length;i++)if(playlists[i].attributes.NAME
===name)return playlists[i];return null})(oldPlaylists,playlist.attributes.NAME);if(!oldPlaylist)return;if(playlist.sidx)return;const firstNewSegment=playlist.segments[0],oldMatchingSegmentIndex=oldPlaylist.segments.findIndex((function(oldSegment){return Math.abs(oldSegment.presentationTime-firstNewSegment.presentationTime)<.016666666666666666}));if(-1===oldMatchingSegmentIndex)return updateMediaSequenceForPlaylist({playlist:playlist,mediaSequence:oldPlaylist.mediaSequence+oldPlaylist.segments.length}),playlist.segments[0].discontinuity=!0,playlist.discontinuityStarts.unshift(0),void((!oldPlaylist.segments.length&&playlist.timeline>oldPlaylist.timeline||oldPlaylist.segments.length&&playlist.timeline>oldPlaylist.segments[oldPlaylist.segments.length-1].timeline)&&playlist.discontinuitySequence--);oldPlaylist.segments[oldMatchingSegmentIndex].discontinuity&&!firstNewSegment.discontinuity&&(firstNewSegment.discontinuity=!0,playlist.discontinuityStarts.unshift(0),playlist.discontinuitySequence--),updateMediaSeque
nceForPlaylist({playlist:playlist,mediaSequence:oldPlaylist.segments[oldMatchingSegmentIndex].number})}))})({oldPlaylists:oldPlaylists,newPlaylists:newPlaylists,timelineStarts:newManifest.timelineStarts}),newManifest},generateSidxKey=sidx=>sidx&&sidx.uri+"-"+(byterange=>{let endRange;return endRange="bigint"==typeof byterange.offset||"bigint"==typeof byterange.length?window.BigInt(byterange.offset)+window.BigInt(byterange.length)-window.BigInt(1):byterange.offset+byterange.length-1,"".concat(byterange.offset,"-").concat(endRange)})(sidx.byterange),mergeDiscontiguousPlaylists=playlists=>{const playlistsByBaseUrl=playlists.reduce((function(acc,cur){return acc[cur.attributes.baseUrl]||(acc[cur.attributes.baseUrl]=[]),acc[cur.attributes.baseUrl].push(cur),acc}),{});let allPlaylists=[];return Object.values(playlistsByBaseUrl).forEach((playlistGroup=>{const mergedPlaylists=values(playlistGroup.reduce(((acc,playlist)=>{const name=playlist.attributes.id+(playlist.attributes.lang||"");return acc[name]?(playlist.segme
nts&&(playlist.segments[0]&&(playlist.segments[0].discontinuity=!0),acc[name].segments.push(...playlist.segments)),playlist.attributes.contentProtection&&(acc[name].attributes.contentProtection=playlist.attributes.contentProtection)):(acc[name]=playlist,acc[name].attributes.timelineStarts=[]),acc[name].attributes.timelineStarts.push({start:playlist.attributes.periodStart,timeline:playlist.attributes.periodStart}),acc}),{}));allPlaylists=allPlaylists.concat(mergedPlaylists)})),allPlaylists.map((playlist=>{var l,key;return playlist.discontinuityStarts=(l=playlist.segments||[],key="discontinuity",l.reduce(((a,e,i)=>(e[key]&&a.push(i),a)),[])),playlist}))},addSidxSegmentsToPlaylist=(playlist,sidxMapping)=>{const sidxKey=generateSidxKey(playlist.sidx),sidxMatch=sidxKey&&sidxMapping[sidxKey]&&sidxMapping[sidxKey].sidx;return sidxMatch&&addSidxSegmentsToPlaylist$1(playlist,sidxMatch,playlist.sidx.resolvedUri),playlist},addSidxSegmentsToPlaylists=function(playlists){let sidxMapping=arguments.length>1&&void 0!==argum
ents[1]?arguments[1]:{};if(!Object.keys(sidxMapping).length)return playlists;for(const i in playlists)playlists[i]=addSidxSegmentsToPlaylist(playlists[i],sidxMapping);return playlists},formatAudioPlaylist=(_ref16,isAudioOnly)=>{let{attributes:attributes,segments:segments,sidx:sidx,mediaSequence:mediaSequence,discontinuitySequence:discontinuitySequence,discontinuityStarts:discontinuityStarts}=_ref16;const playlist={attributes:{NAME:attributes.id,BANDWIDTH:attributes.bandwidth,CODECS:attributes.codecs,"PROGRAM-ID":1},uri:"",endList:"static"===attributes.type,timeline:attributes.periodStart,resolvedUri:attributes.baseUrl||"",targetDuration:attributes.duration,discontinuitySequence:discontinuitySequence,discontinuityStarts:discontinuityStarts,timelineStarts:attributes.timelineStarts,mediaSequence:mediaSequence,segments:segments};return attributes.contentProtection&&(playlist.contentProtection=attributes.contentProtection),attributes.serviceLocation&&(playlist.attributes.serviceLocation=attributes.serviceLocation
),sidx&&(playlist.sidx=sidx),isAudioOnly&&(playlist.attributes.AUDIO="audio",playlist.attributes.SUBTITLES="subs"),playlist},formatVttPlaylist=_ref17=>{let{attributes:attributes,segments:segments,mediaSequence:mediaSequence,discontinuityStarts:discontinuityStarts,discontinuitySequence:discontinuitySequence}=_ref17;void 0===segments&&(segments=[{uri:attributes.baseUrl,timeline:attributes.periodStart,resolvedUri:attributes.baseUrl||"",duration:attributes.sourceDuration,number:0}],attributes.duration=attributes.sourceDuration);const m3u8Attributes={NAME:attributes.id,BANDWIDTH:attributes.bandwidth,"PROGRAM-ID":1};attributes.codecs&&(m3u8Attributes.CODECS=attributes.codecs);const vttPlaylist={attributes:m3u8Attributes,uri:"",endList:"static"===attributes.type,timeline:attributes.periodStart,resolvedUri:attributes.baseUrl||"",targetDuration:attributes.duration,timelineStarts:attributes.timelineStarts,discontinuityStarts:discontinuityStarts,discontinuitySequence:discontinuitySequence,mediaSequence:mediaSequence,se
gments:segments};return attributes.serviceLocation&&(vttPlaylist.attributes.serviceLocation=attributes.serviceLocation),vttPlaylist},formatVideoPlaylist=_ref18=>{let{attributes:attributes,segments:segments,sidx:sidx,discontinuityStarts:discontinuityStarts}=_ref18;const playlist={attributes:{NAME:attributes.id,AUDIO:"audio",SUBTITLES:"subs",RESOLUTION:{width:attributes.width,height:attributes.height},CODECS:attributes.codecs,BANDWIDTH:attributes.bandwidth,"PROGRAM-ID":1},uri:"",endList:"static"===attributes.type,timeline:attributes.periodStart,resolvedUri:attributes.baseUrl||"",targetDuration:attributes.duration,discontinuityStarts:discontinuityStarts,timelineStarts:attributes.timelineStarts,segments:segments};return attributes.frameRate&&(playlist.attributes["FRAME-RATE"]=attributes.frameRate),attributes.contentProtection&&(playlist.contentProtection=attributes.contentProtection),attributes.serviceLocation&&(playlist.attributes.serviceLocation=attributes.serviceLocation),sidx&&(playlist.sidx=sidx),playlist},
videoOnly=_ref19=>{let{attributes:attributes}=_ref19;return"video/mp4"===attributes.mimeType||"video/webm"===attributes.mimeType||"video"===attributes.contentType},audioOnly=_ref20=>{let{attributes:attributes}=_ref20;return"audio/mp4"===attributes.mimeType||"audio/webm"===attributes.mimeType||"audio"===attributes.contentType},vttOnly=_ref21=>{let{attributes:attributes}=_ref21;return"text/vtt"===attributes.mimeType||"text"===attributes.contentType},flattenMediaGroupPlaylists=mediaGroupObject=>mediaGroupObject?Object.keys(mediaGroupObject).reduce(((acc,label)=>{const labelContents=mediaGroupObject[label];return acc.concat(labelContents.playlists)}),[]):[],toM3u8=_ref23=>{let{dashPlaylists:dashPlaylists,locations:locations,contentSteering:contentSteering,sidxMapping:sidxMapping={},previousManifest:previousManifest,eventStream:eventStream}=_ref23;if(!dashPlaylists.length)return{};const{sourceDuration:duration,type:type,suggestedPresentationDelay:suggestedPresentationDelay,minimumUpdatePeriod:minimumUpdatePeriod}
=dashPlaylists[0].attributes,videoPlaylists=mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist),audioPlaylists=mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly)),vttPlaylists=mergeDiscontiguousPlaylists(dashPlaylists.filter(vttOnly)),captions=dashPlaylists.map((playlist=>playlist.attributes.captionServices)).filter(Boolean),manifest={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:duration,playlists:addSidxSegmentsToPlaylists(videoPlaylists,sidxMapping)};minimumUpdatePeriod>=0&&(manifest.minimumUpdatePeriod=1e3*minimumUpdatePeriod),locations&&(manifest.locations=locations),contentSteering&&(manifest.contentSteering=contentSteering),"dynamic"===type&&(manifest.suggestedPresentationDelay=suggestedPresentationDelay),eventStream&&eventStream.length>0&&(manifest.eventStream=eventStream);const isAudioOnly=0===manifest.playlists.length,organizedAudioGroup=audioPlaylists.length?fu
nction(playlists){let mainPlaylist,sidxMapping=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},isAudioOnly=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const formattedPlaylists=playlists.reduce(((a,playlist)=>{const role=playlist.attributes.role&&playlist.attributes.role.value||"",language=playlist.attributes.lang||"";let label=playlist.attributes.label||"main";if(language&&!playlist.attributes.label){const roleLabel=role?" (".concat(role,")"):"";label="".concat(playlist.attributes.lang).concat(roleLabel)}a[label]||(a[label]={language:language,autoselect:!0,default:"main"===role,playlists:[],uri:""});const formatted=addSidxSegmentsToPlaylist(formatAudioPlaylist(playlist,isAudioOnly),sidxMapping);return a[label].playlists.push(formatted),void 0===mainPlaylist&&"main"===role&&(mainPlaylist=playlist,mainPlaylist.default=!0),a}),{});mainPlaylist||(formattedPlaylists[Object.keys(formattedPlaylists)[0]].default=!0);return formattedPlaylists}(audioPlaylists,sidxMapping,isAudioOnly):null,organiz
edVttGroup=vttPlaylists.length?function(playlists){let sidxMapping=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return playlists.reduce(((a,playlist)=>{const label=playlist.attributes.label||playlist.attributes.lang||"text";return a[label]||(a[label]={language:label,default:!1,autoselect:!1,playlists:[],uri:""}),a[label].playlists.push(addSidxSegmentsToPlaylist(formatVttPlaylist(playlist),sidxMapping)),a}),{})}(vttPlaylists,sidxMapping):null,formattedPlaylists=videoPlaylists.concat(flattenMediaGroupPlaylists(organizedAudioGroup),flattenMediaGroupPlaylists(organizedVttGroup)),playlistTimelineStarts=formattedPlaylists.map((_ref24=>{let{timelineStarts:timelineStarts}=_ref24;return timelineStarts}));var playlists,timelineStarts;return manifest.timelineStarts=getUniqueTimelineStarts(playlistTimelineStarts),playlists=formattedPlaylists,timelineStarts=manifest.timelineStarts,playlists.forEach((playlist=>{playlist.mediaSequence=0,playlist.discontinuitySequence=timelineStarts.findIndex((function(_ref22){
let{timeline:timeline}=_ref22;return timeline===playlist.timeline})),playlist.segments&&playlist.segments.forEach(((segment,index)=>{segment.number=index}))})),organizedAudioGroup&&(manifest.mediaGroups.AUDIO.audio=organizedAudioGroup),organizedVttGroup&&(manifest.mediaGroups.SUBTITLES.subs=organizedVttGroup),captions.length&&(manifest.mediaGroups["CLOSED-CAPTIONS"].cc=captions.reduce(((svcObj,svc)=>svc?(svc.forEach((service=>{const{channel:channel,language:language}=service;svcObj[language]={autoselect:!1,default:!1,instreamId:channel,language:language},service.hasOwnProperty("aspectRatio")&&(svcObj[language].aspectRatio=service.aspectRatio),service.hasOwnProperty("easyReader")&&(svcObj[language].easyReader=service.easyReader),service.hasOwnProperty("3D")&&(svcObj[language]["3D"]=service["3D"])})),svcObj):svcObj),{})),previousManifest?positionManifestOnTimeline({oldManifest:previousManifest,newManifest:manifest}):manifest},getLiveRValue=(attributes,time,duration)=>{const{NOW:NOW,clientOffset:clientOffset,av
ailabilityStartTime:availabilityStartTime,timescale:timescale=1,periodStart:periodStart=0,minimumUpdatePeriod:minimumUpdatePeriod=0}=attributes,periodDuration=(NOW+clientOffset)/1e3+minimumUpdatePeriod-(availabilityStartTime+periodStart);return Math.ceil((periodDuration*timescale-time)/duration)},parseByTimeline=(attributes,segmentTimeline)=>{const{type:type,minimumUpdatePeriod:minimumUpdatePeriod=0,media:media="",sourceDuration:sourceDuration,timescale:timescale=1,startNumber:startNumber=1,periodStart:timeline}=attributes,segments=[];let time=-1;for(let sIndex=0;sIndex<segmentTimeline.length;sIndex++){const S=segmentTimeline[sIndex],duration=S.d,repeat=S.r||0,segmentTime=S.t||0;let count;if(time<0&&(time=segmentTime),segmentTime&&segmentTime>time&&(time=segmentTime),repeat<0){const nextS=sIndex+1;count=nextS===segmentTimeline.length?"dynamic"===type&&minimumUpdatePeriod>0&&media.indexOf("$Number$")>0?getLiveRValue(attributes,time,duration):(sourceDuration*timescale-time)/duration:(segmentTimeline[nextS].t-t
ime)/duration}else count=repeat+1;const end=startNumber+segments.length+count;let number=startNumber+segments.length;for(;number<end;)segments.push({number:number,duration:duration/timescale,time:time,timeline:timeline}),time+=duration,number++}return segments},identifierPattern=/\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g,constructTemplateUrl=(url,values)=>url.replace(identifierPattern,(values=>(match,identifier,format,width)=>{if("$$"===match)return"$";if(void 0===values[identifier])return match;const value=""+values[identifier];return"RepresentationID"===identifier?value:(width=format?parseInt(width,10):1,value.length>=width?value:"".concat(new Array(width-value.length+1).join("0")).concat(value))})(values)),segmentsFromTemplate=(attributes,segmentTimeline)=>{const templateValues={RepresentationID:attributes.id,Bandwidth:attributes.bandwidth||0},{initialization:initialization={sourceURL:"",range:""}}=attributes,mapSegment=urlTypeToSegment({baseUrl:attributes.baseUrl,source:constructTemplateUrl(initialization.sourceU
RL,templateValues),range:initialization.range}),segments=((attributes,segmentTimeline)=>attributes.duration||segmentTimeline?attributes.duration?parseByDuration(attributes):parseByTimeline(attributes,segmentTimeline):[{number:attributes.startNumber||1,duration:attributes.sourceDuration,time:0,timeline:attributes.periodStart}])(attributes,segmentTimeline);return segments.map((segment=>{templateValues.Number=segment.number,templateValues.Time=segment.time;const uri=constructTemplateUrl(attributes.media||"",templateValues),timescale=attributes.timescale||1,presentationTimeOffset=attributes.presentationTimeOffset||0,presentationTime=attributes.periodStart+(segment.time-presentationTimeOffset)/timescale;return{uri:uri,timeline:segment.timeline,duration:segment.duration,resolvedUri:resolveUrl$1(attributes.baseUrl||"",uri),map:mapSegment,number:segment.number,presentationTime:presentationTime}}))},segmentsFromList=(attributes,segmentTimeline)=>{const{duration:duration,segmentUrls:segmentUrls=[],periodStart:periodSt
art}=attributes;if(!duration&&!segmentTimeline||duration&&segmentTimeline)throw new Error(errors_SEGMENT_TIME_UNSPECIFIED);const segmentUrlMap=segmentUrls.map((segmentUrlObject=>((attributes,segmentUrl)=>{const{baseUrl:baseUrl,initialization:initialization={}}=attributes,initSegment=urlTypeToSegment({baseUrl:baseUrl,source:initialization.sourceURL,range:initialization.range}),segment=urlTypeToSegment({baseUrl:baseUrl,source:segmentUrl.media,range:segmentUrl.mediaRange});return segment.map=initSegment,segment})(attributes,segmentUrlObject)));let segmentTimeInfo;duration&&(segmentTimeInfo=parseByDuration(attributes)),segmentTimeline&&(segmentTimeInfo=parseByTimeline(attributes,segmentTimeline));return segmentTimeInfo.map(((segmentTime,index)=>{if(segmentUrlMap[index]){const segment=segmentUrlMap[index],timescale=attributes.timescale||1,presentationTimeOffset=attributes.presentationTimeOffset||0;return segment.timeline=segmentTime.timeline,segment.duration=segmentTime.duration,segment.number=segmentTime.number,
segment.presentationTime=periodStart+(segmentTime.time-presentationTimeOffset)/timescale,segment}})).filter((segment=>segment))},generateSegments=_ref25=>{let segmentAttributes,segmentsFn,{attributes:attributes,segmentInfo:segmentInfo}=_ref25;segmentInfo.template?(segmentsFn=segmentsFromTemplate,segmentAttributes=merge$1(attributes,segmentInfo.template)):segmentInfo.base?(segmentsFn=segmentsFromBase,segmentAttributes=merge$1(attributes,segmentInfo.base)):segmentInfo.list&&(segmentsFn=segmentsFromList,segmentAttributes=merge$1(attributes,segmentInfo.list));const segmentsInfo={attributes:attributes};if(!segmentsFn)return segmentsInfo;const segments=segmentsFn(segmentAttributes,segmentInfo.segmentTimeline);if(segmentAttributes.duration){const{duration:duration,timescale:timescale=1}=segmentAttributes;segmentAttributes.duration=duration/timescale}else segments.length?segmentAttributes.duration=segments.reduce(((max,segment)=>Math.max(max,Math.ceil(segment.duration))),0):segmentAttributes.duration=0;return segmen
tsInfo.attributes=segmentAttributes,segmentsInfo.segments=segments,segmentInfo.base&&segmentAttributes.indexRange&&(segmentsInfo.sidx=segments[0],segmentsInfo.segments=[]),segmentsInfo},toPlaylists=representations=>representations.map(generateSegments),findChildren=(element,name)=>from(element.childNodes).filter((_ref26=>{let{tagName:tagName}=_ref26;return tagName===name})),getContent=element=>element.textContent.trim(),parseDuration=str=>{const match=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(str);if(!match)return 0;const[year,month,day,hour,minute,second]=match.slice(1);return 31536e3*parseFloat(year||0)+2592e3*parseFloat(month||0)+86400*parseFloat(day||0)+3600*parseFloat(hour||0)+60*parseFloat(minute||0)+parseFloat(second||0)},parsers={mediaPresentationDuration:value=>parseDuration(value),availabilityStartTime(value){return/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(str=value)&&(str+="Z"),Date.parse(str)/1e3;var str},minimumUpdatePeriod:value=>parseDuration(value),sug
gestedPresentationDelay:value=>parseDuration(value),type:value=>value,timeShiftBufferDepth:value=>parseDuration(value),start:value=>parseDuration(value),width:value=>parseInt(value,10),height:value=>parseInt(value,10),bandwidth:value=>parseInt(value,10),frameRate:value=>(value=>parseFloat(value.split("/").reduce(((prev,current)=>prev/current))))(value),startNumber:value=>parseInt(value,10),timescale:value=>parseInt(value,10),presentationTimeOffset:value=>parseInt(value,10),duration(value){const parsedValue=parseInt(value,10);return isNaN(parsedValue)?parseDuration(value):parsedValue},d:value=>parseInt(value,10),t:value=>parseInt(value,10),r:value=>parseInt(value,10),presentationTime:value=>parseInt(value,10),DEFAULT:value=>value},parseAttributes=el=>el&&el.attributes?from(el.attributes).reduce(((a,e)=>{const parseFn=parsers[e.name]||parsers.DEFAULT;return a[e.name]=parseFn(e.value),a}),{}):{},keySystemsMap={"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27
dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb":"com.adobe.primetime","urn:mpeg:dash:mp4protection:2011":"mp4protection"},buildBaseUrls=(references,baseUrlElements)=>baseUrlElements.length?flatten(references.map((function(reference){return baseUrlElements.map((function(baseUrlElement){const initialBaseUrl=getContent(baseUrlElement),resolvedBaseUrl=resolveUrl$1(reference.baseUrl,initialBaseUrl),finalBaseUrl=merge$1(parseAttributes(baseUrlElement),{baseUrl:resolvedBaseUrl});return resolvedBaseUrl!==initialBaseUrl&&!finalBaseUrl.serviceLocation&&reference.serviceLocation&&(finalBaseUrl.serviceLocation=reference.serviceLocation),finalBaseUrl}))}))):references,getSegmentInformation=adaptationSet=>{const segmentTemplate=findChildren(adaptationSet,"SegmentTemplate")[0],segmentList=findChildren(adaptationSet,"SegmentList")[0],segmentUrls=segmentList&&findChildren(segmentList,"SegmentURL").map((s=>merge$1({tag:"
SegmentURL"},parseAttributes(s)))),segmentBase=findChildren(adaptationSet,"SegmentBase")[0],segmentTimelineParentNode=segmentList||segmentTemplate,segmentTimeline=segmentTimelineParentNode&&findChildren(segmentTimelineParentNode,"SegmentTimeline")[0],segmentInitializationParentNode=segmentList||segmentBase||segmentTemplate,segmentInitialization=segmentInitializationParentNode&&findChildren(segmentInitializationParentNode,"Initialization")[0],template=segmentTemplate&&parseAttributes(segmentTemplate);template&&segmentInitialization?template.initialization=segmentInitialization&&parseAttributes(segmentInitialization):template&&template.initialization&&(template.initialization={sourceURL:template.initialization});const segmentInfo={template:template,segmentTimeline:segmentTimeline&&findChildren(segmentTimeline,"S").map((s=>parseAttributes(s))),list:segmentList&&merge$1(parseAttributes(segmentList),{segmentUrls:segmentUrls,initialization:parseAttributes(segmentInitialization)}),base:segmentBase&&merge$1(parseAtt
ributes(segmentBase),{initialization:parseAttributes(segmentInitialization)})};return Object.keys(segmentInfo).forEach((key=>{segmentInfo[key]||delete segmentInfo[key]})),segmentInfo},toEventStream=period=>flatten(findChildren(period.node,"EventStream").map((eventStream=>{const eventStreamAttributes=parseAttributes(eventStream),schemeIdUri=eventStreamAttributes.schemeIdUri;return findChildren(eventStream,"Event").map((event=>{const eventAttributes=parseAttributes(event),presentationTime=eventAttributes.presentationTime||0,timescale=eventStreamAttributes.timescale||1,duration=eventAttributes.duration||0,start=presentationTime/timescale+period.attributes.start;return{schemeIdUri:schemeIdUri,value:eventStreamAttributes.value,id:eventAttributes.id,start:start,end:start+duration/timescale,messageData:getContent(event)||eventAttributes.messageData,contentEncoding:eventStreamAttributes.contentEncoding,presentationTimeOffset:eventStreamAttributes.presentationTimeOffset||0}}))}))),toRepresentations=(periodAttributes,
periodBaseUrls,periodSegmentInfo)=>adaptationSet=>{const adaptationSetAttributes=parseAttributes(adaptationSet),adaptationSetBaseUrls=buildBaseUrls(periodBaseUrls,findChildren(adaptationSet,"BaseURL")),role=findChildren(adaptationSet,"Role")[0],roleAttributes={role:parseAttributes(role)};let attrs=merge$1(periodAttributes,adaptationSetAttributes,roleAttributes);const accessibility=findChildren(adaptationSet,"Accessibility")[0],captionServices=(service=>{if("urn:scte:dash:cc:cea-608:2015"===service.schemeIdUri)return("string"!=typeof service.value?[]:service.value.split(";")).map((value=>{let channel,language;return language=value,/^CC\d=/.test(value)?[channel,language]=value.split("="):/^CC\d$/.test(value)&&(channel=value),{channel:channel,language:language}}));if("urn:scte:dash:cc:cea-708:2015"===service.schemeIdUri)return("string"!=typeof service.value?[]:service.value.split(";")).map((value=>{const flags={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(value)){const[channel,o
pts=""]=value.split("=");flags.channel=channel,flags.language=value,opts.split(",").forEach((opt=>{const[name,val]=opt.split(":");"lang"===name?flags.language=val:"er"===name?flags.easyReader=Number(val):"war"===name?flags.aspectRatio=Number(val):"3D"===name&&(flags["3D"]=Number(val))}))}else flags.language=value;return flags.channel&&(flags.channel="SERVICE"+flags.channel),flags}))})(parseAttributes(accessibility));captionServices&&(attrs=merge$1(attrs,{captionServices:captionServices}));const label=findChildren(adaptationSet,"Label")[0];if(label&&label.childNodes.length){const labelVal=label.childNodes[0].nodeValue.trim();attrs=merge$1(attrs,{label:labelVal})}const contentProtection=findChildren(adaptationSet,"ContentProtection").reduce(((acc,node)=>{const attributes=parseAttributes(node);attributes.schemeIdUri&&(attributes.schemeIdUri=attributes.schemeIdUri.toLowerCase());const keySystem=keySystemsMap[attributes.schemeIdUri];if(keySystem){acc[keySystem]={attributes:attributes};const psshNode=findChildren(
node,"cenc:pssh")[0];if(psshNode){const pssh=getContent(psshNode);acc[keySystem].pssh=pssh&&decodeB64ToUint8Array(pssh)}}return acc}),{});Object.keys(contentProtection).length&&(attrs=merge$1(attrs,{contentProtection:contentProtection}));const segmentInfo=getSegmentInformation(adaptationSet),representations=findChildren(adaptationSet,"Representation"),adaptationSetSegmentInfo=merge$1(periodSegmentInfo,segmentInfo);return flatten(representations.map(((adaptationSetAttributes,adaptationSetBaseUrls,adaptationSetSegmentInfo)=>representation=>{const repBaseUrlElements=findChildren(representation,"BaseURL"),repBaseUrls=buildBaseUrls(adaptationSetBaseUrls,repBaseUrlElements),attributes=merge$1(adaptationSetAttributes,parseAttributes(representation)),representationSegmentInfo=getSegmentInformation(representation);return repBaseUrls.map((baseUrl=>({segmentInfo:merge$1(adaptationSetSegmentInfo,representationSegmentInfo),attributes:merge$1(attributes,baseUrl)})))})(attrs,adaptationSetBaseUrls,adaptationSetSegmentInfo))
)},toAdaptationSets=(mpdAttributes,mpdBaseUrls)=>(period,index)=>{const periodBaseUrls=buildBaseUrls(mpdBaseUrls,findChildren(period.node,"BaseURL")),periodAttributes=merge$1(mpdAttributes,{periodStart:period.attributes.start});"number"==typeof period.attributes.duration&&(periodAttributes.periodDuration=period.attributes.duration);const adaptationSets=findChildren(period.node,"AdaptationSet"),periodSegmentInfo=getSegmentInformation(period.node);return flatten(adaptationSets.map(toRepresentations(periodAttributes,periodBaseUrls,periodSegmentInfo)))},generateContentSteeringInformation=(contentSteeringNodes,eventHandler)=>{if(contentSteeringNodes.length>1&&eventHandler({type:"warn",message:"The MPD manifest should contain no more than one ContentSteering tag"}),!contentSteeringNodes.length)return null;const infoFromContentSteeringTag=merge$1({serverURL:getContent(contentSteeringNodes[0])},parseAttributes(contentSteeringNodes[0]));return infoFromContentSteeringTag.queryBeforeStart="true"===infoFromContentSteeri
ngTag.queryBeforeStart,infoFromContentSteeringTag},getPeriodStart=_ref27=>{let{attributes:attributes,priorPeriodAttributes:priorPeriodAttributes,mpdType:mpdType}=_ref27;return"number"==typeof attributes.start?attributes.start:priorPeriodAttributes&&"number"==typeof priorPeriodAttributes.start&&"number"==typeof priorPeriodAttributes.duration?priorPeriodAttributes.start+priorPeriodAttributes.duration:priorPeriodAttributes||"static"!==mpdType?null:0},inheritAttributes=function(mpd){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{manifestUri:manifestUri="",NOW:NOW=Date.now(),clientOffset:clientOffset=0,eventHandler:eventHandler=function(){}}=options,periodNodes=findChildren(mpd,"Period");if(!periodNodes.length)throw new Error(errors_INVALID_NUMBER_OF_PERIOD);const locations=findChildren(mpd,"Location"),mpdAttributes=parseAttributes(mpd),mpdBaseUrls=buildBaseUrls([{baseUrl:manifestUri}],findChildren(mpd,"BaseURL")),contentSteeringNodes=findChildren(mpd,"ContentSteering");mpdAttributes.
type=mpdAttributes.type||"static",mpdAttributes.sourceDuration=mpdAttributes.mediaPresentationDuration||0,mpdAttributes.NOW=NOW,mpdAttributes.clientOffset=clientOffset,locations.length&&(mpdAttributes.locations=locations.map(getContent));const periods=[];return periodNodes.forEach(((node,index)=>{const attributes=parseAttributes(node),priorPeriod=periods[index-1];attributes.start=getPeriodStart({attributes:attributes,priorPeriodAttributes:priorPeriod?priorPeriod.attributes:null,mpdType:mpdAttributes.type}),periods.push({node:node,attributes:attributes})})),{locations:mpdAttributes.locations,contentSteeringInfo:generateContentSteeringInformation(contentSteeringNodes,eventHandler),representationInfo:flatten(periods.map(toAdaptationSets(mpdAttributes,mpdBaseUrls))),eventStream:flatten(periods.map(toEventStream))}},stringToMpdXml=manifestString=>{if(""===manifestString)throw new Error(errors_DASH_EMPTY_MANIFEST);const parser=new DOMParser;let xml,mpd;try{xml=parser.parseFromString(manifestString,"application/xml
"),mpd=xml&&"MPD"===xml.documentElement.tagName?xml.documentElement:null}catch(e){}if(!mpd||mpd&&mpd.getElementsByTagName("parsererror").length>0)throw new Error(errors_DASH_INVALID_XML);return mpd},parseUTCTiming=manifestString=>(mpd=>{const UTCTimingNode=findChildren(mpd,"UTCTiming")[0];if(!UTCTimingNode)return null;const attributes=parseAttributes(UTCTimingNode);switch(attributes.schemeIdUri){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":attributes.method="HEAD";break;case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":attributes.method="GET";break;case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":attributes.method="DIRECT",attributes.value=Date.parse(attributes.value);break;default:throw new Error(errors_UNSUPPORTED_UTC_TIMING_SCHEME)}return attributes})(stringToMpdXml(manifestString));var MAX_UINT32=Math.pow(2,32),getUint64=function(uint8){var va
lue,dv=new DataView(uint8.buffer,uint8.byteOffset,uint8.byteLength);return dv.getBigUint64?(value=dv.getBigUint64(0))<Number.MAX_SAFE_INTEGER?Number(value):value:dv.getUint32(0)*MAX_UINT32+dv.getUint32(4)},parseSidx_1=function(data){var view=new DataView(data.buffer,data.byteOffset,data.byteLength),result={version:data[0],flags:new Uint8Array(data.subarray(1,4)),references:[],referenceId:view.getUint32(4),timescale:view.getUint32(8)},i=12;0===result.version?(result.earliestPresentationTime=view.getUint32(i),result.firstOffset=view.getUint32(i+4),i+=8):(result.earliestPresentationTime=getUint64(data.subarray(i)),result.firstOffset=getUint64(data.subarray(i+8)),i+=16),i+=2;var referenceCount=view.getUint16(i);for(i+=2;referenceCount>0;i+=12,referenceCount--)result.references.push({referenceType:(128&data[i])>>>7,referencedSize:2147483647&view.getUint32(i),subsegmentDuration:view.getUint32(i+4),startsWithSap:!!(128&data[i+8]),sapType:(112&data[i+8])>>>4,sapDeltaTime:268435455&view.getUint32(i+8)});return result
},ID3=toUint8([73,68,51]),getId3Offset=function getId3Offset(bytes,offset){return void 0===offset&&(offset=0),(bytes=toUint8(bytes)).length-offset<10||!bytesMatch(bytes,ID3,{offset:offset})?offset:(offset+=function(bytes,offset){void 0===offset&&(offset=0);var flags=(bytes=toUint8(bytes))[offset+5],returnSize=bytes[offset+6]<<21|bytes[offset+7]<<14|bytes[offset+8]<<7|bytes[offset+9];return(16&flags)>>4?returnSize+20:returnSize+10}(bytes,offset),getId3Offset(bytes,offset))},normalizePath$1=function(path){return"string"==typeof path?stringToBytes(path):path},findBox=function findBox(bytes,paths,complete){void 0===complete&&(complete=!1),paths=function(paths){return Array.isArray(paths)?paths.map((function(p){return normalizePath$1(p)})):[normalizePath$1(paths)]}(paths),bytes=toUint8(bytes);var results=[];if(!paths.length)return results;for(var i=0;i<bytes.length;){var size=(bytes[i]<<24|bytes[i+1]<<16|bytes[i+2]<<8|bytes[i+3])>>>0,type=bytes.subarray(i+4,i+8);if(0===size)break;var end=i+size;if(end>bytes.lengt
h){if(complete)break;end=bytes.length}var data=bytes.subarray(i+8,end);bytesMatch(type,paths[0])&&(1===paths.length?results.push(data):results.push.apply(results,findBox(data,paths.slice(1),complete))),i=end}return results},EBML_TAGS={EBML:toUint8([26,69,223,163]),DocType:toUint8([66,130]),Segment:toUint8([24,83,128,103]),SegmentInfo:toUint8([21,73,169,102]),Tracks:toUint8([22,84,174,107]),Track:toUint8([174]),TrackNumber:toUint8([215]),DefaultDuration:toUint8([35,227,131]),TrackEntry:toUint8([174]),TrackType:toUint8([131]),FlagDefault:toUint8([136]),CodecID:toUint8([134]),CodecPrivate:toUint8([99,162]),VideoTrack:toUint8([224]),AudioTrack:toUint8([225]),Cluster:toUint8([31,67,182,117]),Timestamp:toUint8([231]),TimestampScale:toUint8([42,215,177]),BlockGroup:toUint8([160]),BlockDuration:toUint8([155]),Block:toUint8([161]),SimpleBlock:toUint8([163])},LENGTH_TABLE=[128,64,32,16,8,4,2,1],getvint=function(bytes,offset,removeLength,signed){void 0===removeLength&&(removeLength=!0),void 0===signed&&(signed=!1);var
length=function(byte){for(var len=1,i=0;i<LENGTH_TABLE.length&&!(byte&LENGTH_TABLE[i]);i++)len++;return len}(bytes[offset]),valueBytes=bytes.subarray(offset,offset+length);return removeLength&&((valueBytes=Array.prototype.slice.call(bytes,offset,offset+length))[0]^=LENGTH_TABLE[length-1]),{length:length,value:bytesToNumber(valueBytes,{signed:signed}),bytes:valueBytes}},normalizePath=function normalizePath(path){return"string"==typeof path?path.match(/.{1,2}/g).map((function(p){return normalizePath(p)})):"number"==typeof path?numberToBytes(path):path},getInfinityDataSize=function getInfinityDataSize(id,bytes,offset){if(offset>=bytes.length)return bytes.length;var innerid=getvint(bytes,offset,!1);if(bytesMatch(id.bytes,innerid.bytes))return offset;var dataHeader=getvint(bytes,offset+innerid.length);return getInfinityDataSize(id,bytes,offset+dataHeader.length+dataHeader.value+innerid.length)},findEbml=function findEbml(bytes,paths){paths=function(paths){return Array.isArray(paths)?paths.map((function(p){return
normalizePath(p)})):[normalizePath(paths)]}(paths),bytes=toUint8(bytes);var results=[];if(!paths.length)return results;for(var i=0;i<bytes.length;){var id=getvint(bytes,i,!1),dataHeader=getvint(bytes,i+id.length),dataStart=i+id.length+dataHeader.length;127===dataHeader.value&&(dataHeader.value=getInfinityDataSize(id,bytes,dataStart),dataHeader.value!==bytes.length&&(dataHeader.value-=dataStart));var dataEnd=dataStart+dataHeader.value>bytes.length?bytes.length:dataStart+dataHeader.value,data=bytes.subarray(dataStart,dataEnd);bytesMatch(paths[0],id.bytes)&&(1===paths.length?results.push(data):results=results.concat(findEbml(data,paths.slice(1)))),i+=id.length+dataHeader.length+data.length}return results},NAL_TYPE_ONE=toUint8([0,0,0,1]),NAL_TYPE_TWO=toUint8([0,0,1]),EMULATION_PREVENTION=toUint8([0,0,3]),discardEmulationPreventionBytes=function(bytes){for(var positions=[],i=1;i<bytes.length-2;)bytesMatch(bytes.subarray(i,i+3),EMULATION_PREVENTION)&&(positions.push(i+2),i++),i++;if(0===positions.length)return byt
es;var newLength=bytes.length-positions.length,newData=new Uint8Array(newLength),sourceIndex=0;for(i=0;i<newLength;sourceIndex++,i++)sourceIndex===positions[0]&&(sourceIndex++,positions.shift()),newData[i]=bytes[sourceIndex];return newData},findNal=function(bytes,dataType,types,nalLimit){void 0===nalLimit&&(nalLimit=1/0),bytes=toUint8(bytes),types=[].concat(types);for(var nalStart,i=0,nalsFound=0;i<bytes.length&&(nalsFound<nalLimit||nalStart);){var nalOffset=void 0;if(bytesMatch(bytes.subarray(i),NAL_TYPE_ONE)?nalOffset=4:bytesMatch(bytes.subarray(i),NAL_TYPE_TWO)&&(nalOffset=3),nalOffset){if(nalsFound++,nalStart)return discardEmulationPreventionBytes(bytes.subarray(nalStart,i));var nalType=void 0;"h264"===dataType?nalType=31&bytes[i+nalOffset]:"h265"===dataType&&(nalType=bytes[i+nalOffset]>>1&63),-1!==types.indexOf(nalType)&&(nalStart=i+nalOffset),i+=nalOffset+("h264"===dataType?1:2)}else i++}return bytes.subarray(0,0)},CONSTANTS={webm:toUint8([119,101,98,109]),matroska:toUint8([109,97,116,114,111,115,107,9
7]),flac:toUint8([102,76,97,67]),ogg:toUint8([79,103,103,83]),ac3:toUint8([11,119]),riff:toUint8([82,73,70,70]),avi:toUint8([65,86,73]),wav:toUint8([87,65,86,69]),"3gp":toUint8([102,116,121,112,51,103]),mp4:toUint8([102,116,121,112]),fmp4:toUint8([115,116,121,112]),mov:toUint8([102,116,121,112,113,116]),moov:toUint8([109,111,111,118]),moof:toUint8([109,111,111,102])},_isLikely={aac:function(bytes){var offset=getId3Offset(bytes);return bytesMatch(bytes,[255,16],{offset:offset,mask:[255,22]})},mp3:function(bytes){var offset=getId3Offset(bytes);return bytesMatch(bytes,[255,2],{offset:offset,mask:[255,6]})},webm:function(bytes){var docType=findEbml(bytes,[EBML_TAGS.EBML,EBML_TAGS.DocType])[0];return bytesMatch(docType,CONSTANTS.webm)},mkv:function(bytes){var docType=findEbml(bytes,[EBML_TAGS.EBML,EBML_TAGS.DocType])[0];return bytesMatch(docType,CONSTANTS.matroska)},mp4:function(bytes){return!_isLikely["3gp"](bytes)&&!_isLikely.mov(bytes)&&(!(!bytesMatch(bytes,CONSTANTS.mp4,{offset:4})&&!bytesMatch(bytes,CONSTANT
S.fmp4,{offset:4}))||(!(!bytesMatch(bytes,CONSTANTS.moof,{offset:4})&&!bytesMatch(bytes,CONSTANTS.moov,{offset:4}))||void 0))},mov:function(bytes){return bytesMatch(bytes,CONSTANTS.mov,{offset:4})},"3gp":function(bytes){return bytesMatch(bytes,CONSTANTS["3gp"],{offset:4})},ac3:function(bytes){var offset=getId3Offset(bytes);return bytesMatch(bytes,CONSTANTS.ac3,{offset:offset})},ts:function(bytes){if(bytes.length<189&&bytes.length>=1)return 71===bytes[0];for(var i=0;i+188<bytes.length&&i<188;){if(71===bytes[i]&&71===bytes[i+188])return!0;i+=1}return!1},flac:function(bytes){var offset=getId3Offset(bytes);return bytesMatch(bytes,CONSTANTS.flac,{offset:offset})},ogg:function(bytes){return bytesMatch(bytes,CONSTANTS.ogg)},avi:function(bytes){return bytesMatch(bytes,CONSTANTS.riff)&&bytesMatch(bytes,CONSTANTS.avi,{offset:8})},wav:function(bytes){return bytesMatch(bytes,CONSTANTS.riff)&&bytesMatch(bytes,CONSTANTS.wav,{offset:8})},h264:function(bytes){return function(bytes,type,nalLimit){return findNal(bytes,"h264",
type,nalLimit)}(bytes,7,3).length},h265:function(bytes){return function(bytes,type,nalLimit){return findNal(bytes,"h265",type,nalLimit)}(bytes,[32,33],3).length}},isLikelyTypes=Object.keys(_isLikely).filter((function(t){return"ts"!==t&&"h264"!==t&&"h265"!==t})).concat(["ts","h264","h265"]);isLikelyTypes.forEach((function(type){var isLikelyFn=_isLikely[type];_isLikely[type]=function(bytes){return isLikelyFn(toUint8(bytes))}}));var secondsToVideoTs,secondsToAudioTs,videoTsToSeconds,audioTsToSeconds,isLikely=_isLikely,detectContainerForBytes=function(bytes){bytes=toUint8(bytes);for(var i=0;i<isLikelyTypes.length;i++){var type=isLikelyTypes[i];if(isLikely[type](bytes))return type}return""};secondsToVideoTs=function(seconds){return 9e4*seconds},secondsToAudioTs=function(seconds,sampleRate){return seconds*sampleRate},videoTsToSeconds=function(timestamp){return timestamp/9e4},audioTsToSeconds=function(timestamp,sampleRate){return timestamp/sampleRate};var clock_1=9e4;
/*! @name @videojs/http-streaming @version 3.10.0 @license Apache-2.0 */
const resolveUrl=resolveUrl$1,resolveManifestRedirect=(url,req)=>req&&req.responseURL&&url!==req.responseURL?req.responseURL:url,logger=source=>videojs.log.debug?videojs.log.debug.bind(videojs,"VHS:","".concat(source," >")):function(){};function merge(){const context=videojs.obj||videojs,fn=context.merge||context.mergeOptions;for(var _len24=arguments.length,args=new Array(_len24),_key24=0;_key24<_len24;_key24++)args[_key24]=arguments[_key24];return fn.apply(context,args)}function createTimeRanges(){const context=videojs.time||videojs,fn=context.createTimeRanges||context.createTimeRanges;for(var _len25=arguments.length,args=new Array(_len25),_key25=0;_key25<_len25;_key25++)args[_key25]=arguments[_key25];return fn.apply(context,args)}const filterRanges=function(timeRanges,predicate){const results=[];let i;if(timeRanges&&timeRanges.length)for(i=0;i<timeRanges.length;i++)predicate(timeRanges.start(i),timeRanges.end(i))&&results.push([timeRanges.start(i),timeRanges.end(i)]);return createTimeRanges(results)},findR
ange=function(buffered,time){return filterRanges(buffered,(function(start,end){return start-.1<=time&&end+.1>=time}))},findNextRange=function(timeRanges,time){return filterRanges(timeRanges,(function(start){return start-.03333333333333333>=time}))},printableRange=range=>{const strArr=[];if(!range||!range.length)return"";for(let i=0;i<range.length;i++)strArr.push(range.start(i)+" => "+range.end(i));return strArr.join(", ")},timeRangesToArray=timeRanges=>{const timeRangesList=[];for(let i=0;i<timeRanges.length;i++)timeRangesList.push({start:timeRanges.start(i),end:timeRanges.end(i)});return timeRangesList},lastBufferedEnd=function(a){if(a&&a.length&&a.end)return a.end(a.length-1)},timeAheadOf=function(range,startTime){let time=0;if(!range||!range.length)return time;for(let i=0;i<range.length;i++){const start=range.start(i),end=range.end(i);startTime>end||(time+=startTime>start&&startTime<=end?end-startTime:end-start)}return time},segmentDurationWithParts=(playlist,segment)=>{if(!segment.preload)return segment.
duration;let result=0;return(segment.parts||[]).forEach((function(p){result+=p.duration})),(segment.preloadHints||[]).forEach((function(p){"PART"===p.type&&(result+=playlist.partTargetDuration)})),result},getPartsAndSegments=playlist=>(playlist.segments||[]).reduce(((acc,segment,si)=>(segment.parts?segment.parts.forEach((function(part,pi){acc.push({duration:part.duration,segmentIndex:si,partIndex:pi,part:part,segment:segment})})):acc.push({duration:segment.duration,segmentIndex:si,partIndex:null,segment:segment,part:null}),acc)),[]),getLastParts=media=>{const lastSegment=media.segments&&media.segments.length&&media.segments[media.segments.length-1];return lastSegment&&lastSegment.parts||[]},getKnownPartCount=_ref28=>{let{preloadSegment:preloadSegment}=_ref28;if(!preloadSegment)return;const{parts:parts,preloadHints:preloadHints}=preloadSegment;let partCount=(preloadHints||[]).reduce(((count,hint)=>count+("PART"===hint.type?1:0)),0);return partCount+=parts&&parts.length?parts.length:0,partCount},liveEdgeDelay=
(main,media)=>{if(media.endList)return 0;if(main&&main.suggestedPresentationDelay)return main.suggestedPresentationDelay;const hasParts=getLastParts(media).length>0;return hasParts&&media.serverControl&&media.serverControl.partHoldBack?media.serverControl.partHoldBack:hasParts&&media.partTargetDuration?3*media.partTargetDuration:media.serverControl&&media.serverControl.holdBack?media.serverControl.holdBack:media.targetDuration?3*media.targetDuration:0},intervalDuration=function(playlist,endSequence,expired){if(void 0===endSequence&&(endSequence=playlist.mediaSequence+playlist.segments.length),endSequence<playlist.mediaSequence)return 0;const backward=function(playlist,endSequence){let result=0,i=endSequence-playlist.mediaSequence,segment=playlist.segments[i];if(segment){if(void 0!==segment.start)return{result:segment.start,precise:!0};if(void 0!==segment.end)return{result:segment.end-segment.duration,precise:!0}}for(;i--;){if(segment=playlist.segments[i],void 0!==segment.end)return{result:result+segment.end,
precise:!0};if(result+=segmentDurationWithParts(playlist,segment),void 0!==segment.start)return{result:result+segment.start,precise:!0}}return{result:result,precise:!1}}(playlist,endSequence);if(backward.precise)return backward.result;const forward=function(playlist,endSequence){let segment,result=0,i=endSequence-playlist.mediaSequence;for(;i<playlist.segments.length;i++){if(segment=playlist.segments[i],void 0!==segment.start)return{result:segment.start-result,precise:!0};if(result+=segmentDurationWithParts(playlist,segment),void 0!==segment.end)return{result:segment.end-result,precise:!0}}return{result:-1,precise:!1}}(playlist,endSequence);return forward.precise?forward.result:backward.result+expired},duration=function(playlist,endSequence,expired){if(!playlist)return 0;if("number"!=typeof expired&&(expired=0),void 0===endSequence){if(playlist.totalDuration)return playlist.totalDuration;if(!playlist.endList)return window.Infinity}return intervalDuration(playlist,endSequence,expired)},sumDurations=function(_
ref29){let{defaultDuration:defaultDuration,durationList:durationList,startIndex:startIndex,endIndex:endIndex}=_ref29,durations=0;if(startIndex>endIndex&&([startIndex,endIndex]=[endIndex,startIndex]),startIndex<0){for(let i=startIndex;i<Math.min(0,endIndex);i++)durations+=defaultDuration;startIndex=0}for(let i=startIndex;i<endIndex;i++)durations+=durationList[i].duration;return durations},playlistEnd=function(playlist,expired,useSafeLiveEnd,liveEdgePadding){if(!playlist||!playlist.segments)return null;if(playlist.endList)return duration(playlist);if(null===expired)return null;expired=expired||0;let lastSegmentEndTime=intervalDuration(playlist,playlist.mediaSequence+playlist.segments.length,expired);return useSafeLiveEnd&&(lastSegmentEndTime-=liveEdgePadding="number"==typeof liveEdgePadding?liveEdgePadding:liveEdgeDelay(null,playlist)),Math.max(0,lastSegmentEndTime)},isExcluded=function(playlist){return playlist.excludeUntil&&playlist.excludeUntil>Date.now()},isIncompatible=function(playlist){return playlist.e
xcludeUntil&&playlist.excludeUntil===1/0},isEnabled=function(playlist){const excluded=isExcluded(playlist);return!playlist.disabled&&!excluded},hasAttribute=function(attr,playlist){return playlist.attributes&&playlist.attributes[attr]},isLowestEnabledRendition=(main,media)=>{if(1===main.playlists.length)return!0;const currentBandwidth=media.attributes.BANDWIDTH||Number.MAX_VALUE;return 0===main.playlists.filter((playlist=>!!isEnabled(playlist)&&(playlist.attributes.BANDWIDTH||0)<currentBandwidth)).length},playlistMatch=(a,b)=>!(!a&&!b||!a&&b||a&&!b)&&(a===b||(!(!a.id||!b.id||a.id!==b.id)||(!(!a.resolvedUri||!b.resolvedUri||a.resolvedUri!==b.resolvedUri)||!(!a.uri||!b.uri||a.uri!==b.uri)))),someAudioVariant=function(main,callback){const AUDIO=main&&main.mediaGroups&&main.mediaGroups.AUDIO||{};let found=!1;for(const groupName in AUDIO){for(const label in AUDIO[groupName])if(found=callback(AUDIO[groupName][label]),found)break;if(found)break}return!!found},isAudioOnly=main=>{if(!main||!main.playlists||!main.play
lists.length){return someAudioVariant(main,(variant=>variant.playlists&&variant.playlists.length||variant.uri))}for(let i=0;i<main.playlists.length;i++){const playlist=main.playlists[i],CODECS=playlist.attributes&&playlist.attributes.CODECS;if(CODECS&&CODECS.split(",").every((c=>isAudioCodec(c))))continue;if(!someAudioVariant(main,(variant=>playlistMatch(playlist,variant))))return!1}return!0};var Playlist={liveEdgeDelay:liveEdgeDelay,duration:duration,seekable:function(playlist,expired,liveEdgePadding){const seekableStart=expired||0;let seekableEnd=playlistEnd(playlist,expired,!0,liveEdgePadding);return null===seekableEnd?createTimeRanges():(seekableEnd<seekableStart&&(seekableEnd=seekableStart),createTimeRanges(seekableStart,seekableEnd))},getMediaInfoForTime:function(_ref30){let{playlist:playlist,currentTime:currentTime,startingSegmentIndex:startingSegmentIndex,startingPartIndex:startingPartIndex,startTime:startTime,exactManifestTimings:exactManifestTimings}=_ref30,time=currentTime-startTime;const partsAnd
Segments=getPartsAndSegments(playlist);let startIndex=0;for(let i=0;i<partsAndSegments.length;i++){const partAndSegment=partsAndSegments[i];if(startingSegmentIndex===partAndSegment.segmentIndex&&("number"!=typeof startingPartIndex||"number"!=typeof partAndSegment.partIndex||startingPartIndex===partAndSegment.partIndex)){startIndex=i;break}}if(time<0){if(startIndex>0)for(let i=startIndex-1;i>=0;i--){const partAndSegment=partsAndSegments[i];if(time+=partAndSegment.duration,exactManifestTimings){if(time<0)continue}else if(time+.03333333333333333<=0)continue;return{partIndex:partAndSegment.partIndex,segmentIndex:partAndSegment.segmentIndex,startTime:startTime-sumDurations({defaultDuration:playlist.targetDuration,durationList:partsAndSegments,startIndex:startIndex,endIndex:i})}}return{partIndex:partsAndSegments[0]&&partsAndSegments[0].partIndex||null,segmentIndex:partsAndSegments[0]&&partsAndSegments[0].segmentIndex||0,startTime:currentTime}}if(startIndex<0){for(let i=startIndex;i<0;i++)if(time-=playlist.targetDu
ration,time<0)return{partIndex:partsAndSegments[0]&&partsAndSegments[0].partIndex||null,segmentIndex:partsAndSegments[0]&&partsAndSegments[0].segmentIndex||0,startTime:currentTime};startIndex=0}for(let i=startIndex;i<partsAndSegments.length;i++){const partAndSegment=partsAndSegments[i];time-=partAndSegment.duration;const isExtremelyCloseToTheEnd=partAndSegment.duration>.03333333333333333&&time+.03333333333333333>=0;if(!(0===time)&&!isExtremelyCloseToTheEnd||i===partsAndSegments.length-1){if(exactManifestTimings){if(time>0)continue}else if(time-.03333333333333333>=0)continue;return{partIndex:partAndSegment.partIndex,segmentIndex:partAndSegment.segmentIndex,startTime:startTime+sumDurations({defaultDuration:playlist.targetDuration,durationList:partsAndSegments,startIndex:startIndex,endIndex:i})}}}return{segmentIndex:partsAndSegments[partsAndSegments.length-1].segmentIndex,partIndex:partsAndSegments[partsAndSegments.length-1].partIndex,startTime:currentTime}},isEnabled:isEnabled,isDisabled:function(playlist){ret
urn playlist.disabled},isExcluded:isExcluded,isIncompatible:isIncompatible,playlistEnd:playlistEnd,isAes:function(media){for(let i=0;i<media.segments.length;i++)if(media.segments[i].key)return!0;return!1},hasAttribute:hasAttribute,estimateSegmentRequestTime:function(segmentDuration,bandwidth,playlist){let bytesReceived=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!hasAttribute("BANDWIDTH",playlist))return NaN;const size=segmentDuration*playlist.attributes.BANDWIDTH;return(size-8*bytesReceived)/bandwidth},isLowestEnabledRendition:isLowestEnabledRendition,isAudioOnly:isAudioOnly,playlistMatch:playlistMatch,segmentDurationWithParts:segmentDurationWithParts};const{log:log}=videojs,createPlaylistID=(index,uri)=>"".concat(index,"-").concat(uri),groupID=(type,group,label)=>"placeholder-uri-".concat(type,"-").concat(group,"-").concat(label),forEachMediaGroup=(main,callback)=>{main.mediaGroups&&["AUDIO","SUBTITLES"].forEach((mediaType=>{if(main.mediaGroups[mediaType])for(const groupKey in main.mediaGro
ups[mediaType])for(const labelKey in main.mediaGroups[mediaType][groupKey]){const mediaProperties=main.mediaGroups[mediaType][groupKey][labelKey];callback(mediaProperties,mediaType,groupKey,labelKey)}}))},setupMediaPlaylist=_ref32=>{let{playlist:playlist,uri:uri,id:id}=_ref32;playlist.id=id,playlist.playlistErrors_=0,uri&&(playlist.uri=uri),playlist.attributes=playlist.attributes||{}},setupMediaPlaylists=main=>{let i=main.playlists.length;for(;i--;){const playlist=main.playlists[i];setupMediaPlaylist({playlist:playlist,id:createPlaylistID(i,playlist.uri)}),playlist.resolvedUri=resolveUrl(main.uri,playlist.uri),main.playlists[playlist.id]=playlist,main.playlists[playlist.uri]=playlist,playlist.attributes.BANDWIDTH||log.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},resolveMediaGroupUris=main=>{forEachMediaGroup(main,(properties=>{properties.uri&&(properties.resolvedUri=resolveUrl(main.uri,properties.uri))}))},addPropertiesToMain=function(main,uri){let createGroupID=arguments.leng
th>2&&void 0!==arguments[2]?arguments[2]:groupID;main.uri=uri;for(let i=0;i<main.playlists.length;i++)if(!main.playlists[i].uri){const phonyUri="placeholder-uri-".concat(i);main.playlists[i].uri=phonyUri}const audioOnlyMain=isAudioOnly(main);forEachMediaGroup(main,((properties,mediaType,groupKey,labelKey)=>{if(!properties.playlists||!properties.playlists.length){if(audioOnlyMain&&"AUDIO"===mediaType&&!properties.uri)for(let i=0;i<main.playlists.length;i++){const p=main.playlists[i];if(p.attributes&&p.attributes.AUDIO&&p.attributes.AUDIO===groupKey)return}properties.playlists=[_extends$1({},properties)]}properties.playlists.forEach((function(p,i){const groupId=createGroupID(mediaType,groupKey,labelKey,p),id=createPlaylistID(i,groupId);p.uri?p.resolvedUri=p.resolvedUri||resolveUrl(main.uri,p.uri):(p.uri=0===i?groupId:id,p.resolvedUri=p.uri),p.id=p.id||id,p.attributes=p.attributes||{},main.playlists[p.id]=p,main.playlists[p.uri]=p}))})),setupMediaPlaylists(main),resolveMediaGroupUris(main)};class DateRangesStor
age{constructor(){this.offset_=null,this.pendingDateRanges_=new Map,this.processedDateRanges_=new Map}setOffset(){let segments=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if(null!==this.offset_)return;if(!segments.length)return;const[firstSegment]=segments;void 0!==firstSegment.programDateTime&&(this.offset_=firstSegment.programDateTime/1e3)}setPendingDateRanges(){let dateRanges=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if(!dateRanges.length)return;const[dateRange]=dateRanges,startTime=dateRange.startDate.getTime();this.trimProcessedDateRanges_(startTime),this.pendingDateRanges_=dateRanges.reduce(((map,pendingDateRange)=>(map.set(pendingDateRange.id,pendingDateRange),map)),new Map)}processDateRange(dateRange){this.pendingDateRanges_.delete(dateRange.id),this.processedDateRanges_.set(dateRange.id,dateRange)}getDateRangesToProcess(){if(null===this.offset_)return[];const dateRangeClasses={},dateRangesToProcess=[];this.pendingDateRanges_.forEach(((dateRange,id)=>{if(!this.processedD
ateRanges_.has(id)&&(dateRange.startTime=dateRange.startDate.getTime()/1e3-this.offset_,dateRange.processDateRange=()=>this.processDateRange(dateRange),dateRangesToProcess.push(dateRange),dateRange.class))if(dateRangeClasses[dateRange.class]){const length=dateRangeClasses[dateRange.class].push(dateRange);dateRange.classListIndex=length-1}else dateRangeClasses[dateRange.class]=[dateRange],dateRange.classListIndex=0}));for(const dateRange of dateRangesToProcess){const classList=dateRangeClasses[dateRange.class]||[];dateRange.endDate?dateRange.endTime=dateRange.endDate.getTime()/1e3-this.offset_:dateRange.endOnNext&&classList[dateRange.classListIndex+1]?dateRange.endTime=classList[dateRange.classListIndex+1].startTime:dateRange.duration?dateRange.endTime=dateRange.startTime+dateRange.duration:dateRange.plannedDuration?dateRange.endTime=dateRange.startTime+dateRange.plannedDuration:dateRange.endTime=dateRange.startTime}return dateRangesToProcess}trimProcessedDateRanges_(startTime){new Map(this.processedDateRange
s_).forEach(((dateRange,id)=>{dateRange.startDate.getTime()<startTime&&this.processedDateRanges_.delete(id)}))}}const{EventTarget:EventTarget$1}=videojs,updateSegment=(a,b)=>{if(!a)return b;const result=merge(a,b);if(a.preloadHints&&!b.preloadHints&&delete result.preloadHints,a.parts&&!b.parts)delete result.parts;else if(a.parts&&b.parts)for(let i=0;i<b.parts.length;i++)a.parts&&a.parts[i]&&(result.parts[i]=merge(a.parts[i],b.parts[i]));return!a.skipped&&b.skipped&&(result.skipped=!1),a.preload&&!b.preload&&(result.preload=!1),result},updateSegments=(original,update,offset)=>{const oldSegments=original.slice(),newSegments=update.slice();offset=offset||0;const result=[];let currentMap;for(let newIndex=0;newIndex<newSegments.length;newIndex++){const oldSegment=oldSegments[newIndex+offset],newSegment=newSegments[newIndex];oldSegment?(currentMap=oldSegment.map||currentMap,result.push(updateSegment(oldSegment,newSegment))):(currentMap&&!newSegment.map&&(newSegment.map=currentMap),result.push(newSegment))}return r
esult},resolveSegmentUris=(segment,baseUri)=>{!segment.resolvedUri&&segment.uri&&(segment.resolvedUri=resolveUrl(baseUri,segment.uri)),segment.key&&!segment.key.resolvedUri&&(segment.key.resolvedUri=resolveUrl(baseUri,segment.key.uri)),segment.map&&!segment.map.resolvedUri&&(segment.map.resolvedUri=resolveUrl(baseUri,segment.map.uri)),segment.map&&segment.map.key&&!segment.map.key.resolvedUri&&(segment.map.key.resolvedUri=resolveUrl(baseUri,segment.map.key.uri)),segment.parts&&segment.parts.length&&segment.parts.forEach((p=>{p.resolvedUri||(p.resolvedUri=resolveUrl(baseUri,p.uri))})),segment.preloadHints&&segment.preloadHints.length&&segment.preloadHints.forEach((p=>{p.resolvedUri||(p.resolvedUri=resolveUrl(baseUri,p.uri))}))},getAllSegments=function(media){const segments=media.segments||[],preloadSegment=media.preloadSegment;if(preloadSegment&&preloadSegment.parts&&preloadSegment.parts.length){if(preloadSegment.preloadHints)for(let i=0;i<preloadSegment.preloadHints.length;i++)if("MAP"===preloadSegment.prelo
adHints[i].type)return segments;preloadSegment.duration=media.targetDuration,preloadSegment.preload=!0,segments.push(preloadSegment)}return segments},isPlaylistUnchanged=(a,b)=>a===b||a.segments&&b.segments&&a.segments.length===b.segments.length&&a.endList===b.endList&&a.mediaSequence===b.mediaSequence&&a.preloadSegment===b.preloadSegment,updateMain$1=function(main,newMedia){let unchangedCheck=arguments.length>2&&void 0!==arguments[2]?arguments[2]:isPlaylistUnchanged;const result=merge(main,{}),oldMedia=result.playlists[newMedia.id];if(!oldMedia)return null;if(unchangedCheck(oldMedia,newMedia))return null;newMedia.segments=getAllSegments(newMedia);const mergedPlaylist=merge(oldMedia,newMedia);if(mergedPlaylist.preloadSegment&&!newMedia.preloadSegment&&delete mergedPlaylist.preloadSegment,oldMedia.segments){if(newMedia.skip){newMedia.segments=newMedia.segments||[];for(let i=0;i<newMedia.skip.skippedSegments;i++)newMedia.segments.unshift({skipped:!0})}mergedPlaylist.segments=updateSegments(oldMedia.segments,ne
wMedia.segments,newMedia.mediaSequence-oldMedia.mediaSequence)}mergedPlaylist.segments.forEach((segment=>{resolveSegmentUris(segment,mergedPlaylist.resolvedUri)}));for(let i=0;i<result.playlists.length;i++)result.playlists[i].id===newMedia.id&&(result.playlists[i]=mergedPlaylist);return result.playlists[newMedia.id]=mergedPlaylist,result.playlists[newMedia.uri]=mergedPlaylist,forEachMediaGroup(main,((properties,mediaType,groupKey,labelKey)=>{if(properties.playlists)for(let i=0;i<properties.playlists.length;i++)newMedia.id===properties.playlists[i].id&&(properties.playlists[i]=mergedPlaylist)})),result},refreshDelay=(media,update)=>{const segments=media.segments||[],lastSegment=segments[segments.length-1],lastPart=lastSegment&&lastSegment.parts&&lastSegment.parts[lastSegment.parts.length-1],lastDuration=lastPart&&lastPart.duration||lastSegment&&lastSegment.duration;return update&&lastDuration?1e3*lastDuration:500*(media.partTargetDuration||media.targetDuration||10)};class PlaylistLoader extends EventTarget$1{
constructor(src,vhs){let options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(super(),!src)throw new Error("A non-empty playlist URL or object is required");this.logger_=logger("PlaylistLoader");const{withCredentials:withCredentials=!1}=options;this.src=src,this.vhs_=vhs,this.withCredentials=withCredentials,this.addDateRangesToTextTrack_=options.addDateRangesToTextTrack;const vhsOptions=vhs.options_;this.customTagParsers=vhsOptions&&vhsOptions.customTagParsers||[],this.customTagMappers=vhsOptions&&vhsOptions.customTagMappers||[],this.llhls=vhsOptions&&vhsOptions.llhls,this.dateRangesStorage_=new DateRangesStorage,this.state="HAVE_NOTHING",this.handleMediaupdatetimeout_=this.handleMediaupdatetimeout_.bind(this),this.on("mediaupdatetimeout",this.handleMediaupdatetimeout_),this.on("loadedplaylist",this.handleLoadedPlaylist_.bind(this))}handleLoadedPlaylist_(){const mediaPlaylist=this.media();if(!mediaPlaylist)return;this.dateRangesStorage_.setOffset(mediaPlaylist.segments),this.dateRangesStorage
_.setPendingDateRanges(mediaPlaylist.dateRanges);const availableDateRanges=this.dateRangesStorage_.getDateRangesToProcess();availableDateRanges.length&&this.addDateRangesToTextTrack_&&this.addDateRangesToTextTrack_(availableDateRanges)}handleMediaupdatetimeout_(){if("HAVE_METADATA"!==this.state)return;const media=this.media();let uri=resolveUrl(this.main.uri,media.uri);this.llhls&&(uri=((uri,media)=>{if(media.endList||!media.serverControl)return uri;const parameters={};if(media.serverControl.canBlockReload){const{preloadSegment:preloadSegment}=media;let nextMSN=media.mediaSequence+media.segments.length;if(preloadSegment){const parts=preloadSegment.parts||[],nextPart=getKnownPartCount(media)-1;nextPart>-1&&nextPart!==parts.length-1&&(parameters._HLS_part=nextPart),(nextPart>-1||parts.length)&&nextMSN--}parameters._HLS_msn=nextMSN}if(media.serverControl&&media.serverControl.canSkipUntil&&(parameters._HLS_skip=media.serverControl.canSkipDateranges?"v2":"YES"),Object.keys(parameters).length){const parsedUri=new
window.URL(uri);["_HLS_skip","_HLS_msn","_HLS_part"].forEach((function(name){parameters.hasOwnProperty(name)&&parsedUri.searchParams.set(name,parameters[name])})),uri=parsedUri.toString()}return uri})(uri,media)),this.state="HAVE_CURRENT_METADATA",this.request=this.vhs_.xhr({uri:uri,withCredentials:this.withCredentials},((error,req)=>{if(this.request)return error?this.playlistRequestError(this.request,this.media(),"HAVE_METADATA"):void this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})}))}playlistRequestError(xhr,playlist,startingState){const{uri:uri,id:id}=playlist;this.request=null,startingState&&(this.state=startingState),this.error={playlist:this.main.playlists[id],status:xhr.status,message:"HLS playlist request error at URL: ".concat(uri,"."),responseText:xhr.responseText,code:xhr.status>=500?4:2},this.trigger("error")}parseManifest_(_ref33){let{url:url,manifestString:manifestString}=_ref33;return(_ref31=>{let{onwarn:onwarn,oninfo:oninfo,manifestString:
manifestString,customTagParsers:customTagParsers=[],customTagMappers:customTagMappers=[],llhls:llhls}=_ref31;const parser=new Parser;onwarn&&parser.on("warn",onwarn),oninfo&&parser.on("info",oninfo),customTagParsers.forEach((customParser=>parser.addParser(customParser))),customTagMappers.forEach((mapper=>parser.addTagMapper(mapper))),parser.push(manifestString),parser.end();const manifest=parser.manifest;if(llhls||(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach((function(k){manifest.hasOwnProperty(k)&&delete manifest[k]})),manifest.segments&&manifest.segments.forEach((function(segment){["parts","preloadHints"].forEach((function(k){segment.hasOwnProperty(k)&&delete segment[k]}))}))),!manifest.targetDuration){let targetDuration=10;manifest.segments&&manifest.segments.length&&(targetDuration=manifest.segments.reduce(((acc,s)=>Math.max(acc,s.duration)),0)),onwarn&&onwarn({message:"manifest has no targetDuration defaulting to ".concat(targetDuration)}),manifest
.targetDuration=targetDuration}const parts=getLastParts(manifest);if(parts.length&&!manifest.partTargetDuration){const partTargetDuration=parts.reduce(((acc,p)=>Math.max(acc,p.duration)),0);onwarn&&(onwarn({message:"manifest has no partTargetDuration defaulting to ".concat(partTargetDuration)}),log.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),manifest.partTargetDuration=partTargetDuration}return manifest})({onwarn:_ref34=>{let{message:message}=_ref34;return this.logger_("m3u8-parser warn for ".concat(url,": ").concat(message))},oninfo:_ref35=>{let{message:message}=_ref35;return this.logger_("m3u8-parser info for ".concat(url,": ").concat(message))},manifestString:manifestString,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,llhls:this.llhls})}haveMetadata(_ref36){let{playlistString:playlistString,playlistObject:playli
stObject,url:url,id:id}=_ref36;this.request=null,this.state="HAVE_METADATA";const playlist=playlistObject||this.parseManifest_({url:url,manifestString:playlistString});playlist.lastRequest=Date.now(),setupMediaPlaylist({playlist:playlist,uri:url,id:id});const update=updateMain$1(this.main,playlist);this.targetDuration=playlist.partTargetDuration||playlist.targetDuration,this.pendingMedia_=null,update?(this.main=update,this.media_=this.main.playlists[id]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(refreshDelay(this.media(),!!update)),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),window.clearTimeout(this.mediaUpdateTimeout),window.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new DateRangesStorage,this.off()}stopRequest(){if(this.request){const oldRequest=this.request;this.request=null,oldRequest.onreadystatechange=null,oldRequest.abort()}}media(playlist,shouldDelay){if(!playlist)return this.media_;if("HAVE_NOTHING"===this.state)thr
ow new Error("Cannot switch media playlist from "+this.state);if("string"==typeof playlist){if(!this.main.playlists[playlist])throw new Error("Unknown playlist URI: "+playlist);playlist=this.main.playlists[playlist]}if(window.clearTimeout(this.finalRenditionTimeout),shouldDelay){const delay=(playlist.partTargetDuration||playlist.targetDuration)/2*1e3||5e3;return void(this.finalRenditionTimeout=window.setTimeout(this.media.bind(this,playlist,!1),delay))}const startingState=this.state,mediaChange=!this.media_||playlist.id!==this.media_.id,mainPlaylistRef=this.main.playlists[playlist.id];if(mainPlaylistRef&&mainPlaylistRef.endList||playlist.endList&&playlist.segments.length)return this.request&&(this.request.onreadystatechange=null,this.request.abort(),this.request=null),this.state="HAVE_METADATA",this.media_=playlist,void(mediaChange&&(this.trigger("mediachanging"),"HAVE_MAIN_MANIFEST"===startingState?this.trigger("loadedmetadata"):this.trigger("mediachange")));if(this.updateMediaUpdateTimeout_(refreshDelay(pl
aylist,!0)),mediaChange){if(this.state="SWITCHING_MEDIA",this.request){if(playlist.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.pendingMedia_=playlist,this.request=this.vhs_.xhr({uri:playlist.resolvedUri,withCredentials:this.withCredentials},((error,req)=>{if(this.request){if(playlist.lastRequest=Date.now(),playlist.resolvedUri=resolveManifestRedirect(playlist.resolvedUri,req),error)return this.playlistRequestError(this.request,playlist,startingState);this.haveMetadata({playlistString:req.responseText,url:playlist.uri,id:playlist.id}),"HAVE_MAIN_MANIFEST"===startingState?this.trigger("loadedmetadata"):this.trigger("mediachange")}}))}}pause(){this.mediaUpdateTimeout&&(window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.stopRequest(),"HAVE_NOTHING"===this.state&&(this.started=!1),"SWITCHING_MEDIA"===this.state?this.media_?this.state="HAVE_METADATA":this.state="HAVE_MA
IN_MANIFEST":"HAVE_CURRENT_METADATA"===this.state&&(this.state="HAVE_METADATA")}load(shouldDelay){this.mediaUpdateTimeout&&(window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const media=this.media();if(shouldDelay){const delay=media?(media.partTargetDuration||media.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=window.setTimeout((()=>{this.mediaUpdateTimeout=null,this.load()}),delay)}else this.started?media&&!media.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist"):this.start()}updateMediaUpdateTimeout_(delay){this.mediaUpdateTimeout&&(window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.media()&&!this.media().endList&&(this.mediaUpdateTimeout=window.setTimeout((()=>{this.mediaUpdateTimeout=null,this.trigger("mediaupdatetimeout"),this.updateMediaUpdateTimeout_(delay)}),delay))}start(){if(this.started=!0,"object"==typeof this.src)return this.src.uri||(this.src.uri=window.location.href),this.src.resolvedUri=this.src.uri,void setTimeo
ut((()=>{this.setupInitialPlaylist(this.src)}),0);this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials},((error,req)=>{if(!this.request)return;if(this.request=null,error)return this.error={status:req.status,message:"HLS playlist request error at URL: ".concat(this.src,"."),responseText:req.responseText,code:2},"HAVE_NOTHING"===this.state&&(this.started=!1),this.trigger("error");this.src=resolveManifestRedirect(this.src,req);const manifest=this.parseManifest_({manifestString:req.responseText,url:this.src});this.setupInitialPlaylist(manifest)}))}srcUri(){return"string"==typeof this.src?this.src:this.src.uri}setupInitialPlaylist(manifest){if(this.state="HAVE_MAIN_MANIFEST",manifest.playlists)return this.main=manifest,addPropertiesToMain(this.main,this.srcUri()),manifest.playlists.forEach((playlist=>{playlist.segments=getAllSegments(playlist),playlist.segments.forEach((segment=>{resolveSegmentUris(segment,playlist.resolvedUri)}))})),this.trigger("loadedplaylist"),void(this.request||this.
media(this.main.playlists[0]));const uri=this.srcUri()||window.location.href;this.main=((media,uri)=>{const id=createPlaylistID(0,uri),main={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:window.location.href,resolvedUri:window.location.href,playlists:[{uri:uri,id:id,resolvedUri:uri,attributes:{}}]};return main.playlists[id]=main.playlists[0],main.playlists[uri]=main.playlists[0],main})(0,uri),this.haveMetadata({playlistObject:manifest,url:uri,id:this.main.playlists[0].id}),this.trigger("loadedmetadata")}updateOrDeleteClone(clone,isUpdate){const main=this.main,pathway=clone.ID;let i=main.playlists.length;for(;i--;){const p=main.playlists[i];if(p.attributes["PATHWAY-ID"]===pathway){const oldPlaylistUri=p.resolvedUri,oldPlaylistId=p.id;if(isUpdate){const newPlaylistUri=this.createCloneURI_(p.resolvedUri,clone),newPlaylistId=createPlaylistID(pathway,newPlaylistUri),attributes=this.createCloneAttributes_(pathway,p.attributes),updatedPlaylist=this.createClonePlaylist_(p,newPlaylistId,clone,
attributes);main.playlists[i]=updatedPlaylist,main.playlists[newPlaylistId]=updatedPlaylist,main.playlists[newPlaylistUri]=updatedPlaylist}else main.playlists.splice(i,1);delete main.playlists[oldPlaylistId],delete main.playlists[oldPlaylistUri]}}this.updateOrDeleteCloneMedia(clone,isUpdate)}updateOrDeleteCloneMedia(clone,isUpdate){const main=this.main,id=clone.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((mediaType=>{if(main.mediaGroups[mediaType]&&main.mediaGroups[mediaType][id])for(const groupKey in main.mediaGroups[mediaType])if(groupKey===id){for(const labelKey in main.mediaGroups[mediaType][groupKey]){main.mediaGroups[mediaType][groupKey][labelKey].playlists.forEach(((p,i)=>{const oldMediaPlaylist=main.playlists[p.id],oldPlaylistId=oldMediaPlaylist.id,oldPlaylistUri=oldMediaPlaylist.resolvedUri;delete main.playlists[oldPlaylistId],delete main.playlists[oldPlaylistUri]}))}delete main.mediaGroups[mediaType][groupKey]}})),isUpdate&&this.createClonedMediaGroups_(clone)}addClonePathway(clone){let base
Playlist=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const main=this.main,index=main.playlists.length,uri=this.createCloneURI_(basePlaylist.resolvedUri,clone),playlistId=createPlaylistID(clone.ID,uri),attributes=this.createCloneAttributes_(clone.ID,basePlaylist.attributes),playlist=this.createClonePlaylist_(basePlaylist,playlistId,clone,attributes);main.playlists[index]=playlist,main.playlists[playlistId]=playlist,main.playlists[uri]=playlist,this.createClonedMediaGroups_(clone)}createClonedMediaGroups_(clone){const id=clone.ID,baseID=clone["BASE-ID"],main=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((mediaType=>{if(main.mediaGroups[mediaType]&&!main.mediaGroups[mediaType][id])for(const groupKey in main.mediaGroups[mediaType])if(groupKey===baseID){main.mediaGroups[mediaType][id]={};for(const labelKey in main.mediaGroups[mediaType][groupKey]){const oldMedia=main.mediaGroups[mediaType][groupKey][labelKey];main.mediaGroups[mediaType][id][labelKey]=_extends$1({},oldMedia);const newMedi
a=main.mediaGroups[mediaType][id][labelKey],newUri=this.createCloneURI_(oldMedia.resolvedUri,clone);newMedia.resolvedUri=newUri,newMedia.uri=newUri,newMedia.playlists=[],oldMedia.playlists.forEach(((p,i)=>{const oldMediaPlaylist=main.playlists[p.id],group=groupID(mediaType,id,labelKey),newPlaylistID=createPlaylistID(id,group);if(oldMediaPlaylist&&!main.playlists[newPlaylistID]){const newMediaPlaylist=this.createClonePlaylist_(oldMediaPlaylist,newPlaylistID,clone),newPlaylistUri=newMediaPlaylist.resolvedUri;main.playlists[newPlaylistID]=newMediaPlaylist,main.playlists[newPlaylistUri]=newMediaPlaylist}newMedia.playlists[i]=this.createClonePlaylist_(p,newPlaylistID,clone)}))}}}))}createClonePlaylist_(basePlaylist,id,clone,attributes){const uri=this.createCloneURI_(basePlaylist.resolvedUri,clone),newProps={resolvedUri:uri,uri:uri,id:id};return basePlaylist.segments&&(newProps.segments=[]),attributes&&(newProps.attributes=attributes),merge(basePlaylist,newProps)}createCloneURI_(baseURI,clone){const uri=new URL(ba
seURI);uri.hostname=clone["URI-REPLACEMENT"].HOST;const params=clone["URI-REPLACEMENT"].PARAMS;for(const key of Object.keys(params))uri.searchParams.set(key,params[key]);return uri.href}createCloneAttributes_(id,oldAttributes){const attributes={"PATHWAY-ID":id};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((mediaType=>{oldAttributes[mediaType]&&(attributes[mediaType]=id)})),attributes}getKeyIdSet(playlist){if(playlist.contentProtection){const keyIds=new Set;for(const keysystem in playlist.contentProtection){const keyId=playlist.contentProtection[keysystem].attributes.keyId;keyId&&keyIds.add(keyId.toLowerCase())}return keyIds}}}const{xhr:videojsXHR}=videojs,callbackWrapper=function(request,error,response,callback){const reqResponse="arraybuffer"===request.responseType?request.response:request.responseText;!error&&reqResponse&&(request.responseTime=Date.now(),request.roundTripTime=request.responseTime-request.requestTime,request.bytesReceived=reqResponse.byteLength||reqResponse.length,request.bandwidth
||(request.bandwidth=Math.floor(request.bytesReceived/request.roundTripTime*8*1e3))),response.headers&&(request.responseHeaders=response.headers),error&&"ETIMEDOUT"===error.code&&(request.timedout=!0),error||request.aborted||200===response.statusCode||206===response.statusCode||0===response.statusCode||(error=new Error("XHR Failed with a response of: "+(request&&(reqResponse||request.responseText)))),callback(error,request)},xhrFactory=function(){const xhr=function XhrFunction(options,callback){options=merge({timeout:45e3},options);const beforeRequest=XhrFunction.beforeRequest||videojs.Vhs.xhr.beforeRequest,_requestCallbackSet=XhrFunction._requestCallbackSet||videojs.Vhs.xhr._requestCallbackSet||new Set,_responseCallbackSet=XhrFunction._responseCallbackSet||videojs.Vhs.xhr._responseCallbackSet;beforeRequest&&"function"==typeof beforeRequest&&(videojs.log.warn("beforeRequest is deprecated, use onRequest instead."),_requestCallbackSet.add(beforeRequest));const xhrMethod=!0===videojs.Vhs.xhr.original?videojsXHR
:videojs.Vhs.xhr,beforeRequestOptions=((requestSet,options)=>{if(!requestSet||!requestSet.size)return;let newOptions=options;return requestSet.forEach((requestCallback=>{newOptions=requestCallback(newOptions)})),newOptions})(_requestCallbackSet,options);_requestCallbackSet.delete(beforeRequest);const request=xhrMethod(beforeRequestOptions||options,(function(error,response){return((responseSet,request,error,response)=>{responseSet&&responseSet.size&&responseSet.forEach((responseCallback=>{responseCallback(request,error,response)}))})(_responseCallbackSet,request,error,response),callbackWrapper(request,error,response,callback)})),originalAbort=request.abort;return request.abort=function(){return request.aborted=!0,originalAbort.apply(request,arguments)},request.uri=options.uri,request.requestTime=Date.now(),request};return xhr.original=!0,xhr},segmentXhrHeaders=function(segment){const headers={};return segment.byterange&&(headers.Range=function(byterange){let byterangeEnd;const byterangeStart=byterange.offset;
return byterangeEnd="bigint"==typeof byterange.offset||"bigint"==typeof byterange.length?window.BigInt(byterange.offset)+window.BigInt(byterange.length)-window.BigInt(1):byterange.offset+byterange.length-1,"bytes="+byterangeStart+"-"+byterangeEnd}(segment.byterange)),headers},textRange=function(range,i){return range.start(i)+"-"+range.end(i)},formatHexString=function(e,i){const value=e.toString(16);return"00".substring(0,2-value.length)+value+(i%2?" ":"")},formatAsciiString=function(e){return e>=32&&e<126?String.fromCharCode(e):"."},createTransferableMessage=function(message){const transferable={};return Object.keys(message).forEach((key=>{const value=message[key];isArrayBufferView(value)?transferable[key]={bytes:value.buffer,byteOffset:value.byteOffset,byteLength:value.byteLength}:transferable[key]=value})),transferable},initSegmentId=function(initSegment){const byterange=initSegment.byterange||{length:1/0,offset:0};return[byterange.length,byterange.offset,initSegment.resolvedUri].join(",")},segmentKeyId=fu
nction(key){return key.resolvedUri},hexDump=data=>{const bytes=Array.prototype.slice.call(data);let hex,ascii,result="";for(let j=0;j<bytes.length/16;j++)hex=bytes.slice(16*j,16*j+16).map(formatHexString).join(""),ascii=bytes.slice(16*j,16*j+16).map(formatAsciiString).join(""),result+=hex+" "+ascii+"\n";return result};var utils=Object.freeze({__proto__:null,createTransferableMessage:createTransferableMessage,initSegmentId:initSegmentId,segmentKeyId:segmentKeyId,hexDump:hexDump,tagDump:_ref37=>{let{bytes:bytes}=_ref37;return hexDump(bytes)},textRanges:ranges=>{let i,result="";for(i=0;i<ranges.length;i++)result+=textRange(ranges,i)+" ";return result}});const getProgramTime=_ref38=>{let{playlist:playlist,time:time,callback:callback}=_ref38;if(!callback)throw new Error("getProgramTime: callback must be provided");if(!playlist||void 0===time)return callback({message:"getProgramTime: playlist and time must be provided"});const matchedSegment=((time,playlist)=>{if(!playlist||!playlist.segments||0===playlist.segment
s.length)return null;let segment,segmentEnd=0;for(let i=0;i<playlist.segments.length&&(segment=playlist.segments[i],segmentEnd=segment.videoTimingInfo?segment.videoTimingInfo.transmuxedPresentationEnd:segmentEnd+segment.duration,!(time<=segmentEnd));i++);const lastSegment=playlist.segments[playlist.segments.length-1];if(lastSegment.videoTimingInfo&&lastSegment.videoTimingInfo.transmuxedPresentationEnd<time)return null;if(time>segmentEnd){if(time>segmentEnd+.25*lastSegment.duration)return null;segment=lastSegment}return{segment:segment,estimatedStart:segment.videoTimingInfo?segment.videoTimingInfo.transmuxedPresentationStart:segmentEnd-segment.duration,type:segment.videoTimingInfo?"accurate":"estimate"}})(time,playlist);if(!matchedSegment)return callback({message:"valid programTime was not found"});if("estimate"===matchedSegment.type)return callback({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:matchedSegment.estimatedStart});const programTimeObject=
{mediaSeconds:time},programTime=((playerTime,segment)=>{if(!segment.dateTimeObject)return null;const transmuxerPrependedSeconds=segment.videoTimingInfo.transmuxerPrependedSeconds,offsetFromSegmentStart=playerTime-(segment.videoTimingInfo.transmuxedPresentationStart+transmuxerPrependedSeconds);return new Date(segment.dateTimeObject.getTime()+1e3*offsetFromSegmentStart)})(time,matchedSegment.segment);return programTime&&(programTimeObject.programDateTime=programTime.toISOString()),callback(null,programTimeObject)},seekToProgramTime=_ref39=>{let{programTime:programTime,playlist:playlist,retryCount:retryCount=2,seekTo:seekTo,pauseAfterSeek:pauseAfterSeek=!0,tech:tech,callback:callback}=_ref39;if(!callback)throw new Error("seekToProgramTime: callback must be provided");if(void 0===programTime||!playlist||!seekTo)return callback({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!playlist.endList&&!tech.hasStarted_)return callback({message:"player must be playing a live stream to
start buffering"});if(!(playlist=>{if(!playlist.segments||0===playlist.segments.length)return!1;for(let i=0;i<playlist.segments.length;i++)if(!playlist.segments[i].dateTimeObject)return!1;return!0})(playlist))return callback({message:"programDateTime tags must be provided in the manifest "+playlist.resolvedUri});const matchedSegment=((programTime,playlist)=>{let dateTimeObject;try{dateTimeObject=new Date(programTime)}catch(e){return null}if(!playlist||!playlist.segments||0===playlist.segments.length)return null;let segment=playlist.segments[0];if(dateTimeObject<new Date(segment.dateTimeObject))return null;for(let i=0;i<playlist.segments.length-1&&(segment=playlist.segments[i],!(dateTimeObject<new Date(playlist.segments[i+1].dateTimeObject)));i++);const lastSegment=playlist.segments[playlist.segments.length-1],lastSegmentStart=lastSegment.dateTimeObject,lastSegmentDuration=lastSegment.videoTimingInfo?(videoTimingInfo=lastSegment.videoTimingInfo).transmuxedPresentationEnd-videoTimingInfo.transmuxedPresentation
Start-videoTimingInfo.transmuxerPrependedSeconds:lastSegment.duration+.25*lastSegment.duration;var videoTimingInfo;return dateTimeObject>new Date(lastSegmentStart.getTime()+1e3*lastSegmentDuration)?null:(dateTimeObject>new Date(lastSegmentStart)&&(segment=lastSegment),{segment:segment,estimatedStart:segment.videoTimingInfo?segment.videoTimingInfo.transmuxedPresentationStart:Playlist.duration(playlist,playlist.mediaSequence+playlist.segments.indexOf(segment)),type:segment.videoTimingInfo?"accurate":"estimate"})})(programTime,playlist);if(!matchedSegment)return callback({message:"".concat(programTime," was not found in the stream")});const segment=matchedSegment.segment,mediaOffset=((comparisonTimeStamp,programTime)=>{let segmentDateTime,programDateTime;try{segmentDateTime=new Date(comparisonTimeStamp),programDateTime=new Date(programTime)}catch(e){}const segmentTimeEpoch=segmentDateTime.getTime();return(programDateTime.getTime()-segmentTimeEpoch)/1e3})(segment.dateTimeObject,programTime);if("estimate"===match
edSegment.type)return 0===retryCount?callback({message:"".concat(programTime," is not buffered yet. Try again")}):(seekTo(matchedSegment.estimatedStart+mediaOffset),void tech.one("seeked",(()=>{seekToProgramTime({programTime:programTime,playlist:playlist,retryCount:retryCount-1,seekTo:seekTo,pauseAfterSeek:pauseAfterSeek,tech:tech,callback:callback})})));const seekToTime=segment.start+mediaOffset;tech.one("seeked",(()=>callback(null,tech.currentTime()))),pauseAfterSeek&&tech.pause(),seekTo(seekToTime)},callbackOnCompleted=(request,cb)=>{if(4===request.readyState)return cb()},containerRequest=(uri,xhr,cb)=>{let id3Offset,bytes=[],finished=!1;const endRequestAndCallback=function(err,req,type,_bytes){return req.abort(),finished=!0,cb(err,req,type,_bytes)},progressListener=function(error,request){if(finished)return;if(error)return endRequestAndCallback(error,request,"",bytes);const newPart=request.responseText.substring(bytes&&bytes.byteLength||0,request.responseText.length);if(bytes=function(){for(var _len=argu
ments.length,buffers=new Array(_len),_key=0;_key<_len;_key++)buffers[_key]=arguments[_key];if(buffers=buffers.filter((function(b){return b&&(b.byteLength||b.length)&&"string"!=typeof b})),buffers.length<=1)return toUint8(buffers[0]);var totalLen=buffers.reduce((function(total,buf,i){return total+(buf.byteLength||buf.length)}),0),tempBuffer=new Uint8Array(totalLen),offset=0;return buffers.forEach((function(buf){buf=toUint8(buf),tempBuffer.set(buf,offset),offset+=buf.byteLength})),tempBuffer}(bytes,stringToBytes(newPart,!0)),id3Offset=id3Offset||getId3Offset(bytes),bytes.length<10||id3Offset&&bytes.length<id3Offset+2)return callbackOnCompleted(request,(()=>endRequestAndCallback(error,request,"",bytes)));const type=detectContainerForBytes(bytes);return"ts"===type&&bytes.length<188||!type&&bytes.length<376?callbackOnCompleted(request,(()=>endRequestAndCallback(error,request,"",bytes))):endRequestAndCallback(null,request,type,bytes)},options={uri:uri,beforeSend(request){request.overrideMimeType("text/plain; chars
et=x-user-defined"),request.addEventListener("progress",(function(_ref40){let{total:total,loaded:loaded}=_ref40;return callbackWrapper(request,null,{statusCode:request.status},progressListener)}))}},request=xhr(options,(function(error,response){return callbackWrapper(request,error,response,progressListener)}));return request},{EventTarget:EventTarget}=videojs,dashPlaylistUnchanged=function(a,b){if(!isPlaylistUnchanged(a,b))return!1;if(a.sidx&&b.sidx&&(a.sidx.offset!==b.sidx.offset||a.sidx.length!==b.sidx.length))return!1;if(!a.sidx&&b.sidx||a.sidx&&!b.sidx)return!1;if(a.segments&&!b.segments||!a.segments&&b.segments)return!1;if(!a.segments&&!b.segments)return!0;for(let i=0;i<a.segments.length;i++){const aSegment=a.segments[i],bSegment=b.segments[i];if(aSegment.uri!==bSegment.uri)return!1;if(!aSegment.byterange&&!bSegment.byterange)continue;const aByterange=aSegment.byterange,bByterange=bSegment.byterange;if(aByterange&&!bByterange||!aByterange&&bByterange)return!1;if(aByterange.offset!==bByterange.offset||aB
yterange.length!==bByterange.length)return!1}return!0},dashGroupId=(type,group,label,playlist)=>{const playlistId=playlist.attributes.NAME||label;return"placeholder-uri-".concat(type,"-").concat(group,"-").concat(playlistId)},parseMainXml=_ref41=>{let{mainXml:mainXml,srcUrl:srcUrl,clientOffset:clientOffset,sidxMapping:sidxMapping,previousManifest:previousManifest}=_ref41;const manifest=function(manifestString){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const parsedManifestInfo=inheritAttributes(stringToMpdXml(manifestString),options),playlists=toPlaylists(parsedManifestInfo.representationInfo);return toM3u8({dashPlaylists:playlists,locations:parsedManifestInfo.locations,contentSteering:parsedManifestInfo.contentSteeringInfo,sidxMapping:options.sidxMapping,previousManifest:options.previousManifest,eventStream:parsedManifestInfo.eventStream})}(mainXml,{manifestUri:srcUrl,clientOffset:clientOffset,sidxMapping:sidxMapping,previousManifest:previousManifest});return addPropertiesToMain(m
anifest,srcUrl,dashGroupId),manifest},updateMain=(oldMain,newMain,sidxMapping)=>{let noChanges=!0,update=merge(oldMain,{duration:newMain.duration,minimumUpdatePeriod:newMain.minimumUpdatePeriod,timelineStarts:newMain.timelineStarts});for(let i=0;i<newMain.playlists.length;i++){const playlist=newMain.playlists[i];if(playlist.sidx){const sidxKey=generateSidxKey(playlist.sidx);sidxMapping&&sidxMapping[sidxKey]&&sidxMapping[sidxKey].sidx&&addSidxSegmentsToPlaylist$1(playlist,sidxMapping[sidxKey].sidx,playlist.sidx.resolvedUri)}const playlistUpdate=updateMain$1(update,playlist,dashPlaylistUnchanged);playlistUpdate&&(update=playlistUpdate,noChanges=!1)}return forEachMediaGroup(newMain,((properties,type,group,label)=>{if(properties.playlists&&properties.playlists.length){const id=properties.playlists[0].id,playlistUpdate=updateMain$1(update,properties.playlists[0],dashPlaylistUnchanged);playlistUpdate&&(update=playlistUpdate,label in update.mediaGroups[type][group]||(update.mediaGroups[type][group][label]=propertie
s),update.mediaGroups[type][group][label].playlists[0]=update.playlists[id],noChanges=!1)}})),((update,newMain)=>{forEachMediaGroup(update,((properties,type,group,label)=>{label in newMain.mediaGroups[type][group]||delete update.mediaGroups[type][group][label]}))})(update,newMain),newMain.minimumUpdatePeriod!==oldMain.minimumUpdatePeriod&&(noChanges=!1),noChanges?null:update},equivalentSidx=(a,b)=>(Boolean(!a.map&&!b.map)||Boolean(a.map&&b.map&&a.map.byterange.offset===b.map.byterange.offset&&a.map.byterange.length===b.map.byterange.length))&&a.uri===b.uri&&a.byterange.offset===b.byterange.offset&&a.byterange.length===b.byterange.length,compareSidxEntry=(playlists,oldSidxMapping)=>{const newSidxMapping={};for(const id in playlists){const currentSidxInfo=playlists[id].sidx;if(currentSidxInfo){const key=generateSidxKey(currentSidxInfo);if(!oldSidxMapping[key])break;const savedSidxInfo=oldSidxMapping[key].sidxInfo;equivalentSidx(savedSidxInfo,currentSidxInfo)&&(newSidxMapping[key]=oldSidxMapping[key])}}return n
ewSidxMapping};class DashPlaylistLoader extends EventTarget{constructor(srcUrlOrPlaylist,vhs){let options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},mainPlaylistLoader=arguments.length>3?arguments[3]:void 0;super(),this.mainPlaylistLoader_=mainPlaylistLoader||this,mainPlaylistLoader||(this.isMain_=!0);const{withCredentials:withCredentials=!1}=options;if(this.vhs_=vhs,this.withCredentials=withCredentials,this.addMetadataToTextTrack=options.addMetadataToTextTrack,!srcUrlOrPlaylist)throw new Error("A non-empty playlist URL or object is required");this.on("minimumUpdatePeriod",(()=>{this.refreshXml_()})),this.on("mediaupdatetimeout",(()=>{this.refreshMedia_(this.media().id)})),this.state="HAVE_NOTHING",this.loadedPlaylists_={},this.logger_=logger("DashPlaylistLoader"),this.isMain_?(this.mainPlaylistLoader_.srcUrl=srcUrlOrPlaylist,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=srcUrlOrPlaylist}requestErrored_(err,request,startingState){return!this.request||(this.request=null,err?(thi
s.error="object"!=typeof err||err instanceof Error?{status:request.status,message:"DASH request error at URL: "+request.uri,response:request.response,code:2}:err,startingState&&(this.state=startingState),this.trigger("error"),!0):void 0)}addSidxSegments_(playlist,startingState,cb){const sidxKey=playlist.sidx&&generateSidxKey(playlist.sidx);if(!playlist.sidx||!sidxKey||this.mainPlaylistLoader_.sidxMapping_[sidxKey])return void(this.mediaRequest_=window.setTimeout((()=>cb(!1)),0));const uri=resolveManifestRedirect(playlist.sidx.resolvedUri),fin=(err,request)=>{if(this.requestErrored_(err,request,startingState))return;const sidxMapping=this.mainPlaylistLoader_.sidxMapping_;let sidx;try{sidx=parseSidx_1(toUint8(request.response).subarray(8))}catch(e){return void this.requestErrored_(e,request,startingState)}return sidxMapping[sidxKey]={sidxInfo:playlist.sidx,sidx:sidx},addSidxSegmentsToPlaylist$1(playlist,sidx,playlist.sidx.resolvedUri),cb(!0)};this.request=containerRequest(uri,this.vhs_.xhr,((err,request,contai
ner,bytes)=>{if(err)return fin(err,request);if(!container||"mp4"!==container)return fin({status:request.status,message:"Unsupported ".concat(container||"unknown"," container type for sidx segment at URL: ").concat(uri),response:"",playlist:playlist,internal:!0,playlistExclusionDuration:1/0,code:2},request);const{offset:offset,length:length}=playlist.sidx.byterange;if(bytes.length>=length+offset)return fin(err,{response:bytes.subarray(offset,offset+length),status:request.status,uri:request.uri});this.request=this.vhs_.xhr({uri:uri,responseType:"arraybuffer",headers:segmentXhrHeaders({byterange:playlist.sidx.byterange})},fin)}))}dispose(){this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},window.clearTimeout(this.minimumUpdatePeriodTimeout_),window.clearTimeout(this.mediaRequest_),window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.main
PlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){const oldRequest=this.request;this.request=null,oldRequest.onreadystatechange=null,oldRequest.abort()}}media(playlist){if(!playlist)return this.media_;if("HAVE_NOTHING"===this.state)throw new Error("Cannot switch media playlist from "+this.state);const startingState=this.state;if("string"==typeof playlist){if(!this.mainPlaylistLoader_.main.playlists[playlist])throw new Error("Unknown playlist URI: "+playlist);playlist=this.mainPlaylistLoader_.main.playlists[playlist]}const mediaChange=!this.media_||playlist.id!==this.media_.id;if(mediaChange&&this.loadedPlaylists_[playlist.id]&&this.loadedPlaylists_[playlist.id].endList)return this.state="HAVE_METADATA",this.media_=playlist,void(mediaChange&&(this.trigger("mediachanging"),this.trigger("mediachange")));mediaChange&&(this.media_&&this.trigger("mediachanging"),this.addSidxSegmen
ts_(playlist,startingState,(sidxChanged=>{this.haveMetadata({startingState:startingState,playlist:playlist})})))}haveMetadata(_ref42){let{startingState:startingState,playlist:playlist}=_ref42;this.state="HAVE_METADATA",this.loadedPlaylists_[playlist.id]=playlist,this.mediaRequest_=null,this.refreshMedia_(playlist.id),"HAVE_MAIN_MANIFEST"===startingState?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(window.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),"HAVE_NOTHING"===this.state&&(this.started=!1)}load(isFinalRendition){window.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const media=this.media();if(isFinalRendition){const
delay=media?media.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=window.setTimeout((()=>this.load()),delay)}else this.started?media&&!media.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist"):this.start()}start(){this.started=!0,this.isMain_?this.requestMain_(((req,mainChanged)=>{this.haveMain_(),this.hasPendingRequest()||this.media_||this.media(this.mainPlaylistLoader_.main.playlists[0])})):this.mediaRequest_=window.setTimeout((()=>this.haveMain_()),0)}requestMain_(cb){this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials},((error,req)=>{if(this.requestErrored_(error,req))return void("HAVE_NOTHING"===this.state&&(this.started=!1));const mainChanged=req.responseText!==this.mainPlaylistLoader_.mainXml_;return this.mainPlaylistLoader_.mainXml_=req.responseText,req.responseHeaders&&req.responseHeaders.date?this.m
ainLoaded_=Date.parse(req.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl,req),mainChanged?(this.handleMain_(),void this.syncClientServerClock_((()=>cb(req,mainChanged)))):cb(req,mainChanged)}))}syncClientServerClock_(done){const utcTiming=parseUTCTiming(this.mainPlaylistLoader_.mainXml_);return null===utcTiming?(this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),done()):"DIRECT"===utcTiming.method?(this.mainPlaylistLoader_.clientOffset_=utcTiming.value-Date.now(),done()):void(this.request=this.vhs_.xhr({uri:resolveUrl(this.mainPlaylistLoader_.srcUrl,utcTiming.value),method:utcTiming.method,withCredentials:this.withCredentials},((error,req)=>{if(!this.request)return;if(error)return this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),done();let serverTime;serverTime="HEAD"===utcTiming.method?req.responseHeaders&&req.responseHeaders.date?Date.parse(req.responseHeaders.date):this.mainLoaded_:
Date.parse(req.responseText),this.mainPlaylistLoader_.clientOffset_=serverTime-Date.now(),done()})))}haveMain_(){this.state="HAVE_MAIN_MANIFEST",this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){this.mediaRequest_=null;const oldMain=this.mainPlaylistLoader_.main;let newMain=parseMainXml({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:oldMain});oldMain&&(newMain=updateMain(oldMain,newMain,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=newMain||oldMain;const location=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];return location&&location!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=location),(!oldMain||newMain&&newMain.minimumUpdatePeriod!==oldMain.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventSt
reamToMetadataTrack_(newMain),Boolean(newMain)}updateMinimumUpdatePeriodTimeout_(){const mpl=this.mainPlaylistLoader_;mpl.createMupOnMedia_&&(mpl.off("loadedmetadata",mpl.createMupOnMedia_),mpl.createMupOnMedia_=null),mpl.minimumUpdatePeriodTimeout_&&(window.clearTimeout(mpl.minimumUpdatePeriodTimeout_),mpl.minimumUpdatePeriodTimeout_=null);let mup=mpl.main&&mpl.main.minimumUpdatePeriod;0===mup&&(mpl.media()?mup=1e3*mpl.media().targetDuration:(mpl.createMupOnMedia_=mpl.updateMinimumUpdatePeriodTimeout_,mpl.one("loadedmetadata",mpl.createMupOnMedia_))),"number"!=typeof mup||mup<=0?mup<0&&this.logger_("found invalid minimumUpdatePeriod of ".concat(mup,", not setting a timeout")):this.createMUPTimeout_(mup)}createMUPTimeout_(mup){const mpl=this.mainPlaylistLoader_;mpl.minimumUpdatePeriodTimeout_=window.setTimeout((()=>{mpl.minimumUpdatePeriodTimeout_=null,mpl.trigger("minimumUpdatePeriod"),mpl.createMUPTimeout_(mup)}),mup)}refreshXml_(){this.requestMain_(((req,mainChanged)=>{mainChanged&&(this.media_&&(this.med
ia_=this.mainPlaylistLoader_.main.playlists[this.media_.id]),this.mainPlaylistLoader_.sidxMapping_=((main,oldSidxMapping)=>{let mediaGroupSidx=compareSidxEntry(main.playlists,oldSidxMapping);return forEachMediaGroup(main,((properties,mediaType,groupKey,labelKey)=>{if(properties.playlists&&properties.playlists.length){const playlists=properties.playlists;mediaGroupSidx=merge(mediaGroupSidx,compareSidxEntry(playlists,oldSidxMapping))}})),mediaGroupSidx})(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.sidxMapping_),this.addSidxSegments_(this.media(),this.state,(sidxChanged=>{this.refreshMedia_(this.media().id)})))}))}refreshMedia_(mediaID){if(!mediaID)throw new Error("refreshMedia_ must take a media id");this.media_&&this.isMain_&&this.handleMain_();const playlists=this.mainPlaylistLoader_.main.playlists,mediaChanged=!this.media_||this.media_!==playlists[mediaID];if(mediaChanged?this.media_=playlists[mediaID]:this.trigger("playlistunchanged"),!this.mediaUpdateTimeout){const createMediaUpdateTimeout=()=>
{this.media().endList||(this.mediaUpdateTimeout=window.setTimeout((()=>{this.trigger("mediaupdatetimeout"),createMediaUpdateTimeout()}),refreshDelay(this.media(),Boolean(mediaChanged))))};createMediaUpdateTimeout()}this.trigger("loadedplaylist")}addEventStreamToMetadataTrack_(newMain){if(newMain&&this.mainPlaylistLoader_.main.eventStream){const metadataArray=this.mainPlaylistLoader_.main.eventStream.map((eventStreamNode=>({cueTime:eventStreamNode.start,frames:[{data:eventStreamNode.messageData}]})));this.addMetadataToTextTrack("EventStream",metadataArray,this.mainPlaylistLoader_.main.duration)}}getKeyIdSet(playlist){if(playlist.contentProtection){const keyIds=new Set;for(const keysystem in playlist.contentProtection){const defaultKID=playlist.contentProtection[keysystem].attributes["cenc:default_KID"];defaultKID&&keyIds.add(defaultKID.replace(/-/g,"").toLowerCase())}return keyIds}}}var Config={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,BACK_BUFFER_LENGTH:30,GOAL_BUFFER_LENGTH_RATE:1,INITIAL_BANDWIDTH:41
94304,BANDWIDTH_VARIANCE:1.2,BUFFER_LOW_WATER_LINE:0,MAX_BUFFER_LOW_WATER_LINE:30,EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:16,BUFFER_LOW_WATER_LINE_RATE:1,BUFFER_HIGH_WATER_LINE:30};const browserWorkerPolyFill=function(workerObj){return workerObj.on=workerObj.addEventListener,workerObj.off=workerObj.removeEventListener,workerObj},factory=function(code){return function(){const objectUrl=function(str){try{return URL.createObjectURL(new Blob([str],{type:"application/javascript"}))}catch(e){const blob=new BlobBuilder;return blob.append(str),URL.createObjectURL(blob.getBlob())}}(code),worker=browserWorkerPolyFill(new Worker(objectUrl));worker.objURL=objectUrl;const terminate=worker.terminate;return worker.on=worker.addEventListener,worker.off=worker.removeEventListener,worker.terminate=function(){return URL.revokeObjectURL(objectUrl),terminate.call(this)},worker}},transform=function(code){return"var browserWorkerPolyFill = ".concat(browserWorkerPolyFill.toString(),";\n")+"browserWorkerPolyFill(self);\n"+code},getWo
rkerString=function(fn){return fn.toString().replace(/^function.+?{/,"").slice(0,-1)},workerCode$1=transform(getWorkerString((function(){var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Stream$8=function(){this.init=function(){var listeners={};this.on=function(type,listener){listeners[type]||(listeners[type]=[]),listeners[type]=listeners[type].concat(listener)},this.off=function(type,listener){var index;return!!listeners[type]&&(index=listeners[type].indexOf(listener),listeners[type]=listeners[type].slice(),listeners[type].splice(index,1),index>-1)},this.trigger=function(type){var callbacks,i,length,args;if(callbacks=listeners[type])if(2===arguments.length)for(length=callbacks.length,i=0;i<length;++i)callbacks[i].call(this,arguments[1]);else{for(args=[],i=arguments.length,i=1;i<arguments.length;++i)args.push(arguments[i]);for(length=callbacks.length,i=0;i<length;++i)callbacks[i].apply(this,args)}}
,this.dispose=function(){listeners={}}}};Stream$8.prototype.pipe=function(destination){return this.on("data",(function(data){destination.push(data)})),this.on("done",(function(flushSource){destination.flush(flushSource)})),this.on("partialdone",(function(flushSource){destination.partialFlush(flushSource)})),this.on("endedtimeline",(function(flushSource){destination.endTimeline(flushSource)})),this.on("reset",(function(flushSource){destination.reset(flushSource)})),destination},Stream$8.prototype.push=function(data){this.trigger("data",data)},Stream$8.prototype.flush=function(flushSource){this.trigger("done",flushSource)},Stream$8.prototype.partialFlush=function(flushSource){this.trigger("partialdone",flushSource)},Stream$8.prototype.endTimeline=function(flushSource){this.trigger("endedtimeline",flushSource)},Stream$8.prototype.reset=function(flushSource){this.trigger("reset",flushSource)};var box,dinf,esds,ftyp,mfhd,minf,moof,moov,mvex,mvhd,trak,tkhd,mdia,mdhd,hdlr,sdtp,stbl,stsd,traf,trex,trun$1,types,MAJOR
_BRAND,MINOR_VERSION,AVC1_BRAND,VIDEO_HDLR,AUDIO_HDLR,HDLR_TYPES,VMHD,SMHD,DREF,STCO,STSC,STSZ,STTS,videoSample,audioSample,audioTrun,videoTrun,trunHeader,stream=Stream$8,MAX_UINT32$1=Math.pow(2,32),numbers={getUint64:function(uint8){var value,dv=new DataView(uint8.buffer,uint8.byteOffset,uint8.byteLength);return dv.getBigUint64?(value=dv.getBigUint64(0))<Number.MAX_SAFE_INTEGER?Number(value):value:dv.getUint32(0)*MAX_UINT32$1+dv.getUint32(4)},MAX_UINT32:MAX_UINT32$1},MAX_UINT32=numbers.MAX_UINT32;!function(){var i;if(types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],pasp:[],sdtp:[],smhd:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],styp:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[]},"undefined"!=typeof Uint8Array){for(i in types)types.hasOwnProperty(i)&&(types[i]=[i.charCodeAt(0),i.charCodeAt(1),i.charCodeAt(2),i.charCodeAt(3)]);MAJOR_BRAND=new Uint8Array(["i".charCodeAt(0),"s".char
CodeAt(0),"o".charCodeAt(0),"m".charCodeAt(0)]),AVC1_BRAND=new Uint8Array(["a".charCodeAt(0),"v".charCodeAt(0),"c".charCodeAt(0),"1".charCodeAt(0)]),MINOR_VERSION=new Uint8Array([0,0,0,1]),VIDEO_HDLR=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),AUDIO_HDLR=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]),HDLR_TYPES={video:VIDEO_HDLR,audio:AUDIO_HDLR},DREF=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),STCO=new Uint8Array([0,0,0,0,0,0,0,0]),STSC=STCO,STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),STTS=STCO,VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}}(),box=function(type){var i,result,payload=[],size=0;for(i=1;i<arguments.length;i++)payload.push(arguments[i]);for(i=payload.length;i--;)size+=payload[i].byteLength;for(result=new Uint8Array(size+8),new DataView(result.buffer,result.byteOffset,result.byteLeng
th).setUint32(0,result.byteLength),result.set(type,4),i=0,size=8;i<payload.length;i++)result.set(payload[i],size),size+=payload[i].byteLength;return result},dinf=function(){return box(types.dinf,box(types.dref,DREF))},esds=function(track){return box(types.esds,new Uint8Array([0,0,0,0,3,25,0,0,0,4,17,64,21,0,6,0,0,0,218,192,0,0,218,192,5,2,track.audioobjecttype<<3|track.samplingfrequencyindex>>>1,track.samplingfrequencyindex<<7|track.channelcount<<3,6,1,2]))},hdlr=function(type){return box(types.hdlr,HDLR_TYPES[type])},mdhd=function(track){var result=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,track.duration>>>24&255,track.duration>>>16&255,track.duration>>>8&255,255&track.duration,85,196,0,0]);return track.samplerate&&(result[12]=track.samplerate>>>24&255,result[13]=track.samplerate>>>16&255,result[14]=track.samplerate>>>8&255,result[15]=255&track.samplerate),box(types.mdhd,result)},mdia=function(track){return box(types.mdia,mdhd(track),hdlr(track.type),minf(track))},mfhd=function(sequenceNumber){retu
rn box(types.mfhd,new Uint8Array([0,0,0,0,(4278190080&sequenceNumber)>>24,(16711680&sequenceNumber)>>16,(65280&sequenceNumber)>>8,255&sequenceNumber]))},minf=function(track){return box(types.minf,"video"===track.type?box(types.vmhd,VMHD):box(types.smhd,SMHD),dinf(),stbl(track))},moof=function(sequenceNumber,tracks){for(var trackFragments=[],i=tracks.length;i--;)trackFragments[i]=traf(tracks[i]);return box.apply(null,[types.moof,mfhd(sequenceNumber)].concat(trackFragments))},moov=function(tracks){for(var i=tracks.length,boxes=[];i--;)boxes[i]=trak(tracks[i]);return box.apply(null,[types.moov,mvhd(4294967295)].concat(boxes).concat(mvex(tracks)))},mvex=function(tracks){for(var i=tracks.length,boxes=[];i--;)boxes[i]=trex(tracks[i]);return box.apply(null,[types.mvex].concat(boxes))},mvhd=function(duration){var bytes=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(4278190080&duration)>>24,(16711680&duration)>>16,(65280&duration)>>8,255&duration,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 box(types.mvhd,bytes)},sdtp=function(track){var flags,i,samples=track.samples||[],bytes=new Uint8Array(4+samples.length);for(i=0;i<samples.length;i++)flags=samples[i].flags,bytes[i+4]=flags.dependsOn<<4|flags.isDependedOn<<2|flags.hasRedundancy;return box(types.sdtp,bytes)},stbl=function(track){return box(types.stbl,stsd(track),box(types.stts,STTS),box(types.stsc,STSC),box(types.stsz,STSZ),box(types.stco,STCO))},stsd=function(track){return box(types.stsd,new Uint8Array([0,0,0,0,0,0,0,1]),"video"===track.type?videoSample(track):audioSample(track))},videoSample=function(track){var i,avc1Box,sps=track.sps||[],pps=track.pps||[],sequenceParameterSets=[],pictureParameterSets=[];for(i=0;i<sps.length;i++)sequenceParameterSets.push((65280&sps[i].byteLength)>>>8),sequenceParameterSets.push(255&sps[i].byteLength),sequenceParameterSets=sequenceParameterSets.concat(Array.prototype.slice.call(sps[i]));for(i=0;i<
pps.length;i++)pictureParameterSets.push((65280&pps[i].byteLength)>>>8),pictureParameterSets.push(255&pps[i].byteLength),pictureParameterSets=pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));if(avc1Box=[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,(65280&track.width)>>8,255&track.width,(65280&track.height)>>8,255&track.height,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),box(types.avcC,new Uint8Array([1,track.profileIdc,track.profileCompatibility,track.levelIdc,255].concat([sps.length],sequenceParameterSets,[pps.length],pictureParameterSets))),box(types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],track.sarRatio){var hSpacing=track.sarRatio[0],vSpacing=track.sarRatio[1];avc1Box.push(box(types.pasp,new Uint8Array([(4278190080&hSpacing)>>24,(16711680&hSpacing)>>16,(65280&hSpacing)>>8,255&hSpacing,(4278190080&vSpacing)>>24,(16711680&vSpacing)>>16,(65280&
vSpacing)>>8,255&vSpacing])))}return box.apply(null,avc1Box)},audioSample=function(track){return box(types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(65280&track.channelcount)>>8,255&track.channelcount,(65280&track.samplesize)>>8,255&track.samplesize,0,0,0,0,(65280&track.samplerate)>>8,255&track.samplerate,0,0]),esds(track))},tkhd=function(track){var result=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(4278190080&track.id)>>24,(16711680&track.id)>>16,(65280&track.id)>>8,255&track.id,0,0,0,0,(4278190080&track.duration)>>24,(16711680&track.duration)>>16,(65280&track.duration)>>8,255&track.duration,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,(65280&track.width)>>8,255&track.width,0,0,(65280&track.height)>>8,255&track.height,0,0]);return box(types.tkhd,result)},traf=function(track){var trackFragmentHeader,trackFragmentDecodeTime,trackFragmentRun,sampleDependencyTable,upperWordBaseMediaDecodeTime,lowerWordBaseMediaDecodeTime;return trackFragmentHe
ader=box(types.tfhd,new Uint8Array([0,0,0,58,(4278190080&track.id)>>24,(16711680&track.id)>>16,(65280&track.id)>>8,255&track.id,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),upperWordBaseMediaDecodeTime=Math.floor(track.baseMediaDecodeTime/MAX_UINT32),lowerWordBaseMediaDecodeTime=Math.floor(track.baseMediaDecodeTime%MAX_UINT32),trackFragmentDecodeTime=box(types.tfdt,new Uint8Array([1,0,0,0,upperWordBaseMediaDecodeTime>>>24&255,upperWordBaseMediaDecodeTime>>>16&255,upperWordBaseMediaDecodeTime>>>8&255,255&upperWordBaseMediaDecodeTime,lowerWordBaseMediaDecodeTime>>>24&255,lowerWordBaseMediaDecodeTime>>>16&255,lowerWordBaseMediaDecodeTime>>>8&255,255&lowerWordBaseMediaDecodeTime])),92,"audio"===track.type?(trackFragmentRun=trun$1(track,92),box(types.traf,trackFragmentHeader,trackFragmentDecodeTime,trackFragmentRun)):(sampleDependencyTable=sdtp(track),trackFragmentRun=trun$1(track,sampleDependencyTable.length+92),box(types.traf,trackFragmentHeader,trackFragmentDecodeTime,trackFragmentRun,sampleDependencyTable))},trak=funct
ion(track){return track.duration=track.duration||4294967295,box(types.trak,tkhd(track),mdia(track))},trex=function(track){var result=new Uint8Array([0,0,0,0,(4278190080&track.id)>>24,(16711680&track.id)>>16,(65280&track.id)>>8,255&track.id,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return"video"!==track.type&&(result[result.length-1]=0),box(types.trex,result)},trunHeader=function(samples,offset){var durationPresent=0,sizePresent=0,flagsPresent=0,compositionTimeOffset=0;return samples.length&&(void 0!==samples[0].duration&&(durationPresent=1),void 0!==samples[0].size&&(sizePresent=2),void 0!==samples[0].flags&&(flagsPresent=4),void 0!==samples[0].compositionTimeOffset&&(compositionTimeOffset=8)),[0,0,durationPresent|sizePresent|flagsPresent|compositionTimeOffset,1,(4278190080&samples.length)>>>24,(16711680&samples.length)>>>16,(65280&samples.length)>>>8,255&samples.length,(4278190080&offset)>>>24,(16711680&offset)>>>16,(65280&offset)>>>8,255&offset]},videoTrun=function(track,offset){var bytesOffest,bytes,header,sample
s,sample,i;for(offset+=20+16*(samples=track.samples||[]).length,header=trunHeader(samples,offset),(bytes=new Uint8Array(header.length+16*samples.length)).set(header),bytesOffest=header.length,i=0;i<samples.length;i++)sample=samples[i],bytes[bytesOffest++]=(4278190080&sample.duration)>>>24,bytes[bytesOffest++]=(16711680&sample.duration)>>>16,bytes[bytesOffest++]=(65280&sample.duration)>>>8,bytes[bytesOffest++]=255&sample.duration,bytes[bytesOffest++]=(4278190080&sample.size)>>>24,bytes[bytesOffest++]=(16711680&sample.size)>>>16,bytes[bytesOffest++]=(65280&sample.size)>>>8,bytes[bytesOffest++]=255&sample.size,bytes[bytesOffest++]=sample.flags.isLeading<<2|sample.flags.dependsOn,bytes[bytesOffest++]=sample.flags.isDependedOn<<6|sample.flags.hasRedundancy<<4|sample.flags.paddingValue<<1|sample.flags.isNonSyncSample,bytes[bytesOffest++]=61440&sample.flags.degradationPriority,bytes[bytesOffest++]=15&sample.flags.degradationPriority,bytes[bytesOffest++]=(4278190080&sample.compositionTimeOffset)>>>24,bytes[bytesOffe
st++]=(16711680&sample.compositionTimeOffset)>>>16,bytes[bytesOffest++]=(65280&sample.compositionTimeOffset)>>>8,bytes[bytesOffest++]=255&sample.compositionTimeOffset;return box(types.trun,bytes)},audioTrun=function(track,offset){var bytes,bytesOffest,header,samples,sample,i;for(offset+=20+8*(samples=track.samples||[]).length,header=trunHeader(samples,offset),(bytes=new Uint8Array(header.length+8*samples.length)).set(header),bytesOffest=header.length,i=0;i<samples.length;i++)sample=samples[i],bytes[bytesOffest++]=(4278190080&sample.duration)>>>24,bytes[bytesOffest++]=(16711680&sample.duration)>>>16,bytes[bytesOffest++]=(65280&sample.duration)>>>8,bytes[bytesOffest++]=255&sample.duration,bytes[bytesOffest++]=(4278190080&sample.size)>>>24,bytes[bytesOffest++]=(16711680&sample.size)>>>16,bytes[bytesOffest++]=(65280&sample.size)>>>8,bytes[bytesOffest++]=255&sample.size;return box(types.trun,bytes)},trun$1=function(track,offset){return"audio"===track.type?audioTrun(track,offset):videoTrun(track,offset)};var silen
ce,secondsToVideoTs,secondsToAudioTs,videoTsToSeconds,audioTsToSeconds,audioTsToVideoTs,videoTsToAudioTs,metadataTsToSeconds,mp4Generator={ftyp:ftyp=function(){return box(types.ftyp,MAJOR_BRAND,MINOR_VERSION,MAJOR_BRAND,AVC1_BRAND)},mdat:function(data){return box(types.mdat,data)},moof:moof,moov:moov,initSegment:function(tracks){var result,fileType=ftyp(),movie=moov(tracks);return(result=new Uint8Array(fileType.byteLength+movie.byteLength)).set(fileType),result.set(movie,fileType.byteLength),result}},sampleForFrame=function(frame,dataOffset){var sample={size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}};return sample.dataOffset=dataOffset,sample.compositionTimeOffset=frame.pts-frame.dts,sample.duration=frame.duration,sample.size=4*frame.length,sample.size+=frame.byteLength,frame.keyFrame&&(sample.flags.dependsOn=2,sample.flags.isNonSyncSample=0),sample},frameUtils$1={groupNalsIntoFrames:function(nalUnits){var i,currentNal,currentFrame=[],frames=[];f
or(frames.byteLength=0,frames.nalCount=0,frames.duration=0,currentFrame.byteLength=0,i=0;i<nalUnits.length;i++)"access_unit_delimiter_rbsp"===(currentNal=nalUnits[i]).nalUnitType?(currentFrame.length&&(currentFrame.duration=currentNal.dts-currentFrame.dts,frames.byteLength+=currentFrame.byteLength,frames.nalCount+=currentFrame.length,frames.duration+=currentFrame.duration,frames.push(currentFrame)),(currentFrame=[currentNal]).byteLength=currentNal.data.byteLength,currentFrame.pts=currentNal.pts,currentFrame.dts=currentNal.dts):("slice_layer_without_partitioning_rbsp_idr"===currentNal.nalUnitType&&(currentFrame.keyFrame=!0),currentFrame.duration=currentNal.dts-currentFrame.dts,currentFrame.byteLength+=currentNal.data.byteLength,currentFrame.push(currentNal));return frames.length&&(!currentFrame.duration||currentFrame.duration<=0)&&(currentFrame.duration=frames[frames.length-1].duration),frames.byteLength+=currentFrame.byteLength,frames.nalCount+=currentFrame.length,frames.duration+=currentFrame.duration,frame
s.push(currentFrame),frames},groupFramesIntoGops:function(frames){var i,currentFrame,currentGop=[],gops=[];for(currentGop.byteLength=0,currentGop.nalCount=0,currentGop.duration=0,currentGop.pts=frames[0].pts,currentGop.dts=frames[0].dts,gops.byteLength=0,gops.nalCount=0,gops.duration=0,gops.pts=frames[0].pts,gops.dts=frames[0].dts,i=0;i<frames.length;i++)(currentFrame=frames[i]).keyFrame?(currentGop.length&&(gops.push(currentGop),gops.byteLength+=currentGop.byteLength,gops.nalCount+=currentGop.nalCount,gops.duration+=currentGop.duration),(currentGop=[currentFrame]).nalCount=currentFrame.length,currentGop.byteLength=currentFrame.byteLength,currentGop.pts=currentFrame.pts,currentGop.dts=currentFrame.dts,currentGop.duration=currentFrame.duration):(currentGop.duration+=currentFrame.duration,currentGop.nalCount+=currentFrame.length,currentGop.byteLength+=currentFrame.byteLength,currentGop.push(currentFrame));return gops.length&¤tGop.duration<=0&&(currentGop.duration=gops[gops.length-1].duration),gops.byteLe
ngth+=currentGop.byteLength,gops.nalCount+=currentGop.nalCount,gops.duration+=currentGop.duration,gops.push(currentGop),gops},extendFirstKeyFrame:function(gops){var currentGop;return!gops[0][0].keyFrame&&gops.length>1&&(currentGop=gops.shift(),gops.byteLength-=currentGop.byteLength,gops.nalCount-=currentGop.nalCount,gops[0][0].dts=currentGop.dts,gops[0][0].pts=currentGop.pts,gops[0][0].duration+=currentGop.duration),gops},generateSampleTable:function(gops,baseDataOffset){var h,i,sample,currentGop,currentFrame,dataOffset=baseDataOffset||0,samples=[];for(h=0;h<gops.length;h++)for(currentGop=gops[h],i=0;i<currentGop.length;i++)currentFrame=currentGop[i],dataOffset+=(sample=sampleForFrame(currentFrame,dataOffset)).size,samples.push(sample);return samples},concatenateNalData:function(gops){var h,i,j,currentGop,currentFrame,currentNal,dataOffset=0,nalsByteLength=gops.byteLength,numberOfNals=gops.nalCount,data=new Uint8Array(nalsByteLength+4*numberOfNals),view=new DataView(data.buffer);for(h=0;h<gops.length;h++)for
(currentGop=gops[h],i=0;i<currentGop.length;i++)for(currentFrame=currentGop[i],j=0;j<currentFrame.length;j++)currentNal=currentFrame[j],view.setUint32(dataOffset,currentNal.data.byteLength),dataOffset+=4,data.set(currentNal.data,dataOffset),dataOffset+=currentNal.data.byteLength;return data},generateSampleTableForFrame:function(frame,baseDataOffset){var sample,samples=[];return sample=sampleForFrame(frame,baseDataOffset||0),samples.push(sample),samples},concatenateNalDataForFrame:function(frame){var i,currentNal,dataOffset=0,nalsByteLength=frame.byteLength,numberOfNals=frame.length,data=new Uint8Array(nalsByteLength+4*numberOfNals),view=new DataView(data.buffer);for(i=0;i<frame.length;i++)currentNal=frame[i],view.setUint32(dataOffset,currentNal.data.byteLength),dataOffset+=4,data.set(currentNal.data,dataOffset),dataOffset+=currentNal.data.byteLength;return data}},highPrefix=[33,16,5,32,164,27],lowPrefix=[33,65,108,84,1,2,4,8,168,2,4,8,17,191,252],zeroFill=function(count){for(var a=[];count--;)a.push(0);retur
n a};audioTsToVideoTs=function(timestamp,sampleRate){return secondsToVideoTs(audioTsToSeconds(timestamp,sampleRate))},videoTsToAudioTs=function(timestamp,sampleRate){return secondsToAudioTs(videoTsToSeconds(timestamp),sampleRate)},metadataTsToSeconds=function(timestamp,timelineStartPts,keepOriginalTimestamps){return videoTsToSeconds(keepOriginalTimestamps?timestamp:timestamp-timelineStartPts)};var clock$2={ONE_SECOND_IN_TS:9e4,secondsToVideoTs:secondsToVideoTs=function(seconds){return 9e4*seconds},secondsToAudioTs:secondsToAudioTs=function(seconds,sampleRate){return seconds*sampleRate},videoTsToSeconds:videoTsToSeconds=function(timestamp){return timestamp/9e4},audioTsToSeconds:audioTsToSeconds=function(timestamp,sampleRate){return timestamp/sampleRate},audioTsToVideoTs:audioTsToVideoTs,videoTsToAudioTs:videoTsToAudioTs,metadataTsToSeconds:metadataTsToSeconds},coneOfSilence=function(){if(!silence){var coneOfSilence={96e3:[highPrefix,[227,64],zeroFill(154),[56]],88200:[highPrefix,[231],zeroFill(170),[56]],64e3
:[highPrefix,[248,192],zeroFill(240),[56]],48e3:[highPrefix,[255,192],zeroFill(268),[55,148,128],zeroFill(54),[112]],44100:[highPrefix,[255,192],zeroFill(268),[55,163,128],zeroFill(84),[112]],32e3:[highPrefix,[255,192],zeroFill(268),[55,234],zeroFill(226),[112]],24e3:[highPrefix,[255,192],zeroFill(268),[55,255,128],zeroFill(268),[111,112],zeroFill(126),[224]],16e3:[highPrefix,[255,192],zeroFill(268),[55,255,128],zeroFill(268),[111,255],zeroFill(269),[223,108],zeroFill(195),[1,192]],12e3:[lowPrefix,zeroFill(268),[3,127,248],zeroFill(268),[6,255,240],zeroFill(268),[13,255,224],zeroFill(268),[27,253,128],zeroFill(259),[56]],11025:[lowPrefix,zeroFill(268),[3,127,248],zeroFill(268),[6,255,240],zeroFill(268),[13,255,224],zeroFill(268),[27,255,192],zeroFill(268),[55,175,128],zeroFill(108),[112]],8e3:[lowPrefix,zeroFill(268),[3,121,16],zeroFill(47),[7]]};metaTable=coneOfSilence,silence=Object.keys(metaTable).reduce((function(obj,key){return obj[key]=new Uint8Array(metaTable[key].reduce((function(arr,part){return arr
.concat(part)}),[])),obj}),{})}var metaTable;return silence},clock$1=clock$2,audioFrameUtils$1={prefixWithSilence:function(track,frames,audioAppendStartTs,videoBaseMediaDecodeTime){var baseMediaDecodeTimeTs,frameDuration,silentFrame,i,firstFrame,audioGapDuration=0,audioFillFrameCount=0,audioFillDuration=0;if(frames.length&&(baseMediaDecodeTimeTs=clock$1.audioTsToVideoTs(track.baseMediaDecodeTime,track.samplerate),frameDuration=Math.ceil(clock$1.ONE_SECOND_IN_TS/(track.samplerate/1024)),audioAppendStartTs&&videoBaseMediaDecodeTime&&(audioGapDuration=baseMediaDecodeTimeTs-Math.max(audioAppendStartTs,videoBaseMediaDecodeTime),audioFillDuration=(audioFillFrameCount=Math.floor(audioGapDuration/frameDuration))*frameDuration),!(audioFillFrameCount<1||audioFillDuration>clock$1.ONE_SECOND_IN_TS/2))){for((silentFrame=coneOfSilence()[track.samplerate])||(silentFrame=frames[0].data),i=0;i<audioFillFrameCount;i++)firstFrame=frames[0],frames.splice(0,0,{data:silentFrame,dts:firstFrame.dts-frameDuration,pts:firstFrame.pts-
frameDuration});return track.baseMediaDecodeTime-=Math.floor(clock$1.videoTsToAudioTs(audioFillDuration,track.samplerate)),audioFillDuration}},trimAdtsFramesByEarliestDts:function(adtsFrames,track,earliestAllowedDts){return track.minSegmentDts>=earliestAllowedDts?adtsFrames:(track.minSegmentDts=1/0,adtsFrames.filter((function(currentFrame){return currentFrame.dts>=earliestAllowedDts&&(track.minSegmentDts=Math.min(track.minSegmentDts,currentFrame.dts),track.minSegmentPts=track.minSegmentDts,!0)})))},generateSampleTable:function(frames){var i,currentFrame,samples=[];for(i=0;i<frames.length;i++)currentFrame=frames[i],samples.push({size:currentFrame.data.byteLength,duration:1024});return samples},concatenateFrameData:function(frames){var i,currentFrame,dataOffset=0,data=new Uint8Array(function(array){var i,sum=0;for(i=0;i<array.length;i++)sum+=array[i].data.byteLength;return sum}(frames));for(i=0;i<frames.length;i++)currentFrame=frames[i],data.set(currentFrame.data,dataOffset),dataOffset+=currentFrame.data.byteL
ength;return data}},ONE_SECOND_IN_TS$3=clock$2.ONE_SECOND_IN_TS,trackDecodeInfo$1={clearDtsInfo:function(track){delete track.minSegmentDts,delete track.maxSegmentDts,delete track.minSegmentPts,delete track.maxSegmentPts},calculateTrackBaseMediaDecodeTime:function(track,keepOriginalTimestamps){var baseMediaDecodeTime,minSegmentDts=track.minSegmentDts;return keepOriginalTimestamps||(minSegmentDts-=track.timelineStartInfo.dts),baseMediaDecodeTime=track.timelineStartInfo.baseMediaDecodeTime,baseMediaDecodeTime+=minSegmentDts,baseMediaDecodeTime=Math.max(0,baseMediaDecodeTime),"audio"===track.type&&(baseMediaDecodeTime*=track.samplerate/ONE_SECOND_IN_TS$3,baseMediaDecodeTime=Math.floor(baseMediaDecodeTime)),baseMediaDecodeTime},collectDtsInfo:function(track,data){"number"==typeof data.pts&&(void 0===track.timelineStartInfo.pts&&(track.timelineStartInfo.pts=data.pts),void 0===track.minSegmentPts?track.minSegmentPts=data.pts:track.minSegmentPts=Math.min(track.minSegmentPts,data.pts),void 0===track.maxSegmentPts?tra
ck.maxSegmentPts=data.pts:track.maxSegmentPts=Math.max(track.maxSegmentPts,data.pts)),"number"==typeof data.dts&&(void 0===track.timelineStartInfo.dts&&(track.timelineStartInfo.dts=data.dts),void 0===track.minSegmentDts?track.minSegmentDts=data.dts:track.minSegmentDts=Math.min(track.minSegmentDts,data.dts),void 0===track.maxSegmentDts?track.maxSegmentDts=data.dts:track.maxSegmentDts=Math.max(track.maxSegmentDts,data.dts))}},captionPacketParser={parseSei:function(bytes){for(var i=0,result={payloadType:-1,payloadSize:0},payloadType=0,payloadSize=0;i<bytes.byteLength&&128!==bytes[i];){for(;255===bytes[i];)payloadType+=255,i++;for(payloadType+=bytes[i++];255===bytes[i];)payloadSize+=255,i++;if(payloadSize+=bytes[i++],!result.payload&&4===payloadType){if("GA94"===String.fromCharCode(bytes[i+3],bytes[i+4],bytes[i+5],bytes[i+6])){result.payloadType=payloadType,result.payloadSize=payloadSize,result.payload=bytes.subarray(i,i+payloadSize);break}result.payload=void 0}i+=payloadSize,payloadType=0,payloadSize=0}return r
esult},parseUserData:function(sei){return 181!==sei.payload[0]||49!=(sei.payload[1]<<8|sei.payload[2])||"GA94"!==String.fromCharCode(sei.payload[3],sei.payload[4],sei.payload[5],sei.payload[6])||3!==sei.payload[7]?null:sei.payload.subarray(8,sei.payload.length-1)},parseCaptionPackets:function(pts,userData){var i,count,offset,data,results=[];if(!(64&userData[0]))return results;for(count=31&userData[0],i=0;i<count;i++)data={type:3&userData[(offset=3*i)+2],pts:pts},4&userData[offset+2]&&(data.ccData=userData[offset+3]<<8|userData[offset+4],results.push(data));return results},discardEmulationPreventionBytes:function(data){for(var newLength,newData,length=data.byteLength,emulationPreventionBytesPositions=[],i=1;i<length-2;)0===data[i]&&0===data[i+1]&&3===data[i+2]?(emulationPreventionBytesPositions.push(i+2),i+=2):i++;if(0===emulationPreventionBytesPositions.length)return data;newLength=length-emulationPreventionBytesPositions.length,newData=new Uint8Array(newLength);var sourceIndex=0;for(i=0;i<newLength;sourceIn
dex++,i++)sourceIndex===emulationPreventionBytesPositions[0]&&(sourceIndex++,emulationPreventionBytesPositions.shift()),newData[i]=data[sourceIndex];return newData},USER_DATA_REGISTERED_ITU_T_T35:4},Stream$7=stream,cea708Parser=captionPacketParser,CaptionStream$2=function(options){options=options||{},CaptionStream$2.prototype.init.call(this),this.parse708captions_="boolean"!=typeof options.parse708captions||options.parse708captions,this.captionPackets_=[],this.ccStreams_=[new Cea608Stream(0,0),new Cea608Stream(0,1),new Cea608Stream(1,0),new Cea608Stream(1,1)],this.parse708captions_&&(this.cc708Stream_=new Cea708Stream({captionServices:options.captionServices})),this.reset(),this.ccStreams_.forEach((function(cc){cc.on("data",this.trigger.bind(this,"data")),cc.on("partialdone",this.trigger.bind(this,"partialdone")),cc.on("done",this.trigger.bind(this,"done"))}),this),this.parse708captions_&&(this.cc708Stream_.on("data",this.trigger.bind(this,"data")),this.cc708Stream_.on("partialdone",this.trigger.bind(this,"p
artialdone")),this.cc708Stream_.on("done",this.trigger.bind(this,"done")))};CaptionStream$2.prototype=new Stream$7,CaptionStream$2.prototype.push=function(event){var sei,userData,newCaptionPackets;if("sei_rbsp"===event.nalUnitType&&(sei=cea708Parser.parseSei(event.escapedRBSP)).payload&&sei.payloadType===cea708Parser.USER_DATA_REGISTERED_ITU_T_T35&&(userData=cea708Parser.parseUserData(sei)))if(event.dts<this.latestDts_)this.ignoreNextEqualDts_=!0;else{if(event.dts===this.latestDts_&&this.ignoreNextEqualDts_)return this.numSameDts_--,void(this.numSameDts_||(this.ignoreNextEqualDts_=!1));newCaptionPackets=cea708Parser.parseCaptionPackets(event.pts,userData),this.captionPackets_=this.captionPackets_.concat(newCaptionPackets),this.latestDts_!==event.dts&&(this.numSameDts_=0),this.numSameDts_++,this.latestDts_=event.dts}},CaptionStream$2.prototype.flushCCStreams=function(flushType){this.ccStreams_.forEach((function(cc){return"flush"===flushType?cc.flush():cc.partialFlush()}),this)},CaptionStream$2.prototype.flush
Stream=function(flushType){this.captionPackets_.length?(this.captionPackets_.forEach((function(elem,idx){elem.presortIndex=idx})),this.captionPackets_.sort((function(a,b){return a.pts===b.pts?a.presortIndex-b.presortIndex:a.pts-b.pts})),this.captionPackets_.forEach((function(packet){packet.type<2?this.dispatchCea608Packet(packet):this.dispatchCea708Packet(packet)}),this),this.captionPackets_.length=0,this.flushCCStreams(flushType)):this.flushCCStreams(flushType)},CaptionStream$2.prototype.flush=function(){return this.flushStream("flush")},CaptionStream$2.prototype.partialFlush=function(){return this.flushStream("partialFlush")},CaptionStream$2.prototype.reset=function(){this.latestDts_=null,this.ignoreNextEqualDts_=!1,this.numSameDts_=0,this.activeCea608Channel_=[null,null],this.ccStreams_.forEach((function(ccStream){ccStream.reset()}))},CaptionStream$2.prototype.dispatchCea608Packet=function(packet){this.setsTextOrXDSActive(packet)?this.activeCea608Channel_[packet.type]=null:this.setsChannel1Active(packet)?
this.activeCea608Channel_[packet.type]=0:this.setsChannel2Active(packet)&&(this.activeCea608Channel_[packet.type]=1),null!==this.activeCea608Channel_[packet.type]&&this.ccStreams_[(packet.type<<1)+this.activeCea608Channel_[packet.type]].push(packet)},CaptionStream$2.prototype.setsChannel1Active=function(packet){return 4096==(30720&packet.ccData)},CaptionStream$2.prototype.setsChannel2Active=function(packet){return 6144==(30720&packet.ccData)},CaptionStream$2.prototype.setsTextOrXDSActive=function(packet){return 256==(28928&packet.ccData)||4138==(30974&packet.ccData)||6186==(30974&packet.ccData)},CaptionStream$2.prototype.dispatchCea708Packet=function(packet){this.parse708captions_&&this.cc708Stream_.push(packet)};var CHARACTER_TRANSLATION_708={127:9834,4128:32,4129:160,4133:8230,4138:352,4140:338,4144:9608,4145:8216,4146:8217,4147:8220,4148:8221,4149:8226,4153:8482,4154:353,4156:339,4157:8480,4159:376,4214:8539,4215:8540,4216:8541,4217:8542,4218:9168,4219:9124,4220:9123,4221:9135,4222:9126,4223:9121,4256:126
00},within708TextBlock=function(b){return 32<=b&&b<=127||160<=b&&b<=255},Cea708Window=function(windowNum){this.windowNum=windowNum,this.reset()};Cea708Window.prototype.reset=function(){this.clearText(),this.pendingNewLine=!1,this.winAttr={},this.penAttr={},this.penLoc={},this.penColor={},this.visible=0,this.rowLock=0,this.columnLock=0,this.priority=0,this.relativePositioning=0,this.anchorVertical=0,this.anchorHorizontal=0,this.anchorPoint=0,this.rowCount=1,this.virtualRowCount=this.rowCount+1,this.columnCount=41,this.windowStyle=0,this.penStyle=0},Cea708Window.prototype.getText=function(){return this.rows.join("\n")},Cea708Window.prototype.clearText=function(){this.rows=[""],this.rowIdx=0},Cea708Window.prototype.newLine=function(pts){for(this.rows.length>=this.virtualRowCount&&"function"==typeof this.beforeRowOverflow&&this.beforeRowOverflow(pts),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},Cea708Window.prototype.isEmpty=functi
on(){return 0===this.rows.length||1===this.rows.length&&""===this.rows[0]},Cea708Window.prototype.addText=function(text){this.rows[this.rowIdx]+=text},Cea708Window.prototype.backspace=function(){if(!this.isEmpty()){var row=this.rows[this.rowIdx];this.rows[this.rowIdx]=row.substr(0,row.length-1)}};var Cea708Service=function(serviceNum,encoding,stream){this.serviceNum=serviceNum,this.text="",this.currentWindow=new Cea708Window(-1),this.windows=[],this.stream=stream,"string"==typeof encoding&&this.createTextDecoder(encoding)};Cea708Service.prototype.init=function(pts,beforeRowOverflow){this.startPts=pts;for(var win=0;win<8;win++)this.windows[win]=new Cea708Window(win),"function"==typeof beforeRowOverflow&&(this.windows[win].beforeRowOverflow=beforeRowOverflow)},Cea708Service.prototype.setCurrentWindow=function(windowNum){this.currentWindow=this.windows[windowNum]},Cea708Service.prototype.createTextDecoder=function(encoding){if("undefined"==typeof TextDecoder)this.stream.trigger("log",{level:"warn",message:"The
`encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(encoding)}catch(error){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+encoding+" encoding. "+error})}};var Cea708Stream=function(options){options=options||{},Cea708Stream.prototype.init.call(this);var serviceProps,self=this,captionServices=options.captionServices||{},captionServiceEncodings={};Object.keys(captionServices).forEach((serviceName=>{serviceProps=captionServices[serviceName],/^SERVICE/.test(serviceName)&&(captionServiceEncodings[serviceName]=serviceProps.encoding)})),this.serviceEncodings=captionServiceEncodings,this.current708Packet=null,this.services={},this.push=function(packet){3===packet.type?(self.new708Packet(),self.add708Bytes(packet)):(null===self.current708Packet&&self.new708Packet(),self.add708Bytes(packet))}};Cea708Stream.prototype=new Stream$7,Cea708Stream.prototype.new708Packet=function(){null!==this.current708Packet&&this.push708Packet(
),this.current708Packet={data:[],ptsVals:[]}},Cea708Stream.prototype.add708Bytes=function(packet){var data=packet.ccData,byte0=data>>>8,byte1=255&data;this.current708Packet.ptsVals.push(packet.pts),this.current708Packet.data.push(byte0),this.current708Packet.data.push(byte1)},Cea708Stream.prototype.push708Packet=function(){var packet708=this.current708Packet,packetData=packet708.data,serviceNum=null,blockSize=null,i=0,b=packetData[i++];for(packet708.seq=b>>6,packet708.sizeCode=63&b;i<packetData.length;i++)blockSize=31&(b=packetData[i++]),7===(serviceNum=b>>5)&&blockSize>0&&(serviceNum=b=packetData[i++]),this.pushServiceBlock(serviceNum,i,blockSize),blockSize>0&&(i+=blockSize-1)},Cea708Stream.prototype.pushServiceBlock=function(serviceNum,start,size){var b,i=start,packetData=this.current708Packet.data,service=this.services[serviceNum];for(service||(service=this.initService(serviceNum,i));i<start+size&&i<packetData.length;i++)b=packetData[i],within708TextBlock(b)?i=this.handleText(i,service):24===b?i=this.mult
iByteCharacter(i,service):16===b?i=this.extendedCommands(i,service):128<=b&&b<=135?i=this.setCurrentWindow(i,service):152<=b&&b<=159?i=this.defineWindow(i,service):136===b?i=this.clearWindows(i,service):140===b?i=this.deleteWindows(i,service):137===b?i=this.displayWindows(i,service):138===b?i=this.hideWindows(i,service):139===b?i=this.toggleWindows(i,service):151===b?i=this.setWindowAttributes(i,service):144===b?i=this.setPenAttributes(i,service):145===b?i=this.setPenColor(i,service):146===b?i=this.setPenLocation(i,service):143===b?service=this.reset(i,service):8===b?service.currentWindow.backspace():12===b?service.currentWindow.clearText():13===b?service.currentWindow.pendingNewLine=!0:14===b?service.currentWindow.clearText():141===b&&i++},Cea708Stream.prototype.extendedCommands=function(i,service){var b=this.current708Packet.data[++i];return within708TextBlock(b)&&(i=this.handleText(i,service,{isExtended:!0})),i},Cea708Stream.prototype.getPts=function(byteIndex){return this.current708Packet.ptsVals[Math.fl
oor(byteIndex/2)]},Cea708Stream.prototype.initService=function(serviceNum,i){var serviceName,encoding,self=this;return(serviceName="SERVICE"+serviceNum)in this.serviceEncodings&&(encoding=this.serviceEncodings[serviceName]),this.services[serviceNum]=new Cea708Service(serviceNum,encoding,self),this.services[serviceNum].init(this.getPts(i),(function(pts){self.flushDisplayed(pts,self.services[serviceNum])})),this.services[serviceNum]},Cea708Stream.prototype.handleText=function(i,service,options){var char,charCodeArray,code,newCode,isExtended=options&&options.isExtended,isMultiByte=options&&options.isMultiByte,packetData=this.current708Packet.data,extended=isExtended?4096:0,currentByte=packetData[i],nextByte=packetData[i+1],win=service.currentWindow;if(isMultiByte?(charCodeArray=[currentByte,nextByte],i++):charCodeArray=[currentByte],service.textDecoder_&&!isExtended)char=service.textDecoder_.decode(new Uint8Array(charCodeArray));else if(isMultiByte){const unicode=charCodeArray.map((byte=>("0"+(255&byte).toStrin
g(16)).slice(-2))).join("");char=String.fromCharCode(parseInt(unicode,16))}else newCode=CHARACTER_TRANSLATION_708[code=extended|currentByte]||code,char=4096&code&&code===newCode?"":String.fromCharCode(newCode);return win.pendingNewLine&&!win.isEmpty()&&win.newLine(this.getPts(i)),win.pendingNewLine=!1,win.addText(char),i},Cea708Stream.prototype.multiByteCharacter=function(i,service){var packetData=this.current708Packet.data,firstByte=packetData[i+1],secondByte=packetData[i+2];return within708TextBlock(firstByte)&&within708TextBlock(secondByte)&&(i=this.handleText(++i,service,{isMultiByte:!0})),i},Cea708Stream.prototype.setCurrentWindow=function(i,service){var windowNum=7&this.current708Packet.data[i];return service.setCurrentWindow(windowNum),i},Cea708Stream.prototype.defineWindow=function(i,service){var packetData=this.current708Packet.data,b=packetData[i],windowNum=7&b;service.setCurrentWindow(windowNum);var win=service.currentWindow;return b=packetData[++i],win.visible=(32&b)>>5,win.rowLock=(16&b)>>4,win.
columnLock=(8&b)>>3,win.priority=7&b,b=packetData[++i],win.relativePositioning=(128&b)>>7,win.anchorVertical=127&b,b=packetData[++i],win.anchorHorizontal=b,b=packetData[++i],win.anchorPoint=(240&b)>>4,win.rowCount=15&b,b=packetData[++i],win.columnCount=63&b,b=packetData[++i],win.windowStyle=(56&b)>>3,win.penStyle=7&b,win.virtualRowCount=win.rowCount+1,i},Cea708Stream.prototype.setWindowAttributes=function(i,service){var packetData=this.current708Packet.data,b=packetData[i],winAttr=service.currentWindow.winAttr;return b=packetData[++i],winAttr.fillOpacity=(192&b)>>6,winAttr.fillRed=(48&b)>>4,winAttr.fillGreen=(12&b)>>2,winAttr.fillBlue=3&b,b=packetData[++i],winAttr.borderType=(192&b)>>6,winAttr.borderRed=(48&b)>>4,winAttr.borderGreen=(12&b)>>2,winAttr.borderBlue=3&b,b=packetData[++i],winAttr.borderType+=(128&b)>>5,winAttr.wordWrap=(64&b)>>6,winAttr.printDirection=(48&b)>>4,winAttr.scrollDirection=(12&b)>>2,winAttr.justify=3&b,b=packetData[++i],winAttr.effectSpeed=(240&b)>>4,winAttr.effectDirection=(12&b)>>2,w
inAttr.displayEffect=3&b,i},Cea708Stream.prototype.flushDisplayed=function(pts,service){for(var displayedText=[],winId=0;winId<8;winId++)service.windows[winId].visible&&!service.windows[winId].isEmpty()&&displayedText.push(service.windows[winId].getText());service.endPts=pts,service.text=displayedText.join("\n\n"),this.pushCaption(service),service.startPts=pts},Cea708Stream.prototype.pushCaption=function(service){""!==service.text&&(this.trigger("data",{startPts:service.startPts,endPts:service.endPts,text:service.text,stream:"cc708_"+service.serviceNum}),service.text="",service.startPts=service.endPts)},Cea708Stream.prototype.displayWindows=function(i,service){var b=this.current708Packet.data[++i],pts=this.getPts(i);this.flushDisplayed(pts,service);for(var winId=0;winId<8;winId++)b&1<<winId&&(service.windows[winId].visible=1);return i},Cea708Stream.prototype.hideWindows=function(i,service){var b=this.current708Packet.data[++i],pts=this.getPts(i);this.flushDisplayed(pts,service);for(var winId=0;winId<8;winId+
+)b&1<<winId&&(service.windows[winId].visible=0);return i},Cea708Stream.prototype.toggleWindows=function(i,service){var b=this.current708Packet.data[++i],pts=this.getPts(i);this.flushDisplayed(pts,service);for(var winId=0;winId<8;winId++)b&1<<winId&&(service.windows[winId].visible^=1);return i},Cea708Stream.prototype.clearWindows=function(i,service){var b=this.current708Packet.data[++i],pts=this.getPts(i);this.flushDisplayed(pts,service);for(var winId=0;winId<8;winId++)b&1<<winId&&service.windows[winId].clearText();return i},Cea708Stream.prototype.deleteWindows=function(i,service){var b=this.current708Packet.data[++i],pts=this.getPts(i);this.flushDisplayed(pts,service);for(var winId=0;winId<8;winId++)b&1<<winId&&service.windows[winId].reset();return i},Cea708Stream.prototype.setPenAttributes=function(i,service){var packetData=this.current708Packet.data,b=packetData[i],penAttr=service.currentWindow.penAttr;return b=packetData[++i],penAttr.textTag=(240&b)>>4,penAttr.offset=(12&b)>>2,penAttr.penSize=3&b,b=packe
tData[++i],penAttr.italics=(128&b)>>7,penAttr.underline=(64&b)>>6,penAttr.edgeType=(56&b)>>3,penAttr.fontStyle=7&b,i},Cea708Stream.prototype.setPenColor=function(i,service){var packetData=this.current708Packet.data,b=packetData[i],penColor=service.currentWindow.penColor;return b=packetData[++i],penColor.fgOpacity=(192&b)>>6,penColor.fgRed=(48&b)>>4,penColor.fgGreen=(12&b)>>2,penColor.fgBlue=3&b,b=packetData[++i],penColor.bgOpacity=(192&b)>>6,penColor.bgRed=(48&b)>>4,penColor.bgGreen=(12&b)>>2,penColor.bgBlue=3&b,b=packetData[++i],penColor.edgeRed=(48&b)>>4,penColor.edgeGreen=(12&b)>>2,penColor.edgeBlue=3&b,i},Cea708Stream.prototype.setPenLocation=function(i,service){var packetData=this.current708Packet.data,b=packetData[i],penLoc=service.currentWindow.penLoc;return service.currentWindow.pendingNewLine=!0,b=packetData[++i],penLoc.row=15&b,b=packetData[++i],penLoc.column=63&b,i},Cea708Stream.prototype.reset=function(i,service){var pts=this.getPts(i);return this.flushDisplayed(pts,service),this.initService(serv
ice.serviceNum,i)};var CHARACTER_TRANSLATION={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},getCharFromCode=function(code){return null===code?"":(code=CHARACTER_TRANSLATION[code]||code,String.fromCharCode(code))},ROWS=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],createDisplayBuffer=function(){for(var result=[],
i=15;i--;)result.push({text:"",indent:0,offset:0});return result},Cea608Stream=function(field,dataChannel){Cea608Stream.prototype.init.call(this),this.field_=field||0,this.dataChannel_=dataChannel||0,this.name_="CC"+(1+(this.field_<<1|this.dataChannel_)),this.setConstants(),this.reset(),this.push=function(packet){var data,swap,char0,char1,text;if((data=32639&packet.ccData)!==this.lastControlCode_){if(4096==(61440&data)?this.lastControlCode_=data:data!==this.PADDING_&&(this.lastControlCode_=null),char0=data>>>8,char1=255&data,data!==this.PADDING_)if(data===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(data===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(packet.pts),this.flushDisplayed(packet.pts),swap=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=swap,this.startPts_=packet.pts;else if(data===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(packet.pts);else if(data===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(packet.pts);else if(data===this.ROL
L_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(packet.pts);else if(data===this.CARRIAGE_RETURN_)this.clearFormatting(packet.pts),this.flushDisplayed(packet.pts),this.shiftRowsUp_(),this.startPts_=packet.pts;else if(data===this.BACKSPACE_)"popOn"===this.mode_?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1);else if(data===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(packet.pts),this.displayed_=createDisplayBuffer();else if(data===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=createDisplayBuffer();else if(data===this.RESUME_DIRECT_CAPTIONING_)"paintOn"!==this.mode_&&(this.flushDisplayed(packet.pts),this.displayed_=createDisplayBuffer()),this.mode_="paintOn",this.startPts_=packet.pts;else if(this.isSpecialCharacter(char0,char1))text=getCharFromCode((char0=(3&char0)<<8)|char1),this[this.mode_](packet.pts,text),this.column_++;else if(this.isExtCharacter(char0,char1))"popOn"===this.mode_?this.nonD
isplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),text=getCharFromCode((char0=(3&char0)<<8)|char1),this[this.mode_](packet.pts,text),this.column_++;else if(this.isMidRowCode(char0,char1))this.clearFormatting(packet.pts),this[this.mode_](packet.pts," "),this.column_++,14==(14&char1)&&this.addFormatting(packet.pts,["i"]),1==(1&char1)&&this.addFormatting(packet.pts,["u"]);else if(this.isOffsetControlCode(char0,char1)){const offset=3&char1;this.nonDisplayed_[this.row_].offset=offset,this.column_+=offset}else if(this.isPAC(char0,char1)){var row=ROWS.indexOf(7968&data);if("rollUp"===this.mode_&&(row-this.rollUpRows_+1<0&&(row=this.rollUpRows_-1),this.setRollUp(packet.pts,row)),row!==this.row_&&(this.clearFormatting(packet.pts),this.row_=row),1&char1&&-1===this.formatting_.indexOf("u")&&this.addFormatting(packet.pts,["u"]),16==(16&data)){const indentations=(14&data)>>1;this.column_=4*indentations,this.nonDisplayed_[th
is.row_].indent+=indentations}this.isColorPAC(char1)&&14==(14&char1)&&this.addFormatting(packet.pts,["i"])}else this.isNormalChar(char0)&&(0===char1&&(char1=null),text=getCharFromCode(char0),text+=getCharFromCode(char1),this[this.mode_](packet.pts,text),this.column_+=text.length)}else this.lastControlCode_=null}};Cea608Stream.prototype=new Stream$7,Cea608Stream.prototype.flushDisplayed=function(pts){const logWarning=index=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+index+"."})},content=[];this.displayed_.forEach(((row,i)=>{if(row&&row.text&&row.text.length){try{row.text=row.text.trim()}catch(e){logWarning(i)}row.text.length&&content.push({text:row.text,line:i+1,position:10+Math.min(70,10*row.indent)+2.5*row.offset})}else null==row&&logWarning(i)})),content.length&&this.trigger("data",{startPts:this.startPts_,endPts:pts,content:content,stream:this.name_})},Cea608Stream.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=crea
teDisplayBuffer(),this.nonDisplayed_=createDisplayBuffer(),this.lastControlCode_=null,this.column_=0,this.row_=14,this.rollUpRows_=2,this.formatting_=[]},Cea608Stream.prototype.setConstants=function(){0===this.dataChannel_?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):1===this.dataChannel_&&(this.BASE_=24,this.EXT_=25,this.CONTROL_=(28|this.field_)<<8,this.OFFSET_=31),this.PADDING_=0,this.RESUME_CAPTION_LOADING_=32|this.CONTROL_,this.END_OF_CAPTION_=47|this.CONTROL_,this.ROLL_UP_2_ROWS_=37|this.CONTROL_,this.ROLL_UP_3_ROWS_=38|this.CONTROL_,this.ROLL_UP_4_ROWS_=39|this.CONTROL_,this.CARRIAGE_RETURN_=45|this.CONTROL_,this.RESUME_DIRECT_CAPTIONING_=41|this.CONTROL_,this.BACKSPACE_=33|this.CONTROL_,this.ERASE_DISPLAYED_MEMORY_=44|this.CONTROL_,this.ERASE_NON_DISPLAYED_MEMORY_=46|this.CONTROL_},Cea608Stream.prototype.isSpecialCharacter=function(char0,char1){return char0===this.EXT_&&char1>=48&&char1<=63},Cea608Stream.prototype.isExtCharacter=function(char0,char1){return(char0===t
his.EXT_+1||char0===this.EXT_+2)&&char1>=32&&char1<=63},Cea608Stream.prototype.isMidRowCode=function(char0,char1){return char0===this.EXT_&&char1>=32&&char1<=47},Cea608Stream.prototype.isOffsetControlCode=function(char0,char1){return char0===this.OFFSET_&&char1>=33&&char1<=35},Cea608Stream.prototype.isPAC=function(char0,char1){return char0>=this.BASE_&&char0<this.BASE_+8&&char1>=64&&char1<=127},Cea608Stream.prototype.isColorPAC=function(char1){return char1>=64&&char1<=79||char1>=96&&char1<=127},Cea608Stream.prototype.isNormalChar=function(char){return char>=32&&char<=127},Cea608Stream.prototype.setRollUp=function(pts,newBaseRow){if("rollUp"!==this.mode_&&(this.row_=14,this.mode_="rollUp",this.flushDisplayed(pts),this.nonDisplayed_=createDisplayBuffer(),this.displayed_=createDisplayBuffer()),void 0!==newBaseRow&&newBaseRow!==this.row_)for(var i=0;i<this.rollUpRows_;i++)this.displayed_[newBaseRow-i]=this.displayed_[this.row_-i],this.displayed_[this.row_-i]={text:"",indent:0,offset:0};void 0===newBaseRow&&(newB
aseRow=this.row_),this.topRow_=newBaseRow-this.rollUpRows_+1},Cea608Stream.prototype.addFormatting=function(pts,format){this.formatting_=this.formatting_.concat(format);var text=format.reduce((function(text,format){return text+"<"+format+">"}),"");this[this.mode_](pts,text)},Cea608Stream.prototype.clearFormatting=function(pts){if(this.formatting_.length){var text=this.formatting_.reverse().reduce((function(text,format){return text+"</"+format+">"}),"");this.formatting_=[],this[this.mode_](pts,text)}},Cea608Stream.prototype.popOn=function(pts,text){var baseRow=this.nonDisplayed_[this.row_].text;baseRow+=text,this.nonDisplayed_[this.row_].text=baseRow},Cea608Stream.prototype.rollUp=function(pts,text){var baseRow=this.displayed_[this.row_].text;baseRow+=text,this.displayed_[this.row_].text=baseRow},Cea608Stream.prototype.shiftRowsUp_=function(){var i;for(i=0;i<this.topRow_;i++)this.displayed_[i]={text:"",indent:0,offset:0};for(i=this.row_+1;i<15;i++)this.displayed_[i]={text:"",indent:0,offset:0};for(i=this.topR
ow_;i<this.row_;i++)this.displayed_[i]=this.displayed_[i+1];this.displayed_[this.row_]={text:"",indent:0,offset:0}},Cea608Stream.prototype.paintOn=function(pts,text){var baseRow=this.displayed_[this.row_].text;baseRow+=text,this.displayed_[this.row_].text=baseRow};var captionStream={CaptionStream:CaptionStream$2,Cea608Stream:Cea608Stream,Cea708Stream:Cea708Stream},streamTypes={H264_STREAM_TYPE:27,ADTS_STREAM_TYPE:15,METADATA_STREAM_TYPE:21},Stream$6=stream,handleRollover$1=function(value,reference){var direction=1;for(value>reference&&(direction=-1);Math.abs(reference-value)>4294967296;)value+=8589934592*direction;return value},TimestampRolloverStream$1=function(type){var lastDTS,referenceDTS;TimestampRolloverStream$1.prototype.init.call(this),this.type_=type||"shared",this.push=function(data){"metadata"!==data.type?"shared"!==this.type_&&data.type!==this.type_||(void 0===referenceDTS&&(referenceDTS=data.dts),data.dts=handleRollover$1(data.dts,referenceDTS),data.pts=handleRollover$1(data.pts,referenceDTS),la
stDTS=data.dts,this.trigger("data",data)):this.trigger("data",data)},this.flush=function(){referenceDTS=lastDTS,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){referenceDTS=void 0,lastDTS=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};TimestampRolloverStream$1.prototype=new Stream$6;var MetadataStream,timestampRolloverStream={TimestampRolloverStream:TimestampRolloverStream$1,handleRollover:handleRollover$1},typedArray_typedArrayIndexOf=(typedArray,element,fromIndex)=>{if(!typedArray)return-1;for(var currentIndex=fromIndex;currentIndex<typedArray.length;currentIndex++)if(typedArray[currentIndex]===element)return currentIndex;return-1},typedArrayIndexOf=typedArray_typedArrayIndexOf,textEncodingDescriptionByte_Utf8=3,percentEncode$1=function(bytes,start,end){var i,result="";for(i=start;i<end;i++)result+="%"+("00"+bytes[i].toString(16)).slice(-2);return result},parseUtf8=function(bytes,start,end){return decode
URIComponent(percentEncode$1(bytes,start,end))},parseIso88591$1=function(bytes,start,end){return unescape(percentEncode$1(bytes,start,end))},parseSyncSafeInteger$1=function(data){return data[0]<<21|data[1]<<14|data[2]<<7|data[3]},frameParsers={APIC:function(frame){var mimeTypeEndIndex,descriptionEndIndex,i=1;frame.data[0]===textEncodingDescriptionByte_Utf8&&((mimeTypeEndIndex=typedArrayIndexOf(frame.data,0,i))<0||(frame.mimeType=parseIso88591$1(frame.data,i,mimeTypeEndIndex),i=mimeTypeEndIndex+1,frame.pictureType=frame.data[i],i++,(descriptionEndIndex=typedArrayIndexOf(frame.data,0,i))<0||(frame.description=parseUtf8(frame.data,i,descriptionEndIndex),i=descriptionEndIndex+1,"--\x3e"===frame.mimeType?frame.url=parseIso88591$1(frame.data,i,frame.data.length):frame.pictureData=frame.data.subarray(i,frame.data.length))))},"T*":function(frame){frame.data[0]===textEncodingDescriptionByte_Utf8&&(frame.value=parseUtf8(frame.data,1,frame.data.length).replace(/\0*$/,""),frame.values=frame.value.split("\0"))},TXXX:func
tion(frame){var descriptionEndIndex;frame.data[0]===textEncodingDescriptionByte_Utf8&&-1!==(descriptionEndIndex=typedArrayIndexOf(frame.data,0,1))&&(frame.description=parseUtf8(frame.data,1,descriptionEndIndex),frame.value=parseUtf8(frame.data,descriptionEndIndex+1,frame.data.length).replace(/\0*$/,""),frame.data=frame.value)},"W*":function(frame){frame.url=parseIso88591$1(frame.data,0,frame.data.length).replace(/\0.*$/,"")},WXXX:function(frame){var descriptionEndIndex;frame.data[0]===textEncodingDescriptionByte_Utf8&&-1!==(descriptionEndIndex=typedArrayIndexOf(frame.data,0,1))&&(frame.description=parseUtf8(frame.data,1,descriptionEndIndex),frame.url=parseIso88591$1(frame.data,descriptionEndIndex+1,frame.data.length).replace(/\0.*$/,""))},PRIV:function(frame){var i;for(i=0;i<frame.data.length;i++)if(0===frame.data[i]){frame.owner=parseIso88591$1(frame.data,0,i);break}frame.privateData=frame.data.subarray(i+1),frame.data=frame.privateData}},parseId3={parseId3Frames:function(data){var frameSize,frameStart=10,t
agSize=0,frames=[];if(!(data.length<10||data[0]!=="I".charCodeAt(0)||data[1]!=="D".charCodeAt(0)||data[2]!=="3".charCodeAt(0))){tagSize=parseSyncSafeInteger$1(data.subarray(6,10)),tagSize+=10,64&data[5]&&(frameStart+=4,frameStart+=parseSyncSafeInteger$1(data.subarray(10,14)),tagSize-=parseSyncSafeInteger$1(data.subarray(16,20)));do{if((frameSize=parseSyncSafeInteger$1(data.subarray(frameStart+4,frameStart+8)))<1)break;var frame={id:String.fromCharCode(data[frameStart],data[frameStart+1],data[frameStart+2],data[frameStart+3]),data:data.subarray(frameStart+10,frameStart+frameSize+10)};frame.key=frame.id,frameParsers[frame.id]?frameParsers[frame.id](frame):"T"===frame.id[0]?frameParsers["T*"](frame):"W"===frame.id[0]&&frameParsers["W*"](frame),frames.push(frame),frameStart+=10,frameStart+=frameSize}while(frameStart<tagSize);return frames}},parseSyncSafeInteger:parseSyncSafeInteger$1,frameParsers:frameParsers},StreamTypes$3=streamTypes,id3=parseId3;(MetadataStream=function(options){var i,settings={descriptor:opt
ions&&options.descriptor},tagSize=0,buffer=[],bufferSize=0;if(MetadataStream.prototype.init.call(this),this.dispatchType=StreamTypes$3.METADATA_STREAM_TYPE.toString(16),settings.descriptor)for(i=0;i<settings.descriptor.length;i++)this.dispatchType+=("00"+settings.descriptor[i].toString(16)).slice(-2);this.push=function(chunk){var tag,frameStart,frameSize,frame,i;if("timed-metadata"===chunk.type)if(chunk.dataAlignmentIndicator&&(bufferSize=0,buffer.length=0),0===buffer.length&&(chunk.data.length<10||chunk.data[0]!=="I".charCodeAt(0)||chunk.data[1]!=="D".charCodeAt(0)||chunk.data[2]!=="3".charCodeAt(0)))this.trigger("log",{level:"warn",message:"Skipping unrecognized metadata packet"});else if(buffer.push(chunk),bufferSize+=chunk.data.byteLength,1===buffer.length&&(tagSize=id3.parseSyncSafeInteger(chunk.data.subarray(6,10)),tagSize+=10),!(bufferSize<tagSize)){for(tag={data:new Uint8Array(tagSize),frames:[],pts:buffer[0].pts,dts:buffer[0].dts},i=0;i<tagSize;)tag.data.set(buffer[0].data.subarray(0,tagSize-i),i),i
+=buffer[0].data.byteLength,bufferSize-=buffer[0].data.byteLength,buffer.shift();frameStart=10,64&tag.data[5]&&(frameStart+=4,frameStart+=id3.parseSyncSafeInteger(tag.data.subarray(10,14)),tagSize-=id3.parseSyncSafeInteger(tag.data.subarray(16,20)));do{if((frameSize=id3.parseSyncSafeInteger(tag.data.subarray(frameStart+4,frameStart+8)))<1){this.trigger("log",{level:"warn",message:"Malformed ID3 frame encountered. Skipping remaining metadata parsing."});break}if((frame={id:String.fromCharCode(tag.data[frameStart],tag.data[frameStart+1],tag.data[frameStart+2],tag.data[frameStart+3]),data:tag.data.subarray(frameStart+10,frameStart+frameSize+10)}).key=frame.id,id3.frameParsers[frame.id]?id3.frameParsers[frame.id](frame):"T"===frame.id[0]?id3.frameParsers["T*"](frame):"W"===frame.id[0]&&id3.frameParsers["W*"](frame),"com.apple.streaming.transportStreamTimestamp"===frame.owner){var d=frame.data,size=(1&d[3])<<30|d[4]<<22|d[5]<<14|d[6]<<6|d[7]>>>2;size*=4,size+=3&d[7],frame.timeStamp=size,void 0===tag.pts&&void 0==
=tag.dts&&(tag.pts=frame.timeStamp,tag.dts=frame.timeStamp),this.trigger("timestamp",frame)}tag.frames.push(frame),frameStart+=10,frameStart+=frameSize}while(frameStart<tagSize);this.trigger("data",tag)}}}).prototype=new stream;var TransportPacketStream,TransportParseStream,ElementaryStream,metadataStream=MetadataStream,Stream$4=stream,CaptionStream$1=captionStream,StreamTypes$2=streamTypes,TimestampRolloverStream=timestampRolloverStream.TimestampRolloverStream;(TransportPacketStream=function(){var buffer=new Uint8Array(188),bytesInBuffer=0;TransportPacketStream.prototype.init.call(this),this.push=function(bytes){var everything,startIndex=0,endIndex=188;for(bytesInBuffer?((everything=new Uint8Array(bytes.byteLength+bytesInBuffer)).set(buffer.subarray(0,bytesInBuffer)),everything.set(bytes,bytesInBuffer),bytesInBuffer=0):everything=bytes;endIndex<everything.byteLength;)71!==everything[startIndex]||71!==everything[endIndex]?(startIndex++,endIndex++):(this.trigger("data",everything.subarray(startIndex,endIndex)
),startIndex+=188,endIndex+=188);startIndex<everything.byteLength&&(buffer.set(everything.subarray(startIndex),0),bytesInBuffer=everything.byteLength-startIndex)},this.flush=function(){188===bytesInBuffer&&71===buffer[0]&&(this.trigger("data",buffer),bytesInBuffer=0),this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.reset=function(){bytesInBuffer=0,this.trigger("reset")}}).prototype=new Stream$4,TransportParseStream=function(){var parsePsi,parsePat,parsePmt,self;TransportParseStream.prototype.init.call(this),self=this,this.packetsWaitingForPmt=[],this.programMapTable=void 0,parsePsi=function(payload,psi){var offset=0;psi.payloadUnitStartIndicator&&(offset+=payload[offset]+1),"pat"===psi.type?parsePat(payload.subarray(offset),psi):parsePmt(payload.subarray(offset),psi)},parsePat=function(payload,pat){pat.section_number=payload[7],pat.last_section_number=payload[8],self.pmtPid=(31&payload[10])<<8|payload[11],pat.pmtPid=self.pmtPid},parsePmt=function(payload,pmt)
{var tableEnd,offset;if(1&payload[5]){for(self.programMapTable={video:null,audio:null,"timed-metadata":{}},tableEnd=3+((15&payload[1])<<8|payload[2])-4,offset=12+((15&payload[10])<<8|payload[11]);offset<tableEnd;){var streamType=payload[offset],pid=(31&payload[offset+1])<<8|payload[offset+2];streamType===StreamTypes$2.H264_STREAM_TYPE&&null===self.programMapTable.video?self.programMapTable.video=pid:streamType===StreamTypes$2.ADTS_STREAM_TYPE&&null===self.programMapTable.audio?self.programMapTable.audio=pid:streamType===StreamTypes$2.METADATA_STREAM_TYPE&&(self.programMapTable["timed-metadata"][pid]=streamType),offset+=5+((15&payload[offset+3])<<8|payload[offset+4])}pmt.programMapTable=self.programMapTable}},this.push=function(packet){var result={},offset=4;if(result.payloadUnitStartIndicator=!!(64&packet[1]),result.pid=31&packet[1],result.pid<<=8,result.pid|=packet[2],(48&packet[3])>>>4>1&&(offset+=packet[offset]+1),0===result.pid)result.type="pat",parsePsi(packet.subarray(offset),result),this.trigger("data
",result);else if(result.pid===this.pmtPid)for(result.type="pmt",parsePsi(packet.subarray(offset),result),this.trigger("data",result);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else void 0===this.programMapTable?this.packetsWaitingForPmt.push([packet,offset,result]):this.processPes_(packet,offset,result)},this.processPes_=function(packet,offset,result){result.pid===this.programMapTable.video?result.streamType=StreamTypes$2.H264_STREAM_TYPE:result.pid===this.programMapTable.audio?result.streamType=StreamTypes$2.ADTS_STREAM_TYPE:result.streamType=this.programMapTable["timed-metadata"][result.pid],result.type="pes",result.data=packet.subarray(offset),this.trigger("data",result)}},TransportParseStream.prototype=new Stream$4,TransportParseStream.STREAM_TYPES={h264:27,adts:15},ElementaryStream=function(){var programMapTable,self=this,segmentHadPmt=!1,video={data:[],size:0},audio={data:[],size:0},timedMetadata={data:[],size:0},flushStream=function(stream,type,fo
rceFlush){var packetFlushable,fragment,packetData=new Uint8Array(stream.size),event={type:type},i=0,offset=0;if(stream.data.length&&!(stream.size<9)){for(event.trackId=stream.data[0].pid,i=0;i<stream.data.length;i++)fragment=stream.data[i],packetData.set(fragment.data,offset),offset+=fragment.data.byteLength;!function(payload,pes){var ptsDtsFlags;const startPrefix=payload[0]<<16|payload[1]<<8|payload[2];pes.data=new Uint8Array,1===startPrefix&&(pes.packetLength=6+(payload[4]<<8|payload[5]),pes.dataAlignmentIndicator=0!=(4&payload[6]),192&(ptsDtsFlags=payload[7])&&(pes.pts=(14&payload[9])<<27|(255&payload[10])<<20|(254&payload[11])<<12|(255&payload[12])<<5|(254&payload[13])>>>3,pes.pts*=4,pes.pts+=(6&payload[13])>>>1,pes.dts=pes.pts,64&ptsDtsFlags&&(pes.dts=(14&payload[14])<<27|(255&payload[15])<<20|(254&payload[16])<<12|(255&payload[17])<<5|(254&payload[18])>>>3,pes.dts*=4,pes.dts+=(6&payload[18])>>>1)),pes.data=payload.subarray(9+payload[8]))}(packetData,event),packetFlushable="video"===type||event.packetLe
ngth<=stream.size,(forceFlush||packetFlushable)&&(stream.size=0,stream.data.length=0),packetFlushable&&self.trigger("data",event)}};ElementaryStream.prototype.init.call(this),this.push=function(data){({pat:function(){},pes:function(){var stream,streamType;switch(data.streamType){case StreamTypes$2.H264_STREAM_TYPE:stream=video,streamType="video";break;case StreamTypes$2.ADTS_STREAM_TYPE:stream=audio,streamType="audio";break;case StreamTypes$2.METADATA_STREAM_TYPE:stream=timedMetadata,streamType="timed-metadata";break;default:return}data.payloadUnitStartIndicator&&flushStream(stream,streamType,!0),stream.data.push(data),stream.size+=data.data.byteLength},pmt:function(){var event={type:"metadata",tracks:[]};null!==(programMapTable=data.programMapTable).video&&event.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+programMapTable.video,codec:"avc",type:"video"}),null!==programMapTable.audio&&event.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+programMapTable.audio,codec:"adts",type:"audio
"}),segmentHadPmt=!0,self.trigger("data",event)}})[data.type]()},this.reset=function(){video.size=0,video.data.length=0,audio.size=0,audio.data.length=0,this.trigger("reset")},this.flushStreams_=function(){flushStream(video,"video"),flushStream(audio,"audio"),flushStream(timedMetadata,"timed-metadata")},this.flush=function(){if(!segmentHadPmt&&programMapTable){var pmt={type:"metadata",tracks:[]};null!==programMapTable.video&&pmt.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+programMapTable.video,codec:"avc",type:"video"}),null!==programMapTable.audio&&pmt.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+programMapTable.audio,codec:"adts",type:"audio"}),self.trigger("data",pmt)}segmentHadPmt=!1,this.flushStreams_(),this.trigger("done")}},ElementaryStream.prototype=new Stream$4;var m2ts$1={PAT_PID:0,MP2T_PACKET_LENGTH:188,TransportPacketStream:TransportPacketStream,TransportParseStream:TransportParseStream,ElementaryStream:ElementaryStream,TimestampRolloverStream:TimestampRolloverStream,
CaptionStream:CaptionStream$1.CaptionStream,Cea608Stream:CaptionStream$1.Cea608Stream,Cea708Stream:CaptionStream$1.Cea708Stream,MetadataStream:metadataStream};for(var type in StreamTypes$2)StreamTypes$2.hasOwnProperty(type)&&(m2ts$1[type]=StreamTypes$2[type]);var AdtsStream$1,m2ts_1=m2ts$1,ONE_SECOND_IN_TS$2=clock$2.ONE_SECOND_IN_TS,ADTS_SAMPLING_FREQUENCIES$1=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];(AdtsStream$1=function(handlePartialSegments){var buffer,frameNum=0;AdtsStream$1.prototype.init.call(this),this.skipWarn_=function(start,end){this.trigger("log",{level:"warn",message:"adts skiping bytes ".concat(start," to ").concat(end," in frame ").concat(frameNum," outside syncword")})},this.push=function(packet){var frameLength,protectionSkipBytes,oldBuffer,sampleCount,adtsFrameDuration,i=0;if(handlePartialSegments||(frameNum=0),"audio"===packet.type){var skip;for(buffer&&buffer.length?(oldBuffer=buffer,(buffer=new Uint8Array(oldBuffer.byteLength+packet.data.byteLength)).set(oldB
uffer),buffer.set(packet.data,oldBuffer.byteLength)):buffer=packet.data;i+7<buffer.length;)if(255===buffer[i]&&240==(246&buffer[i+1])){if("number"==typeof skip&&(this.skipWarn_(skip,i),skip=null),protectionSkipBytes=2*(1&~buffer[i+1]),frameLength=(3&buffer[i+3])<<11|buffer[i+4]<<3|(224&buffer[i+5])>>5,adtsFrameDuration=(sampleCount=1024*(1+(3&buffer[i+6])))*ONE_SECOND_IN_TS$2/ADTS_SAMPLING_FREQUENCIES$1[(60&buffer[i+2])>>>2],buffer.byteLength-i<frameLength)break;this.trigger("data",{pts:packet.pts+frameNum*adtsFrameDuration,dts:packet.dts+frameNum*adtsFrameDuration,sampleCount:sampleCount,audioobjecttype:1+(buffer[i+2]>>>6&3),channelcount:(1&buffer[i+2])<<2|(192&buffer[i+3])>>>6,samplerate:ADTS_SAMPLING_FREQUENCIES$1[(60&buffer[i+2])>>>2],samplingfrequencyindex:(60&buffer[i+2])>>>2,samplesize:16,data:buffer.subarray(i+7+protectionSkipBytes,i+frameLength)}),frameNum++,i+=frameLength}else"number"!=typeof skip&&(skip=i),i++;"number"==typeof skip&&(this.skipWarn_(skip,i),skip=null),buffer=buffer.subarray(i)}},th
is.flush=function(){frameNum=0,this.trigger("done")},this.reset=function(){buffer=void 0,this.trigger("reset")},this.endTimeline=function(){buffer=void 0,this.trigger("endedtimeline")}}).prototype=new stream;var ExpGolomb$1,adts=AdtsStream$1;ExpGolomb$1=function(workingData){var workingBytesAvailable=workingData.byteLength,workingWord=0,workingBitsAvailable=0;this.length=function(){return 8*workingBytesAvailable},this.bitsAvailable=function(){return 8*workingBytesAvailable+workingBitsAvailable},this.loadWord=function(){var position=workingData.byteLength-workingBytesAvailable,workingBytes=new Uint8Array(4),availableBytes=Math.min(4,workingBytesAvailable);if(0===availableBytes)throw new Error("no bytes available");workingBytes.set(workingData.subarray(position,position+availableBytes)),workingWord=new DataView(workingBytes.buffer).getUint32(0),workingBitsAvailable=8*availableBytes,workingBytesAvailable-=availableBytes},this.skipBits=function(count){var skipBytes;workingBitsAvailable>count?(workingWord<<=count
,workingBitsAvailable-=count):(count-=workingBitsAvailable,count-=8*(skipBytes=Math.floor(count/8)),workingBytesAvailable-=skipBytes,this.loadWord(),workingWord<<=count,workingBitsAvailable-=count)},this.readBits=function(size){var bits=Math.min(workingBitsAvailable,size),valu=workingWord>>>32-bits;return(workingBitsAvailable-=bits)>0?workingWord<<=bits:workingBytesAvailable>0&&this.loadWord(),(bits=size-bits)>0?valu<<bits|this.readBits(bits):valu},this.skipLeadingZeros=function(){var leadingZeroCount;for(leadingZeroCount=0;leadingZeroCount<workingBitsAvailable;++leadingZeroCount)if(0!=(workingWord&2147483648>>>leadingZeroCount))return workingWord<<=leadingZeroCount,workingBitsAvailable-=leadingZeroCount,leadingZeroCount;return this.loadWord(),leadingZeroCount+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var clz=this.skipLeadingZeros();retur
n this.readBits(clz+1)-1},this.readExpGolomb=function(){var valu=this.readUnsignedExpGolomb();return 1&valu?1+valu>>>1:-1*(valu>>>1)},this.readBoolean=function(){return 1===this.readBits(1)},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};var H264Stream$1,NalByteStream,PROFILES_WITH_OPTIONAL_SPS_DATA,Stream$2=stream,ExpGolomb=ExpGolomb$1;(NalByteStream=function(){var i,buffer,syncPoint=0;NalByteStream.prototype.init.call(this),this.push=function(data){var swapBuffer;buffer?((swapBuffer=new Uint8Array(buffer.byteLength+data.data.byteLength)).set(buffer),swapBuffer.set(data.data,buffer.byteLength),buffer=swapBuffer):buffer=data.data;for(var len=buffer.byteLength;syncPoint<len-3;syncPoint++)if(1===buffer[syncPoint+2]){i=syncPoint+5;break}for(;i<len;)switch(buffer[i]){case 0:if(0!==buffer[i-1]){i+=2;break}if(0!==buffer[i-2]){i++;break}syncPoint+3!==i-2&&this.trigger("data",buffer.subarray(syncPoint+3,i-2));do{i++}while(1!==buffer[i]&&i<len);syncPoint=i-2,i+=3;break;case 1:if(0!==buffer
[i-1]||0!==buffer[i-2]){i+=3;break}this.trigger("data",buffer.subarray(syncPoint+3,i-2)),syncPoint=i-2,i+=3;break;default:i+=3}buffer=buffer.subarray(syncPoint),i-=syncPoint,syncPoint=0},this.reset=function(){buffer=null,syncPoint=0,this.trigger("reset")},this.flush=function(){buffer&&buffer.byteLength>3&&this.trigger("data",buffer.subarray(syncPoint+3)),buffer=null,syncPoint=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}}).prototype=new Stream$2,PROFILES_WITH_OPTIONAL_SPS_DATA={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},H264Stream$1=function(){var self,trackId,currentPts,currentDts,discardEmulationPreventionBytes,readSequenceParameterSet,skipScalingList,nalByteStream=new NalByteStream;H264Stream$1.prototype.init.call(this),self=this,this.push=function(packet){"video"===packet.type&&(trackId=packet.trackId,currentPts=packet.pts,currentDts=packet.dts,nalByteStream.push(packet))},nalByteStream.on("data",(function(data){var
event={trackId:trackId,pts:currentPts,dts:currentDts,data:data,nalUnitTypeCode:31&data[0]};switch(event.nalUnitTypeCode){case 5:event.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:event.nalUnitType="sei_rbsp",event.escapedRBSP=discardEmulationPreventionBytes(data.subarray(1));break;case 7:event.nalUnitType="seq_parameter_set_rbsp",event.escapedRBSP=discardEmulationPreventionBytes(data.subarray(1)),event.config=readSequenceParameterSet(event.escapedRBSP);break;case 8:event.nalUnitType="pic_parameter_set_rbsp";break;case 9:event.nalUnitType="access_unit_delimiter_rbsp"}self.trigger("data",event)})),nalByteStream.on("done",(function(){self.trigger("done")})),nalByteStream.on("partialdone",(function(){self.trigger("partialdone")})),nalByteStream.on("reset",(function(){self.trigger("reset")})),nalByteStream.on("endedtimeline",(function(){self.trigger("endedtimeline")})),this.flush=function(){nalByteStream.flush()},this.partialFlush=function(){nalByteStream.partialFlush()},this.reset=functio
n(){nalByteStream.reset()},this.endTimeline=function(){nalByteStream.endTimeline()},skipScalingList=function(count,expGolombDecoder){var j,lastScale=8,nextScale=8;for(j=0;j<count;j++)0!==nextScale&&(nextScale=(lastScale+expGolombDecoder.readExpGolomb()+256)%256),lastScale=0===nextScale?lastScale:nextScale},discardEmulationPreventionBytes=function(data){for(var newLength,newData,length=data.byteLength,emulationPreventionBytesPositions=[],i=1;i<length-2;)0===data[i]&&0===data[i+1]&&3===data[i+2]?(emulationPreventionBytesPositions.push(i+2),i+=2):i++;if(0===emulationPreventionBytesPositions.length)return data;newLength=length-emulationPreventionBytesPositions.length,newData=new Uint8Array(newLength);var sourceIndex=0;for(i=0;i<newLength;sourceIndex++,i++)sourceIndex===emulationPreventionBytesPositions[0]&&(sourceIndex++,emulationPreventionBytesPositions.shift()),newData[i]=data[sourceIndex];return newData},readSequenceParameterSet=function(data){var expGolombDecoder,profileIdc,levelIdc,profileCompatibility,chro
maFormatIdc,picOrderCntType,numRefFramesInPicOrderCntCycle,picWidthInMbsMinus1,picHeightInMapUnitsMinus1,frameMbsOnlyFlag,scalingListCount,i,frameCropLeftOffset=0,frameCropRightOffset=0,frameCropTopOffset=0,frameCropBottomOffset=0,sarRatio=[1,1];if(profileIdc=(expGolombDecoder=new ExpGolomb(data)).readUnsignedByte(),profileCompatibility=expGolombDecoder.readUnsignedByte(),levelIdc=expGolombDecoder.readUnsignedByte(),expGolombDecoder.skipUnsignedExpGolomb(),PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]&&(3===(chromaFormatIdc=expGolombDecoder.readUnsignedExpGolomb())&&expGolombDecoder.skipBits(1),expGolombDecoder.skipUnsignedExpGolomb(),expGolombDecoder.skipUnsignedExpGolomb(),expGolombDecoder.skipBits(1),expGolombDecoder.readBoolean()))for(scalingListCount=3!==chromaFormatIdc?8:12,i=0;i<scalingListCount;i++)expGolombDecoder.readBoolean()&&skipScalingList(i<6?16:64,expGolombDecoder);if(expGolombDecoder.skipUnsignedExpGolomb(),0===(picOrderCntType=expGolombDecoder.readUnsignedExpGolomb()))expGolombDecoder.readUns
ignedExpGolomb();else if(1===picOrderCntType)for(expGolombDecoder.skipBits(1),expGolombDecoder.skipExpGolomb(),expGolombDecoder.skipExpGolomb(),numRefFramesInPicOrderCntCycle=expGolombDecoder.readUnsignedExpGolomb(),i=0;i<numRefFramesInPicOrderCntCycle;i++)expGolombDecoder.skipExpGolomb();if(expGolombDecoder.skipUnsignedExpGolomb(),expGolombDecoder.skipBits(1),picWidthInMbsMinus1=expGolombDecoder.readUnsignedExpGolomb(),picHeightInMapUnitsMinus1=expGolombDecoder.readUnsignedExpGolomb(),0===(frameMbsOnlyFlag=expGolombDecoder.readBits(1))&&expGolombDecoder.skipBits(1),expGolombDecoder.skipBits(1),expGolombDecoder.readBoolean()&&(frameCropLeftOffset=expGolombDecoder.readUnsignedExpGolomb(),frameCropRightOffset=expGolombDecoder.readUnsignedExpGolomb(),frameCropTopOffset=expGolombDecoder.readUnsignedExpGolomb(),frameCropBottomOffset=expGolombDecoder.readUnsignedExpGolomb()),expGolombDecoder.readBoolean()&&expGolombDecoder.readBoolean()){switch(expGolombDecoder.readUnsignedByte()){case 1:sarRatio=[1,1];break;case
2:sarRatio=[12,11];break;case 3:sarRatio=[10,11];break;case 4:sarRatio=[16,11];break;case 5:sarRatio=[40,33];break;case 6:sarRatio=[24,11];break;case 7:sarRatio=[20,11];break;case 8:sarRatio=[32,11];break;case 9:sarRatio=[80,33];break;case 10:sarRatio=[18,11];break;case 11:sarRatio=[15,11];break;case 12:sarRatio=[64,33];break;case 13:sarRatio=[160,99];break;case 14:sarRatio=[4,3];break;case 15:sarRatio=[3,2];break;case 16:sarRatio=[2,1];break;case 255:sarRatio=[expGolombDecoder.readUnsignedByte()<<8|expGolombDecoder.readUnsignedByte(),expGolombDecoder.readUnsignedByte()<<8|expGolombDecoder.readUnsignedByte()]}sarRatio&&(sarRatio[0],sarRatio[1])}return{profileIdc:profileIdc,levelIdc:levelIdc,profileCompatibility:profileCompatibility,width:16*(picWidthInMbsMinus1+1)-2*frameCropLeftOffset-2*frameCropRightOffset,height:(2-frameMbsOnlyFlag)*(picHeightInMapUnitsMinus1+1)*16-2*frameCropTopOffset-2*frameCropBottomOffset,sarRatio:sarRatio}}},H264Stream$1.prototype=new Stream$2;var AacStream$1,h264={H264Stream:H264Str
eam$1,NalByteStream:NalByteStream},ADTS_SAMPLING_FREQUENCIES=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],parseId3TagSize=function(header,byteIndex){var returnSize=header[byteIndex+6]<<21|header[byteIndex+7]<<14|header[byteIndex+8]<<7|header[byteIndex+9];return returnSize=returnSize>=0?returnSize:0,(16&header[byteIndex+5])>>4?returnSize+20:returnSize+10},getId3Offset=function(data,offset){return data.length-offset<10||data[offset]!=="I".charCodeAt(0)||data[offset+1]!=="D".charCodeAt(0)||data[offset+2]!=="3".charCodeAt(0)?offset:(offset+=parseId3TagSize(data,offset),getId3Offset(data,offset))},parseSyncSafeInteger=function(data){return data[0]<<21|data[1]<<14|data[2]<<7|data[3]},utils={isLikelyAacData:function(data){var offset=getId3Offset(data,0);return data.length>=offset+2&&255==(255&data[offset])&&240==(240&data[offset+1])&&16==(22&data[offset+1])},parseId3TagSize:parseId3TagSize,parseAdtsSize:function(header,byteIndex){var lowThree=(224&header[byteIndex+5])>>5,middle=header[byteI
ndex+4]<<3;return 6144&header[byteIndex+3]|middle|lowThree},parseType:function(header,byteIndex){return header[byteIndex]==="I".charCodeAt(0)&&header[byteIndex+1]==="D".charCodeAt(0)&&header[byteIndex+2]==="3".charCodeAt(0)?"timed-metadata":!0&header[byteIndex]&&240==(240&header[byteIndex+1])?"audio":null},parseSampleRate:function(packet){for(var i=0;i+5<packet.length;){if(255===packet[i]&&240==(246&packet[i+1]))return ADTS_SAMPLING_FREQUENCIES[(60&packet[i+2])>>>2];i++}return null},parseAacTimestamp:function(packet){var frameStart,frameSize,frame;frameStart=10,64&packet[5]&&(frameStart+=4,frameStart+=parseSyncSafeInteger(packet.subarray(10,14)));do{if((frameSize=parseSyncSafeInteger(packet.subarray(frameStart+4,frameStart+8)))<1)return null;if("PRIV"===String.fromCharCode(packet[frameStart],packet[frameStart+1],packet[frameStart+2],packet[frameStart+3])){frame=packet.subarray(frameStart+10,frameStart+frameSize+10);for(var i=0;i<frame.byteLength;i++)if(0===frame[i]){var owner=unescape(function(bytes,start,en
d){var i,result="";for(i=start;i<end;i++)result+="%"+("00"+bytes[i].toString(16)).slice(-2);return result}(frame,0,i));if("com.apple.streaming.transportStreamTimestamp"===owner){var d=frame.subarray(i+1),size=(1&d[3])<<30|d[4]<<22|d[5]<<14|d[6]<<6|d[7]>>>2;return size*=4,size+=3&d[7]}break}}frameStart+=10,frameStart+=frameSize}while(frameStart<packet.byteLength);return null}},aacUtils=utils;(AacStream$1=function(){var everything=new Uint8Array,timeStamp=0;AacStream$1.prototype.init.call(this),this.setTimestamp=function(timestamp){timeStamp=timestamp},this.push=function(bytes){var bytesLeft,chunk,packet,tempLength,frameSize=0,byteIndex=0;for(everything.length?(tempLength=everything.length,(everything=new Uint8Array(bytes.byteLength+tempLength)).set(everything.subarray(0,tempLength)),everything.set(bytes,tempLength)):everything=bytes;everything.length-byteIndex>=3;)if(everything[byteIndex]!=="I".charCodeAt(0)||everything[byteIndex+1]!=="D".charCodeAt(0)||everything[byteIndex+2]!=="3".charCodeAt(0))if(255!=(255
&everything[byteIndex])||240!=(240&everything[byteIndex+1]))byteIndex++;else{if(everything.length-byteIndex<7)break;if(byteIndex+(frameSize=aacUtils.parseAdtsSize(everything,byteIndex))>everything.length)break;packet={type:"audio",data:everything.subarray(byteIndex,byteIndex+frameSize),pts:timeStamp,dts:timeStamp},this.trigger("data",packet),byteIndex+=frameSize}else{if(everything.length-byteIndex<10)break;if(byteIndex+(frameSize=aacUtils.parseId3TagSize(everything,byteIndex))>everything.length)break;chunk={type:"timed-metadata",data:everything.subarray(byteIndex,byteIndex+frameSize)},this.trigger("data",chunk),byteIndex+=frameSize}bytesLeft=everything.length-byteIndex,everything=bytesLeft>0?everything.subarray(byteIndex):new Uint8Array},this.reset=function(){everything=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){everything=new Uint8Array,this.trigger("endedtimeline")}}).prototype=new stream;var VideoSegmentStream,AudioSegmentStream,Transmuxer,CoalesceStream,Stream=stream,mp4=mp4Generat
or,frameUtils=frameUtils$1,audioFrameUtils=audioFrameUtils$1,trackDecodeInfo=trackDecodeInfo$1,m2ts=m2ts_1,clock=clock$2,AdtsStream=adts,H264Stream=h264.H264Stream,AacStream=AacStream$1,isLikelyAacData=utils.isLikelyAacData,ONE_SECOND_IN_TS$1=clock$2.ONE_SECOND_IN_TS,AUDIO_PROPERTIES=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],VIDEO_PROPERTIES=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],retriggerForStream=function(key,event){event.stream=key,this.trigger("log",event)},addPipelineLogRetriggers=function(transmuxer,pipeline){for(var keys=Object.keys(pipeline),i=0;i<keys.length;i++){var key=keys[i];"headOfPipeline"!==key&&pipeline[key].on&&pipeline[key].on("log",retriggerForStream.bind(transmuxer,key))}},arrayEquals=function(a,b){var i;if(a.length!==b.length)return!1;for(i=0;i<a.length;i++)if(a[i]!==b[i])return!1;return!0},generateSegmentTimingInfo=function(baseMediaDecodeTime,startDts,startPts,endDts,endPts,prependedContentDuration){retu
rn{start:{dts:baseMediaDecodeTime,pts:baseMediaDecodeTime+(startPts-startDts)},end:{dts:baseMediaDecodeTime+(endDts-startDts),pts:baseMediaDecodeTime+(endPts-startPts)},prependedContentDuration:prependedContentDuration,baseMediaDecodeTime:baseMediaDecodeTime}};AudioSegmentStream=function(track,options){var sequenceNumber,adtsFrames=[],earliestAllowedDts=0,audioAppendStartTs=0,videoBaseMediaDecodeTime=1/0;sequenceNumber=(options=options||{}).firstSequenceNumber||0,AudioSegmentStream.prototype.init.call(this),this.push=function(data){trackDecodeInfo.collectDtsInfo(track,data),track&&AUDIO_PROPERTIES.forEach((function(prop){track[prop]=data[prop]})),adtsFrames.push(data)},this.setEarliestDts=function(earliestDts){earliestAllowedDts=earliestDts},this.setVideoBaseMediaDecodeTime=function(baseMediaDecodeTime){videoBaseMediaDecodeTime=baseMediaDecodeTime},this.setAudioAppendStart=function(timestamp){audioAppendStartTs=timestamp},this.flush=function(){var frames,moof,mdat,boxes,frameDuration,segmentDuration,videoClo
ckCyclesOfSilencePrefixed;0!==adtsFrames.length?(frames=audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames,track,earliestAllowedDts),track.baseMediaDecodeTime=trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track,options.keepOriginalTimestamps),videoClockCyclesOfSilencePrefixed=audioFrameUtils.prefixWithSilence(track,frames,audioAppendStartTs,videoBaseMediaDecodeTime),track.samples=audioFrameUtils.generateSampleTable(frames),mdat=mp4.mdat(audioFrameUtils.concatenateFrameData(frames)),adtsFrames=[],moof=mp4.moof(sequenceNumber,[track]),boxes=new Uint8Array(moof.byteLength+mdat.byteLength),sequenceNumber++,boxes.set(moof),boxes.set(mdat,moof.byteLength),trackDecodeInfo.clearDtsInfo(track),frameDuration=Math.ceil(1024*ONE_SECOND_IN_TS$1/track.samplerate),frames.length&&(segmentDuration=frames.length*frameDuration,this.trigger("segmentTimingInfo",generateSegmentTimingInfo(clock.audioTsToVideoTs(track.baseMediaDecodeTime,track.samplerate),frames[0].dts,frames[0].pts,frames[0].dts+segmentDuration,frames[0].p
ts+segmentDuration,videoClockCyclesOfSilencePrefixed||0)),this.trigger("timingInfo",{start:frames[0].pts,end:frames[0].pts+segmentDuration})),this.trigger("data",{track:track,boxes:boxes}),this.trigger("done","AudioSegmentStream")):this.trigger("done","AudioSegmentStream")},this.reset=function(){trackDecodeInfo.clearDtsInfo(track),adtsFrames=[],this.trigger("reset")}},AudioSegmentStream.prototype=new Stream,VideoSegmentStream=function(track,options){var sequenceNumber,config,pps,nalUnits=[],gopsToAlignWith=[];sequenceNumber=(options=options||{}).firstSequenceNumber||0,VideoSegmentStream.prototype.init.call(this),delete track.minPTS,this.gopCache_=[],this.push=function(nalUnit){trackDecodeInfo.collectDtsInfo(track,nalUnit),"seq_parameter_set_rbsp"!==nalUnit.nalUnitType||config||(config=nalUnit.config,track.sps=[nalUnit.data],VIDEO_PROPERTIES.forEach((function(prop){track[prop]=config[prop]}),this)),"pic_parameter_set_rbsp"!==nalUnit.nalUnitType||pps||(pps=nalUnit.data,track.pps=[nalUnit.data]),nalUnits.push(n
alUnit)},this.flush=function(){for(var frames,gopForFusion,gops,moof,mdat,boxes,firstGop,lastGop,prependedContentDuration=0;nalUnits.length&&"access_unit_delimiter_rbsp"!==nalUnits[0].nalUnitType;)nalUnits.shift();if(0===nalUnits.length)return this.resetStream_(),void this.trigger("done","VideoSegmentStream");if(frames=frameUtils.groupNalsIntoFrames(nalUnits),(gops=frameUtils.groupFramesIntoGops(frames))[0][0].keyFrame||((gopForFusion=this.getGopForFusion_(nalUnits[0],track))?(prependedContentDuration=gopForFusion.duration,gops.unshift(gopForFusion),gops.byteLength+=gopForFusion.byteLength,gops.nalCount+=gopForFusion.nalCount,gops.pts=gopForFusion.pts,gops.dts=gopForFusion.dts,gops.duration+=gopForFusion.duration):gops=frameUtils.extendFirstKeyFrame(gops)),gopsToAlignWith.length){var alignedGops;if(!(alignedGops=options.alignGopsAtEnd?this.alignGopsAtEnd_(gops):this.alignGopsAtStart_(gops)))return this.gopCache_.unshift({gop:gops.pop(),pps:track.pps,sps:track.sps}),this.gopCache_.length=Math.min(6,this.gopCa
che_.length),nalUnits=[],this.resetStream_(),void this.trigger("done","VideoSegmentStream");trackDecodeInfo.clearDtsInfo(track),gops=alignedGops}trackDecodeInfo.collectDtsInfo(track,gops),track.samples=frameUtils.generateSampleTable(gops),mdat=mp4.mdat(frameUtils.concatenateNalData(gops)),track.baseMediaDecodeTime=trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track,options.keepOriginalTimestamps),this.trigger("processedGopsInfo",gops.map((function(gop){return{pts:gop.pts,dts:gop.dts,byteLength:gop.byteLength}}))),firstGop=gops[0],lastGop=gops[gops.length-1],this.trigger("segmentTimingInfo",generateSegmentTimingInfo(track.baseMediaDecodeTime,firstGop.dts,firstGop.pts,lastGop.dts+lastGop.duration,lastGop.pts+lastGop.duration,prependedContentDuration)),this.trigger("timingInfo",{start:gops[0].pts,end:gops[gops.length-1].pts+gops[gops.length-1].duration}),this.gopCache_.unshift({gop:gops.pop(),pps:track.pps,sps:track.sps}),this.gopCache_.length=Math.min(6,this.gopCache_.length),nalUnits=[],this.trigger("base
MediaDecodeTime",track.baseMediaDecodeTime),this.trigger("timelineStartInfo",track.timelineStartInfo),moof=mp4.moof(sequenceNumber,[track]),boxes=new Uint8Array(moof.byteLength+mdat.byteLength),sequenceNumber++,boxes.set(moof),boxes.set(mdat,moof.byteLength),this.trigger("data",{track:track,boxes:boxes}),this.resetStream_(),this.trigger("done","VideoSegmentStream")},this.reset=function(){this.resetStream_(),nalUnits=[],this.gopCache_.length=0,gopsToAlignWith.length=0,this.trigger("reset")},this.resetStream_=function(){trackDecodeInfo.clearDtsInfo(track),config=void 0,pps=void 0},this.getGopForFusion_=function(nalUnit){var dtsDistance,nearestGopObj,currentGop,currentGopObj,i,nearestDistance=1/0;for(i=0;i<this.gopCache_.length;i++)currentGop=(currentGopObj=this.gopCache_[i]).gop,track.pps&&arrayEquals(track.pps[0],currentGopObj.pps[0])&&track.sps&&arrayEquals(track.sps[0],currentGopObj.sps[0])&&(currentGop.dts<track.timelineStartInfo.dts||(dtsDistance=nalUnit.dts-currentGop.dts-currentGop.duration)>=-1e4&&dtsD
istance<=45e3&&(!nearestGopObj||nearestDistance>dtsDistance)&&(nearestGopObj=currentGopObj,nearestDistance=dtsDistance));return nearestGopObj?nearestGopObj.gop:null},this.alignGopsAtStart_=function(gops){var alignIndex,gopIndex,align,gop,byteLength,nalCount,duration,alignedGops;for(byteLength=gops.byteLength,nalCount=gops.nalCount,duration=gops.duration,alignIndex=gopIndex=0;alignIndex<gopsToAlignWith.length&&gopIndex<gops.length&&(align=gopsToAlignWith[alignIndex],gop=gops[gopIndex],align.pts!==gop.pts);)gop.pts>align.pts?alignIndex++:(gopIndex++,byteLength-=gop.byteLength,nalCount-=gop.nalCount,duration-=gop.duration);return 0===gopIndex?gops:gopIndex===gops.length?null:((alignedGops=gops.slice(gopIndex)).byteLength=byteLength,alignedGops.duration=duration,alignedGops.nalCount=nalCount,alignedGops.pts=alignedGops[0].pts,alignedGops.dts=alignedGops[0].dts,alignedGops)},this.alignGopsAtEnd_=function(gops){var alignIndex,gopIndex,align,gop,alignEndIndex,matchFound,trimIndex;for(alignIndex=gopsToAlignWith.leng
th-1,gopIndex=gops.length-1,alignEndIndex=null,matchFound=!1;alignIndex>=0&&gopIndex>=0;){if(align=gopsToAlignWith[alignIndex],gop=gops[gopIndex],align.pts===gop.pts){matchFound=!0;break}align.pts>gop.pts?alignIndex--:(alignIndex===gopsToAlignWith.length-1&&(alignEndIndex=gopIndex),gopIndex--)}if(!matchFound&&null===alignEndIndex)return null;if(0===(trimIndex=matchFound?gopIndex:alignEndIndex))return gops;var alignedGops=gops.slice(trimIndex),metadata=alignedGops.reduce((function(total,gop){return total.byteLength+=gop.byteLength,total.duration+=gop.duration,total.nalCount+=gop.nalCount,total}),{byteLength:0,duration:0,nalCount:0});return alignedGops.byteLength=metadata.byteLength,alignedGops.duration=metadata.duration,alignedGops.nalCount=metadata.nalCount,alignedGops.pts=alignedGops[0].pts,alignedGops.dts=alignedGops[0].dts,alignedGops},this.alignGopsWith=function(newGopsToAlignWith){gopsToAlignWith=newGopsToAlignWith}},VideoSegmentStream.prototype=new Stream,CoalesceStream=function(options,metadataStream)
{this.numberOfTracks=0,this.metadataStream=metadataStream,void 0!==(options=options||{}).remux?this.remuxTracks=!!options.remux:this.remuxTracks=!0,"boolean"==typeof options.keepOriginalTimestamps?this.keepOriginalTimestamps=options.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,CoalesceStream.prototype.init.call(this),this.push=function(output){return output.content||output.text?this.pendingCaptions.push(output):output.frames?this.pendingMetadata.push(output):(this.pendingTracks.push(output.track),this.pendingBytes+=output.boxes.byteLength,"video"===output.track.type&&(this.videoTrack=output.track,this.pendingBoxes.push(output.boxes)),void("audio"===output.track.type&&(this.audioTrack=output.track,this.pendingBoxes.unshift(output.boxes))))}},CoalesceStream.prototype=new Stream,CoalesceStream.prototype.flush=function(flushSource){var caption,id3,initS
egment,i,offset=0,event={captions:[],captionStreams:{},metadata:[],info:{}},timelineStartPts=0;if(this.pendingTracks.length<this.numberOfTracks){if("VideoSegmentStream"!==flushSource&&"AudioSegmentStream"!==flushSource)return;if(this.remuxTracks)return;if(0===this.pendingTracks.length)return this.emittedTracks++,void(this.emittedTracks>=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0))}if(this.videoTrack?(timelineStartPts=this.videoTrack.timelineStartInfo.pts,VIDEO_PROPERTIES.forEach((function(prop){event.info[prop]=this.videoTrack[prop]}),this)):this.audioTrack&&(timelineStartPts=this.audioTrack.timelineStartInfo.pts,AUDIO_PROPERTIES.forEach((function(prop){event.info[prop]=this.audioTrack[prop]}),this)),this.videoTrack||this.audioTrack){for(1===this.pendingTracks.length?event.type=this.pendingTracks[0].type:event.type="combined",this.emittedTracks+=this.pendingTracks.length,initSegment=mp4.initSegment(this.pendingTracks),event.initSegment=new Uint8Array(initSegment.byteLength),event.initSeg
ment.set(initSegment),event.data=new Uint8Array(this.pendingBytes),i=0;i<this.pendingBoxes.length;i++)event.data.set(this.pendingBoxes[i],offset),offset+=this.pendingBoxes[i].byteLength;for(i=0;i<this.pendingCaptions.length;i++)(caption=this.pendingCaptions[i]).startTime=clock.metadataTsToSeconds(caption.startPts,timelineStartPts,this.keepOriginalTimestamps),caption.endTime=clock.metadataTsToSeconds(caption.endPts,timelineStartPts,this.keepOriginalTimestamps),event.captionStreams[caption.stream]=!0,event.captions.push(caption);for(i=0;i<this.pendingMetadata.length;i++)(id3=this.pendingMetadata[i]).cueTime=clock.metadataTsToSeconds(id3.pts,timelineStartPts,this.keepOriginalTimestamps),event.metadata.push(id3);for(event.metadata.dispatchType=this.metadataStream.dispatchType,this.pendingTracks.length=0,this.videoTrack=null,this.pendingBoxes.length=0,this.pendingCaptions.length=0,this.pendingBytes=0,this.pendingMetadata.length=0,this.trigger("data",event),i=0;i<event.captions.length;i++)caption=event.captions[i]
,this.trigger("caption",caption);for(i=0;i<event.metadata.length;i++)id3=event.metadata[i],this.trigger("id3Frame",id3)}this.emittedTracks>=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},CoalesceStream.prototype.setRemux=function(val){this.remuxTracks=val},(Transmuxer=function(options){var videoTrack,audioTrack,self=this,hasFlushed=!0;Transmuxer.prototype.init.call(this),options=options||{},this.baseMediaDecodeTime=options.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var pipeline={};this.transmuxPipeline_=pipeline,pipeline.type="aac",pipeline.metadataStream=new m2ts.MetadataStream,pipeline.aacStream=new AacStream,pipeline.audioTimestampRolloverStream=new m2ts.TimestampRolloverStream("audio"),pipeline.timedMetadataTimestampRolloverStream=new m2ts.TimestampRolloverStream("timed-metadata"),pipeline.adtsStream=new AdtsStream,pipeline.coalesceStream=new CoalesceStream(options,pipeline.metadataStream),pipeline.headOfPipeline=pipeline.aacStream,pipeline.aacStr
eam.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream),pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream),pipeline.metadataStream.on("timestamp",(function(frame){pipeline.aacStream.setTimestamp(frame.timeStamp)})),pipeline.aacStream.on("data",(function(data){"timed-metadata"!==data.type&&"audio"!==data.type||pipeline.audioSegmentStream||(audioTrack=audioTrack||{timelineStartInfo:{baseMediaDecodeTime:self.baseMediaDecodeTime},codec:"adts",type:"audio"},pipeline.coalesceStream.numberOfTracks++,pipeline.audioSegmentStream=new AudioSegmentStream(audioTrack,options),pipeline.audioSegmentStream.on("log",self.getLogTrigger_("audioSegmentStream")),pipeline.audioSegmentStream.on("timingInfo",self.trigger.bind(self,"audioTimingInfo")),pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream),self.trigger("trackinfo",{hasAudio:!!audioTrack,hasVideo:!!videoTrack}))})),pipeline.coalesceStream.on("d
ata",this.trigger.bind(this,"data")),pipeline.coalesceStream.on("done",this.trigger.bind(this,"done")),addPipelineLogRetriggers(this,pipeline)},this.setupTsPipeline=function(){var pipeline={};this.transmuxPipeline_=pipeline,pipeline.type="ts",pipeline.metadataStream=new m2ts.MetadataStream,pipeline.packetStream=new m2ts.TransportPacketStream,pipeline.parseStream=new m2ts.TransportParseStream,pipeline.elementaryStream=new m2ts.ElementaryStream,pipeline.timestampRolloverStream=new m2ts.TimestampRolloverStream,pipeline.adtsStream=new AdtsStream,pipeline.h264Stream=new H264Stream,pipeline.captionStream=new m2ts.CaptionStream(options),pipeline.coalesceStream=new CoalesceStream(options,pipeline.metadataStream),pipeline.headOfPipeline=pipeline.packetStream,pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream),pipeline.timestampRolloverStream.pipe(pipeline.h264Stream),pipeline.timestampRolloverStream.pipe(pipeline.adtsStream),pipeline.timestampRollove
rStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream),pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream),pipeline.elementaryStream.on("data",(function(data){var i;if("metadata"===data.type){for(i=data.tracks.length;i--;)videoTrack||"video"!==data.tracks[i].type?audioTrack||"audio"!==data.tracks[i].type||((audioTrack=data.tracks[i]).timelineStartInfo.baseMediaDecodeTime=self.baseMediaDecodeTime):(videoTrack=data.tracks[i]).timelineStartInfo.baseMediaDecodeTime=self.baseMediaDecodeTime;videoTrack&&!pipeline.videoSegmentStream&&(pipeline.coalesceStream.numberOfTracks++,pipeline.videoSegmentStream=new VideoSegmentStream(videoTrack,options),pipeline.videoSegmentStream.on("log",self.getLogTrigger_("videoSegmentStream")),pipeline.videoSegmentStream.on("timelineStartInfo",(function(timelineStartInfo){audioTrack&&!options.keepOriginalTimestamps&&(audioTrack.timelineStartInfo=timelineStartInfo,pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts-self.baseMediaDecod
eTime))})),pipeline.videoSegmentStream.on("processedGopsInfo",self.trigger.bind(self,"gopInfo")),pipeline.videoSegmentStream.on("segmentTimingInfo",self.trigger.bind(self,"videoSegmentTimingInfo")),pipeline.videoSegmentStream.on("baseMediaDecodeTime",(function(baseMediaDecodeTime){audioTrack&&pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime)})),pipeline.videoSegmentStream.on("timingInfo",self.trigger.bind(self,"videoTimingInfo")),pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream)),audioTrack&&!pipeline.audioSegmentStream&&(pipeline.coalesceStream.numberOfTracks++,pipeline.audioSegmentStream=new AudioSegmentStream(audioTrack,options),pipeline.audioSegmentStream.on("log",self.getLogTrigger_("audioSegmentStream")),pipeline.audioSegmentStream.on("timingInfo",self.trigger.bind(self,"audioTimingInfo")),pipeline.audioSegmentStream.on("segmentTimingInfo",self.trigger.bind(self,"audioSegmentTimingInfo")),pipeline.adtsStream.pipe(pipeline.audioSegmentStream).
pipe(pipeline.coalesceStream)),self.trigger("trackinfo",{hasAudio:!!audioTrack,hasVideo:!!videoTrack})}})),pipeline.coalesceStream.on("data",this.trigger.bind(this,"data")),pipeline.coalesceStream.on("id3Frame",(function(id3Frame){id3Frame.dispatchType=pipeline.metadataStream.dispatchType,self.trigger("id3Frame",id3Frame)})),pipeline.coalesceStream.on("caption",this.trigger.bind(this,"caption")),pipeline.coalesceStream.on("done",this.trigger.bind(this,"done")),addPipelineLogRetriggers(this,pipeline)},this.setBaseMediaDecodeTime=function(baseMediaDecodeTime){var pipeline=this.transmuxPipeline_;options.keepOriginalTimestamps||(this.baseMediaDecodeTime=baseMediaDecodeTime),audioTrack&&(audioTrack.timelineStartInfo.dts=void 0,audioTrack.timelineStartInfo.pts=void 0,trackDecodeInfo.clearDtsInfo(audioTrack),pipeline.audioTimestampRolloverStream&&pipeline.audioTimestampRolloverStream.discontinuity()),videoTrack&&(pipeline.videoSegmentStream&&(pipeline.videoSegmentStream.gopCache_=[]),videoTrack.timelineStartInfo.dt
s=void 0,videoTrack.timelineStartInfo.pts=void 0,trackDecodeInfo.clearDtsInfo(videoTrack),pipeline.captionStream.reset()),pipeline.timestampRolloverStream&&pipeline.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(timestamp){audioTrack&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp)},this.setRemux=function(val){var pipeline=this.transmuxPipeline_;options.remux=val,pipeline&&pipeline.coalesceStream&&pipeline.coalesceStream.setRemux(val)},this.alignGopsWith=function(gopsToAlignWith){videoTrack&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith)},this.getLogTrigger_=function(key){var self=this;return function(event){event.stream=key,self.trigger("log",event)}},this.push=function(data){if(hasFlushed){var isAac=isLikelyAacData(data);isAac&&"aac"!==this.transmuxPipeline_.type?this.setupAacPipeline():isAac||"ts"===this.transmuxPipeline_.type||this.setupTsPipeline(),hasFlushed=!1}this.transmuxPipeline
_.headOfPipeline.push(data)},this.flush=function(){hasFlushed=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}}).prototype=new Stream;var win,startTime,getTracks,getTimescaleFromMediaHeader,getEmsgID3,transmuxer={Transmuxer:Transmuxer,VideoSegmentStream:VideoSegmentStream,AudioSegmentStream:AudioSegmentStream,AUDIO_PROPERTIES:AUDIO_PROPERTIES,VIDEO_PROPERTIES:VIDEO_PROPERTIES,generateSegmentTimingInfo:generateSegmentTimingInfo},bin_toUnsigned=function(value){return value>>>0},parseType_1=function(buffer){var result="";return result+=String.fromCharCode(buffer[0]),result+=String.fromCharCode(buffer[1]),result+=String.fromCharCode(buffer[2]),result+=String.fromCharCode(buffer[3])},toUnsigned$2=bin_toUnsigned,par
seType$2=parseType_1,findBox$2=function(data,path){var i,size,type,end,subresults,results=[];if(!path.length)return null;for(i=0;i<data.byteLength;)size=toUnsigned$2(data[i]<<24|data[i+1]<<16|data[i+2]<<8|data[i+3]),type=parseType$2(data.subarray(i+4,i+8)),end=size>1?i+size:data.byteLength,type===path[0]&&(1===path.length?results.push(data.subarray(i+8,end)):(subresults=findBox$2(data.subarray(i+8,end),path.slice(1))).length&&(results=results.concat(subresults))),i=end;return results},toUnsigned$1=bin_toUnsigned,getUint64$2=numbers.getUint64,parseTfdt$2=function(data){var result={version:data[0],flags:new Uint8Array(data.subarray(1,4))};return 1===result.version?result.baseMediaDecodeTime=getUint64$2(data.subarray(4)):result.baseMediaDecodeTime=toUnsigned$1(data[4]<<24|data[5]<<16|data[6]<<8|data[7]),result},parseSampleFlags=function(flags){return{isLeading:(12&flags[0])>>>2,dependsOn:3&flags[0],isDependedOn:(192&flags[1])>>>6,hasRedundancy:(48&flags[1])>>>4,paddingValue:(14&flags[1])>>>1,isNonSyncSample:1&f
lags[1],degradationPriority:flags[2]<<8|flags[3]}},parseTrun$2=function(data){var sample,result={version:data[0],flags:new Uint8Array(data.subarray(1,4)),samples:[]},view=new DataView(data.buffer,data.byteOffset,data.byteLength),dataOffsetPresent=1&result.flags[2],firstSampleFlagsPresent=4&result.flags[2],sampleDurationPresent=1&result.flags[1],sampleSizePresent=2&result.flags[1],sampleFlagsPresent=4&result.flags[1],sampleCompositionTimeOffsetPresent=8&result.flags[1],sampleCount=view.getUint32(4),offset=8;for(dataOffsetPresent&&(result.dataOffset=view.getInt32(offset),offset+=4),firstSampleFlagsPresent&&sampleCount&&(sample={flags:parseSampleFlags(data.subarray(offset,offset+4))},offset+=4,sampleDurationPresent&&(sample.duration=view.getUint32(offset),offset+=4),sampleSizePresent&&(sample.size=view.getUint32(offset),offset+=4),sampleCompositionTimeOffsetPresent&&(1===result.version?sample.compositionTimeOffset=view.getInt32(offset):sample.compositionTimeOffset=view.getUint32(offset),offset+=4),result.sample
s.push(sample),sampleCount--);sampleCount--;)sample={},sampleDurationPresent&&(sample.duration=view.getUint32(offset),offset+=4),sampleSizePresent&&(sample.size=view.getUint32(offset),offset+=4),sampleFlagsPresent&&(sample.flags=parseSampleFlags(data.subarray(offset,offset+4)),offset+=4),sampleCompositionTimeOffsetPresent&&(1===result.version?sample.compositionTimeOffset=view.getInt32(offset):sample.compositionTimeOffset=view.getUint32(offset),offset+=4),result.samples.push(sample);return result},parseTfhd$2=function(data){var i,view=new DataView(data.buffer,data.byteOffset,data.byteLength),result={version:data[0],flags:new Uint8Array(data.subarray(1,4)),trackId:view.getUint32(4)},baseDataOffsetPresent=1&result.flags[2],sampleDescriptionIndexPresent=2&result.flags[2],defaultSampleDurationPresent=8&result.flags[2],defaultSampleSizePresent=16&result.flags[2],defaultSampleFlagsPresent=32&result.flags[2],durationIsEmpty=65536&result.flags[0],defaultBaseIsMoof=131072&result.flags[0];return i=8,baseDataOffsetPrese
nt&&(i+=4,result.baseDataOffset=view.getUint32(12),i+=4),sampleDescriptionIndexPresent&&(result.sampleDescriptionIndex=view.getUint32(i),i+=4),defaultSampleDurationPresent&&(result.defaultSampleDuration=view.getUint32(i),i+=4),defaultSampleSizePresent&&(result.defaultSampleSize=view.getUint32(i),i+=4),defaultSampleFlagsPresent&&(result.defaultSampleFlags=view.getUint32(i)),durationIsEmpty&&(result.durationIsEmpty=!0),!baseDataOffsetPresent&&defaultBaseIsMoof&&(result.baseDataOffsetIsMoof=!0),result},discardEmulationPreventionBytes=(win="undefined"!=typeof window?window:void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:{},captionPacketParser.discardEmulationPreventionBytes),CaptionStream=captionStream.CaptionStream,findBox$1=findBox$2,parseTfdt$1=parseTfdt$2,parseTrun$1=parseTrun$2,parseTfhd$1=parseTfhd$2,window$2=win,mapToSample=function(offset,samples){for(var approximateOffset=offset,i=0;i<samples.length;i++){var sample=samples[i];if(approximateOffset<sample.size)return sample;approximat
eOffset-=sample.size}return null},parseCaptionNals=function(segment,videoTrackId){var trafs=findBox$1(segment,["moof","traf"]),mdats=findBox$1(segment,["mdat"]),captionNals={},mdatTrafPairs=[];return mdats.forEach((function(mdat,index){var matchingTraf=trafs[index];mdatTrafPairs.push({mdat:mdat,traf:matchingTraf})})),mdatTrafPairs.forEach((function(pair){var samples,result,mdat=pair.mdat,traf=pair.traf,tfhd=findBox$1(traf,["tfhd"]),headerInfo=parseTfhd$1(tfhd[0]),trackId=headerInfo.trackId,tfdt=findBox$1(traf,["tfdt"]),baseMediaDecodeTime=tfdt.length>0?parseTfdt$1(tfdt[0]).baseMediaDecodeTime:0,truns=findBox$1(traf,["trun"]);videoTrackId===trackId&&truns.length>0&&(samples=function(truns,baseMediaDecodeTime,tfhd){var currentDts=baseMediaDecodeTime,defaultSampleDuration=tfhd.defaultSampleDuration||0,defaultSampleSize=tfhd.defaultSampleSize||0,trackId=tfhd.trackId,allSamples=[];return truns.forEach((function(trun){var samples=parseTrun$1(trun).samples;samples.forEach((function(sample){void 0===sample.duration&
&(sample.duration=defaultSampleDuration),void 0===sample.size&&(sample.size=defaultSampleSize),sample.trackId=trackId,sample.dts=currentDts,void 0===sample.compositionTimeOffset&&(sample.compositionTimeOffset=0),"bigint"==typeof currentDts?(sample.pts=currentDts+window$2.BigInt(sample.compositionTimeOffset),currentDts+=window$2.BigInt(sample.duration)):(sample.pts=currentDts+sample.compositionTimeOffset,currentDts+=sample.duration)})),allSamples=allSamples.concat(samples)})),allSamples}(truns,baseMediaDecodeTime,headerInfo),result=function(avcStream,samples,trackId){var seiNal,i,length,lastMatchedSample,avcView=new DataView(avcStream.buffer,avcStream.byteOffset,avcStream.byteLength),result={logs:[],seiNals:[]};for(i=0;i+4<avcStream.length;i+=length)if(length=avcView.getUint32(i),i+=4,!(length<=0))switch(31&avcStream[i]){case 6:var data=avcStream.subarray(i+1,i+1+length),matchingSample=mapToSample(i,samples);if(seiNal={nalUnitType:"sei_rbsp",size:length,data:data,escapedRBSP:discardEmulationPreventionBytes(da
ta),trackId:trackId},matchingSample)seiNal.pts=matchingSample.pts,seiNal.dts=matchingSample.dts,lastMatchedSample=matchingSample;else{if(!lastMatchedSample){result.logs.push({level:"warn",message:"We've encountered a nal unit without data at "+i+" for trackId "+trackId+". See mux.js#223."});break}seiNal.pts=lastMatchedSample.pts,seiNal.dts=lastMatchedSample.dts}result.seiNals.push(seiNal)}return result}(mdat,samples,trackId),captionNals[trackId]||(captionNals[trackId]={seiNals:[],logs:[]}),captionNals[trackId].seiNals=captionNals[trackId].seiNals.concat(result.seiNals),captionNals[trackId].logs=captionNals[trackId].logs.concat(result.logs))})),captionNals},captionParser=function(){var captionStream,segmentCache,trackId,timescale,parsedCaptions,parsingPartial,isInitialized=!1;this.isInitialized=function(){return isInitialized},this.init=function(options){captionStream=new CaptionStream,isInitialized=!0,parsingPartial=!!options&&options.isPartial,captionStream.on("data",(function(event){event.startTime=event.s
tartPts/timescale,event.endTime=event.endPts/timescale,parsedCaptions.captions.push(event),parsedCaptions.captionStreams[event.stream]=!0})),captionStream.on("log",(function(log){parsedCaptions.logs.push(log)}))},this.isNewInit=function(videoTrackIds,timescales){return!(videoTrackIds&&0===videoTrackIds.length||timescales&&"object"==typeof timescales&&0===Object.keys(timescales).length)&&(trackId!==videoTrackIds[0]||timescale!==timescales[trackId])},this.parse=function(segment,videoTrackIds,timescales){var parsedData;if(!this.isInitialized())return null;if(!videoTrackIds||!timescales)return null;if(this.isNewInit(videoTrackIds,timescales))trackId=videoTrackIds[0],timescale=timescales[trackId];else if(null===trackId||!timescale)return segmentCache.push(segment),null;for(;segmentCache.length>0;){var cachedSegment=segmentCache.shift();this.parse(cachedSegment,videoTrackIds,timescales)}return parsedData=function(segment,trackId,timescale){if(null===trackId)return null;var trackNals=parseCaptionNals(segment,trackI
d)[trackId]||{};return{seiNals:trackNals.seiNals,logs:trackNals.logs,timescale:timescale}}(segment,trackId,timescale),parsedData&&parsedData.logs&&(parsedCaptions.logs=parsedCaptions.logs.concat(parsedData.logs)),null!==parsedData&&parsedData.seiNals?(this.pushNals(parsedData.seiNals),this.flushStream(),parsedCaptions):parsedCaptions.logs.length?{logs:parsedCaptions.logs,captions:[],captionStreams:[]}:null},this.pushNals=function(nals){if(!this.isInitialized()||!nals||0===nals.length)return null;nals.forEach((function(nal){captionStream.push(nal)}))},this.flushStream=function(){if(!this.isInitialized())return null;parsingPartial?captionStream.partialFlush():captionStream.flush()},this.clearParsedCaptions=function(){parsedCaptions.captions=[],parsedCaptions.captionStreams={},parsedCaptions.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;captionStream.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){segmentCac
he=[],trackId=null,timescale=null,parsedCaptions?this.clearParsedCaptions():parsedCaptions={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},uint8ToCString=function(data){for(var index=0,curChar=String.fromCharCode(data[index]),retString="";"\0"!==curChar;)retString+=curChar,index++,curChar=String.fromCharCode(data[index]);return retString+=curChar},getUint64$1=numbers.getUint64,isValidEmsgBox=function(version,emsg){var hasScheme="\0"!==emsg.scheme_id_uri,isValidV0Box=0===version&&isDefined(emsg.presentation_time_delta)&&hasScheme,isValidV1Box=1===version&&isDefined(emsg.presentation_time)&&hasScheme;return!(version>1)&&isValidV0Box||isValidV1Box},isDefined=function(data){return void 0!==data||null!==data},emsg$1={parseEmsgBox:function(boxData){var scheme_id_uri,value,timescale,presentation_time,presentation_time_delta,event_duration,id,offset=4,version=boxData[0];if(0===version)offset+=(scheme_id_uri=uint8ToCString(boxData.subarray(offset))).length,offset+=(value=uint8ToCStrin
g(boxData.subarray(offset))).length,timescale=(dv=new DataView(boxData.buffer)).getUint32(offset),offset+=4,presentation_time_delta=dv.getUint32(offset),offset+=4,event_duration=dv.getUint32(offset),offset+=4,id=dv.getUint32(offset),offset+=4;else if(1===version){var dv;timescale=(dv=new DataView(boxData.buffer)).getUint32(offset),offset+=4,presentation_time=getUint64$1(boxData.subarray(offset)),offset+=8,event_duration=dv.getUint32(offset),offset+=4,id=dv.getUint32(offset),offset+=4,offset+=(scheme_id_uri=uint8ToCString(boxData.subarray(offset))).length,offset+=(value=uint8ToCString(boxData.subarray(offset))).length}var emsgBox={scheme_id_uri:scheme_id_uri,value:value,timescale:timescale||1,presentation_time:presentation_time,presentation_time_delta:presentation_time_delta,event_duration:event_duration,id:id,message_data:new Uint8Array(boxData.subarray(offset,boxData.byteLength))};return isValidEmsgBox(version,emsgBox)?emsgBox:void 0},scaleTime:function(presentationTime,timescale,timeDelta,offset){return pr
esentationTime||0===presentationTime?presentationTime/timescale:offset+timeDelta/timescale}},toUnsigned=bin_toUnsigned,toHexString=function(value){return("00"+value.toString(16)).slice(-2)},findBox=findBox$2,parseType$1=parseType_1,emsg=emsg$1,parseTfhd=parseTfhd$2,parseTrun=parseTrun$2,parseTfdt=parseTfdt$2,getUint64=numbers.getUint64,window$1=win,parseId3Frames=parseId3.parseId3Frames;startTime=function(timescale,fragment){var lowestTime=findBox(fragment,["moof","traf"]).reduce((function(acc,traf){var baseTime,tfhd=findBox(traf,["tfhd"])[0],id=toUnsigned(tfhd[4]<<24|tfhd[5]<<16|tfhd[6]<<8|tfhd[7]),scale=timescale[id]||9e4,tfdt=findBox(traf,["tfdt"])[0],dv=new DataView(tfdt.buffer,tfdt.byteOffset,tfdt.byteLength);let seconds;return"bigint"==typeof(baseTime=1===tfdt[0]?getUint64(tfdt.subarray(4,12)):dv.getUint32(4))?seconds=baseTime/window$1.BigInt(scale):"number"!=typeof baseTime||isNaN(baseTime)||(seconds=baseTime/scale),seconds<Number.MAX_SAFE_INTEGER&&(seconds=Number(seconds)),seconds<acc&&(acc=seconds),
acc}),1/0);return"bigint"==typeof lowestTime||isFinite(lowestTime)?lowestTime:0},getTimescaleFromMediaHeader=function(mdhd){var index=0===mdhd[0]?12:20;return toUnsigned(mdhd[index]<<24|mdhd[index+1]<<16|mdhd[index+2]<<8|mdhd[index+3])},getTracks=function(init){var traks=findBox(init,["moov","trak"]),tracks=[];return traks.forEach((function(trak){var view,tkhdVersion,track={},tkhd=findBox(trak,["tkhd"])[0];tkhd&&(tkhdVersion=(view=new DataView(tkhd.buffer,tkhd.byteOffset,tkhd.byteLength)).getUint8(0),track.id=0===tkhdVersion?view.getUint32(12):view.getUint32(20));var hdlr=findBox(trak,["mdia","hdlr"])[0];if(hdlr){var type=parseType$1(hdlr.subarray(8,12));track.type="vide"===type?"video":"soun"===type?"audio":type}var stsd=findBox(trak,["mdia","minf","stbl","stsd"])[0];if(stsd){var sampleDescriptions=stsd.subarray(8);track.codec=parseType$1(sampleDescriptions.subarray(4,8));var codecConfig,codecBox=findBox(sampleDescriptions,[track.codec])[0];codecBox&&(/^[asm]vc[1-9]$/i.test(track.codec)?(codecConfig=codecBo
x.subarray(78),"avcC"===parseType$1(codecConfig.subarray(4,8))&&codecConfig.length>11?(track.codec+=".",track.codec+=toHexString(codecConfig[9]),track.codec+=toHexString(codecConfig[10]),track.codec+=toHexString(codecConfig[11])):track.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(track.codec)?(codecConfig=codecBox.subarray(28),"esds"===parseType$1(codecConfig.subarray(4,8))&&codecConfig.length>20&&0!==codecConfig[19]?(track.codec+="."+toHexString(codecConfig[19]),track.codec+="."+toHexString(codecConfig[20]>>>2&63).replace(/^0/,"")):track.codec="mp4a.40.2"):track.codec=track.codec.toLowerCase())}var mdhd=findBox(trak,["mdia","mdhd"])[0];mdhd&&(track.timescale=getTimescaleFromMediaHeader(mdhd)),tracks.push(track)})),tracks},getEmsgID3=function(segmentData){let offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;var emsgBoxes=findBox(segmentData,["emsg"]);return emsgBoxes.map((data=>{var parsedBox=emsg.parseEmsgBox(new Uint8Array(data)),parsedId3Frames=parseId3Frames(parsedBox.message_data);return{cueTi
me:emsg.scaleTime(parsedBox.presentation_time,parsedBox.timescale,parsedBox.presentation_time_delta,offset),duration:emsg.scaleTime(parsedBox.event_duration,parsedBox.timescale),frames:parsedId3Frames}}))};var probe$2_startTime=startTime,probe$2_tracks=getTracks,probe$2_getEmsgID3=getEmsgID3,StreamTypes$1=streamTypes,parsePid=function(packet){var pid=31&packet[1];return pid<<=8,pid|=packet[2]},parsePayloadUnitStartIndicator=function(packet){return!!(64&packet[1])},parseAdaptionField=function(packet){var offset=0;return(48&packet[3])>>>4>1&&(offset+=packet[4]+1),offset},parseNalUnitType=function(type){switch(type){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}},probe$1={parseType:function(packet,pmtPid){var pid=parsePid(packet);return 0===pid?"pat":pid===pmtPid?"pmt":pmtPid?"pes":null},parsePat:function(packet){var pusi=parsePayloadUnitSta
rtIndicator(packet),offset=4+parseAdaptionField(packet);return pusi&&(offset+=packet[offset]+1),(31&packet[offset+10])<<8|packet[offset+11]},parsePmt:function(packet){var programMapTable={},pusi=parsePayloadUnitStartIndicator(packet),payloadOffset=4+parseAdaptionField(packet);if(pusi&&(payloadOffset+=packet[payloadOffset]+1),1&packet[payloadOffset+5]){var tableEnd;tableEnd=3+((15&packet[payloadOffset+1])<<8|packet[payloadOffset+2])-4;for(var offset=12+((15&packet[payloadOffset+10])<<8|packet[payloadOffset+11]);offset<tableEnd;){var i=payloadOffset+offset;programMapTable[(31&packet[i+1])<<8|packet[i+2]]=packet[i],offset+=5+((15&packet[i+3])<<8|packet[i+4])}return programMapTable}},parsePayloadUnitStartIndicator:parsePayloadUnitStartIndicator,parsePesType:function(packet,programMapTable){switch(programMapTable[parsePid(packet)]){case StreamTypes$1.H264_STREAM_TYPE:return"video";case StreamTypes$1.ADTS_STREAM_TYPE:return"audio";case StreamTypes$1.METADATA_STREAM_TYPE:return"timed-metadata";default:return null}}
,parsePesTime:function(packet){if(!parsePayloadUnitStartIndicator(packet))return null;var offset=4+parseAdaptionField(packet);if(offset>=packet.byteLength)return null;var ptsDtsFlags,pes=null;return 192&(ptsDtsFlags=packet[offset+7])&&((pes={}).pts=(14&packet[offset+9])<<27|(255&packet[offset+10])<<20|(254&packet[offset+11])<<12|(255&packet[offset+12])<<5|(254&packet[offset+13])>>>3,pes.pts*=4,pes.pts+=(6&packet[offset+13])>>>1,pes.dts=pes.pts,64&ptsDtsFlags&&(pes.dts=(14&packet[offset+14])<<27|(255&packet[offset+15])<<20|(254&packet[offset+16])<<12|(255&packet[offset+17])<<5|(254&packet[offset+18])>>>3,pes.dts*=4,pes.dts+=(6&packet[offset+18])>>>1)),pes},videoPacketContainsKeyFrame:function(packet){for(var offset=4+parseAdaptionField(packet),frameBuffer=packet.subarray(offset),frameI=0,frameSyncPoint=0,foundKeyFrame=!1;frameSyncPoint<frameBuffer.byteLength-3;frameSyncPoint++)if(1===frameBuffer[frameSyncPoint+2]){frameI=frameSyncPoint+5;break}for(;frameI<frameBuffer.byteLength;)switch(frameBuffer[frameI]){ca
se 0:if(0!==frameBuffer[frameI-1]){frameI+=2;break}if(0!==frameBuffer[frameI-2]){frameI++;break}frameSyncPoint+3!==frameI-2&&"slice_layer_without_partitioning_rbsp_idr"===parseNalUnitType(31&frameBuffer[frameSyncPoint+3])&&(foundKeyFrame=!0);do{frameI++}while(1!==frameBuffer[frameI]&&frameI<frameBuffer.length);frameSyncPoint=frameI-2,frameI+=3;break;case 1:if(0!==frameBuffer[frameI-1]||0!==frameBuffer[frameI-2]){frameI+=3;break}"slice_layer_without_partitioning_rbsp_idr"===parseNalUnitType(31&frameBuffer[frameSyncPoint+3])&&(foundKeyFrame=!0),frameSyncPoint=frameI-2,frameI+=3;break;default:frameI+=3}return frameBuffer=frameBuffer.subarray(frameSyncPoint),frameI-=frameSyncPoint,frameSyncPoint=0,frameBuffer&&frameBuffer.byteLength>3&&"slice_layer_without_partitioning_rbsp_idr"===parseNalUnitType(31&frameBuffer[frameSyncPoint+3])&&(foundKeyFrame=!0),foundKeyFrame}},StreamTypes=streamTypes,handleRollover=timestampRolloverStream.handleRollover,probe={};probe.ts=probe$1,probe.aac=utils;var ONE_SECOND_IN_TS=clock$2
.ONE_SECOND_IN_TS,parseAudioPes_=function(bytes,pmt,result){for(var packet,pesType,pusi,parsed,startIndex=0,endIndex=188,endLoop=!1;endIndex<=bytes.byteLength;)if(71!==bytes[startIndex]||71!==bytes[endIndex]&&endIndex!==bytes.byteLength)startIndex++,endIndex++;else{if(packet=bytes.subarray(startIndex,endIndex),"pes"===probe.ts.parseType(packet,pmt.pid))pesType=probe.ts.parsePesType(packet,pmt.table),pusi=probe.ts.parsePayloadUnitStartIndicator(packet),"audio"===pesType&&pusi&&(parsed=probe.ts.parsePesTime(packet))&&(parsed.type="audio",result.audio.push(parsed),endLoop=!0);if(endLoop)break;startIndex+=188,endIndex+=188}for(startIndex=(endIndex=bytes.byteLength)-188,endLoop=!1;startIndex>=0;)if(71!==bytes[startIndex]||71!==bytes[endIndex]&&endIndex!==bytes.byteLength)startIndex--,endIndex--;else{if(packet=bytes.subarray(startIndex,endIndex),"pes"===probe.ts.parseType(packet,pmt.pid))pesType=probe.ts.parsePesType(packet,pmt.table),pusi=probe.ts.parsePayloadUnitStartIndicator(packet),"audio"===pesType&&pusi&&(p
arsed=probe.ts.parsePesTime(packet))&&(parsed.type="audio",result.audio.push(parsed),endLoop=!0);if(endLoop)break;startIndex-=188,endIndex-=188}},parseVideoPes_=function(bytes,pmt,result){for(var packet,pesType,pusi,parsed,frame,i,pes,startIndex=0,endIndex=188,endLoop=!1,currentFrame={data:[],size:0};endIndex<bytes.byteLength;)if(71!==bytes[startIndex]||71!==bytes[endIndex])startIndex++,endIndex++;else{if(packet=bytes.subarray(startIndex,endIndex),"pes"===probe.ts.parseType(packet,pmt.pid))if(pesType=probe.ts.parsePesType(packet,pmt.table),pusi=probe.ts.parsePayloadUnitStartIndicator(packet),"video"===pesType&&(pusi&&!endLoop&&(parsed=probe.ts.parsePesTime(packet))&&(parsed.type="video",result.video.push(parsed),endLoop=!0),!result.firstKeyFrame)){if(pusi&&0!==currentFrame.size){for(frame=new Uint8Array(currentFrame.size),i=0;currentFrame.data.length;)pes=currentFrame.data.shift(),frame.set(pes,i),i+=pes.byteLength;if(probe.ts.videoPacketContainsKeyFrame(frame)){var firstKeyFrame=probe.ts.parsePesTime(frame)
;firstKeyFrame?(result.firstKeyFrame=firstKeyFrame,result.firstKeyFrame.type="video"):console.warn("Failed to extract PTS/DTS from PES at first keyframe. This could be an unusual TS segment, or else mux.js did not parse your TS segment correctly. If you know your TS segments do contain PTS/DTS on keyframes please file a bug report! You can try ffprobe to double check for yourself.")}currentFrame.size=0}currentFrame.data.push(packet),currentFrame.size+=packet.byteLength}if(endLoop&&result.firstKeyFrame)break;startIndex+=188,endIndex+=188}for(startIndex=(endIndex=bytes.byteLength)-188,endLoop=!1;startIndex>=0;)if(71!==bytes[startIndex]||71!==bytes[endIndex])startIndex--,endIndex--;else{if(packet=bytes.subarray(startIndex,endIndex),"pes"===probe.ts.parseType(packet,pmt.pid))pesType=probe.ts.parsePesType(packet,pmt.table),pusi=probe.ts.parsePayloadUnitStartIndicator(packet),"video"===pesType&&pusi&&(parsed=probe.ts.parsePesTime(packet))&&(parsed.type="video",result.video.push(parsed),endLoop=!0);if(endLoop)break
;startIndex-=188,endIndex-=188}},inspectTs_=function(bytes){var pmt={pid:null,table:null},result={};for(var pid in function(bytes,pmt){for(var packet,startIndex=0,endIndex=188;endIndex<bytes.byteLength;)if(71!==bytes[startIndex]||71!==bytes[endIndex])startIndex++,endIndex++;else{switch(packet=bytes.subarray(startIndex,endIndex),probe.ts.parseType(packet,pmt.pid)){case"pat":pmt.pid=probe.ts.parsePat(packet);break;case"pmt":var table=probe.ts.parsePmt(packet);pmt.table=pmt.table||{},Object.keys(table).forEach((function(key){pmt.table[key]=table[key]}))}startIndex+=188,endIndex+=188}}(bytes,pmt),pmt.table){if(pmt.table.hasOwnProperty(pid))switch(pmt.table[pid]){case StreamTypes.H264_STREAM_TYPE:result.video=[],parseVideoPes_(bytes,pmt,result),0===result.video.length&&delete result.video;break;case StreamTypes.ADTS_STREAM_TYPE:result.audio=[],parseAudioPes_(bytes,pmt,result),0===result.audio.length&&delete result.audio}}return result},tsInspector_inspect=function(bytes,baseTimestamp){var result;return result=pro
be.aac.isLikelyAacData(bytes)?function(bytes){for(var packet,endLoop=!1,audioCount=0,sampleRate=null,timestamp=null,frameSize=0,byteIndex=0;bytes.length-byteIndex>=3;){switch(probe.aac.parseType(bytes,byteIndex)){case"timed-metadata":if(bytes.length-byteIndex<10){endLoop=!0;break}if((frameSize=probe.aac.parseId3TagSize(bytes,byteIndex))>bytes.length){endLoop=!0;break}null===timestamp&&(packet=bytes.subarray(byteIndex,byteIndex+frameSize),timestamp=probe.aac.parseAacTimestamp(packet)),byteIndex+=frameSize;break;case"audio":if(bytes.length-byteIndex<7){endLoop=!0;break}if((frameSize=probe.aac.parseAdtsSize(bytes,byteIndex))>bytes.length){endLoop=!0;break}null===sampleRate&&(packet=bytes.subarray(byteIndex,byteIndex+frameSize),sampleRate=probe.aac.parseSampleRate(packet)),audioCount++,byteIndex+=frameSize;break;default:byteIndex++}if(endLoop)return null}if(null===sampleRate||null===timestamp)return null;var audioTimescale=ONE_SECOND_IN_TS/sampleRate;return{audio:[{type:"audio",dts:timestamp,pts:timestamp},{type
:"audio",dts:timestamp+1024*audioCount*audioTimescale,pts:timestamp+1024*audioCount*audioTimescale}]}}(bytes):inspectTs_(bytes),result&&(result.audio||result.video)?(function(segmentInfo,baseTimestamp){if(segmentInfo.audio&&segmentInfo.audio.length){var audioBaseTimestamp=baseTimestamp;(void 0===audioBaseTimestamp||isNaN(audioBaseTimestamp))&&(audioBaseTimestamp=segmentInfo.audio[0].dts),segmentInfo.audio.forEach((function(info){info.dts=handleRollover(info.dts,audioBaseTimestamp),info.pts=handleRollover(info.pts,audioBaseTimestamp),info.dtsTime=info.dts/ONE_SECOND_IN_TS,info.ptsTime=info.pts/ONE_SECOND_IN_TS}))}if(segmentInfo.video&&segmentInfo.video.length){var videoBaseTimestamp=baseTimestamp;if((void 0===videoBaseTimestamp||isNaN(videoBaseTimestamp))&&(videoBaseTimestamp=segmentInfo.video[0].dts),segmentInfo.video.forEach((function(info){info.dts=handleRollover(info.dts,videoBaseTimestamp),info.pts=handleRollover(info.pts,videoBaseTimestamp),info.dtsTime=info.dts/ONE_SECOND_IN_TS,info.ptsTime=info.pts/ON
E_SECOND_IN_TS})),segmentInfo.firstKeyFrame){var frame=segmentInfo.firstKeyFrame;frame.dts=handleRollover(frame.dts,videoBaseTimestamp),frame.pts=handleRollover(frame.pts,videoBaseTimestamp),frame.dtsTime=frame.dts/ONE_SECOND_IN_TS,frame.ptsTime=frame.pts/ONE_SECOND_IN_TS}}}(result,baseTimestamp),result):null};class MessageHandlers{constructor(self,options){this.options=options||{},this.self=self,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new transmuxer.Transmuxer(this.options),function(self,transmuxer){transmuxer.on("data",(function(segment){const initArray=segment.initSegment;segment.initSegment={data:initArray.buffer,byteOffset:initArray.byteOffset,byteLength:initArray.byteLength};const typedArray=segment.data;segment.data=typedArray.buffer,self.postMessage({action:"data",segment:segment,byteOffset:typedArray.byteOffset,byteLength:typedArray.byteLength},[segment.data])})),transmuxer.on("done",(function(data){self.postMessage({action:"done"})})),transmuxer.on("gopInfo",(f
unction(gopInfo){self.postMessage({action:"gopInfo",gopInfo:gopInfo})})),transmuxer.on("videoSegmentTimingInfo",(function(timingInfo){const videoSegmentTimingInfo={start:{decode:clock$2.videoTsToSeconds(timingInfo.start.dts),presentation:clock$2.videoTsToSeconds(timingInfo.start.pts)},end:{decode:clock$2.videoTsToSeconds(timingInfo.end.dts),presentation:clock$2.videoTsToSeconds(timingInfo.end.pts)},baseMediaDecodeTime:clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)};timingInfo.prependedContentDuration&&(videoSegmentTimingInfo.prependedContentDuration=clock$2.videoTsToSeconds(timingInfo.prependedContentDuration)),self.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:videoSegmentTimingInfo})})),transmuxer.on("audioSegmentTimingInfo",(function(timingInfo){const audioSegmentTimingInfo={start:{decode:clock$2.videoTsToSeconds(timingInfo.start.dts),presentation:clock$2.videoTsToSeconds(timingInfo.start.pts)},end:{decode:clock$2.videoTsToSeconds(timingInfo.end.dts),presentation:clock$2.vi
deoTsToSeconds(timingInfo.end.pts)},baseMediaDecodeTime:clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)};timingInfo.prependedContentDuration&&(audioSegmentTimingInfo.prependedContentDuration=clock$2.videoTsToSeconds(timingInfo.prependedContentDuration)),self.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:audioSegmentTimingInfo})})),transmuxer.on("id3Frame",(function(id3Frame){self.postMessage({action:"id3Frame",id3Frame:id3Frame})})),transmuxer.on("caption",(function(caption){self.postMessage({action:"caption",caption:caption})})),transmuxer.on("trackinfo",(function(trackInfo){self.postMessage({action:"trackinfo",trackInfo:trackInfo})})),transmuxer.on("audioTimingInfo",(function(audioTimingInfo){self.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:clock$2.videoTsToSeconds(audioTimingInfo.start),end:clock$2.videoTsToSeconds(audioTimingInfo.end)}})})),transmuxer.on("videoTimingInfo",(function(videoTimingInfo){self.postMessage({action:"videoTimingInfo",videoTimingInfo:
{start:clock$2.videoTsToSeconds(videoTimingInfo.start),end:clock$2.videoTsToSeconds(videoTimingInfo.end)}})})),transmuxer.on("log",(function(log){self.postMessage({action:"log",log:log})}))}(this.self,this.transmuxer)}pushMp4Captions(data){this.captionParser||(this.captionParser=new captionParser,this.captionParser.init());const segment=new Uint8Array(data.data,data.byteOffset,data.byteLength),parsed=this.captionParser.parse(segment,data.trackIds,data.timescales);this.self.postMessage({action:"mp4Captions",captions:parsed&&parsed.captions||[],logs:parsed&&parsed.logs||[],data:segment.buffer},[segment.buffer])}probeMp4StartTime(_ref43){let{timescales:timescales,data:data}=_ref43;const startTime=probe$2_startTime(timescales,data);this.self.postMessage({action:"probeMp4StartTime",startTime:startTime,data:data},[data.buffer])}probeMp4Tracks(_ref44){let{data:data}=_ref44;const tracks=probe$2_tracks(data);this.self.postMessage({action:"probeMp4Tracks",tracks:tracks,data:data},[data.buffer])}probeEmsgID3(_ref45){le
t{data:data,offset:offset}=_ref45;const id3Frames=probe$2_getEmsgID3(data,offset);this.self.postMessage({action:"probeEmsgID3",id3Frames:id3Frames,emsgData:data},[data.buffer])}probeTs(_ref46){let{data:data,baseStartTime:baseStartTime}=_ref46;const tsStartTime="number"!=typeof baseStartTime||isNaN(baseStartTime)?void 0:baseStartTime*clock$2.ONE_SECOND_IN_TS,timeInfo=tsInspector_inspect(data,tsStartTime);let result=null;timeInfo&&(result={hasVideo:timeInfo.video&&2===timeInfo.video.length||!1,hasAudio:timeInfo.audio&&2===timeInfo.audio.length||!1},result.hasVideo&&(result.videoStart=timeInfo.video[0].ptsTime),result.hasAudio&&(result.audioStart=timeInfo.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:result,data:data},[data.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(data){const segment=new Uint8Array(data.data,data.byteOffset,data.byteLength);this.transmuxe
r.push(segment)}reset(){this.transmuxer.reset()}setTimestampOffset(data){const timestampOffset=data.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)))}setAudioAppendStart(data){this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)))}setRemux(data){this.transmuxer.setRemux(data.remux)}flush(data){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(data){this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice())}}self.onmessage=function(event){"init"===event.data.action&&event.data.options?this.messageHandlers=new MessageHandlers(self,event.data.options):(this.messageHandlers||(this.messageHandlers=new MessageHandlers(self)),event.data&&event.data.action&&"init"!==event.data.action&&this.messageHandlers[event.data.action]&&this.messageHandlers[event.data.action](event.data)
)}})));var TransmuxWorker=factory(workerCode$1);const processTransmux=options=>{const{transmuxer:transmuxer,bytes:bytes,audioAppendStart:audioAppendStart,gopsToAlignWith:gopsToAlignWith,remux:remux,onData:onData,onTrackInfo:onTrackInfo,onAudioTimingInfo:onAudioTimingInfo,onVideoTimingInfo:onVideoTimingInfo,onVideoSegmentTimingInfo:onVideoSegmentTimingInfo,onAudioSegmentTimingInfo:onAudioSegmentTimingInfo,onId3:onId3,onCaptions:onCaptions,onDone:onDone,onEndedTimeline:onEndedTimeline,onTransmuxerLog:onTransmuxerLog,isEndOfTimeline:isEndOfTimeline}=options,transmuxedData={buffer:[]};let waitForEndedTimelineEvent=isEndOfTimeline;if(transmuxer.onmessage=event=>{transmuxer.currentTransmux===options&&("data"===event.data.action&&((event,transmuxedData,callback)=>{const{type:type,initSegment:initSegment,captions:captions,captionStreams:captionStreams,metadata:metadata,videoFrameDtsTime:videoFrameDtsTime,videoFramePtsTime:videoFramePtsTime}=event.data.segment;transmuxedData.buffer.push({captions:captions,captionStre
ams:captionStreams,metadata:metadata});const boxes=event.data.segment.boxes||{data:event.data.segment.data},result={type:type,data:new Uint8Array(boxes.data,boxes.data.byteOffset,boxes.data.byteLength),initSegment:new Uint8Array(initSegment.data,initSegment.byteOffset,initSegment.byteLength)};void 0!==videoFrameDtsTime&&(result.videoFrameDtsTime=videoFrameDtsTime),void 0!==videoFramePtsTime&&(result.videoFramePtsTime=videoFramePtsTime),callback(result)})(event,transmuxedData,onData),"trackinfo"===event.data.action&&onTrackInfo(event.data.trackInfo),"gopInfo"===event.data.action&&((event,transmuxedData)=>{transmuxedData.gopInfo=event.data.gopInfo})(event,transmuxedData),"audioTimingInfo"===event.data.action&&onAudioTimingInfo(event.data.audioTimingInfo),"videoTimingInfo"===event.data.action&&onVideoTimingInfo(event.data.videoTimingInfo),"videoSegmentTimingInfo"===event.data.action&&onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo),"audioSegmentTimingInfo"===event.data.action&&onAudioSegmentTimingInf
o(event.data.audioSegmentTimingInfo),"id3Frame"===event.data.action&&onId3([event.data.id3Frame],event.data.id3Frame.dispatchType),"caption"===event.data.action&&onCaptions(event.data.caption),"endedtimeline"===event.data.action&&(waitForEndedTimelineEvent=!1,onEndedTimeline()),"log"===event.data.action&&onTransmuxerLog(event.data.log),"transmuxed"===event.data.type&&(waitForEndedTimelineEvent||(transmuxer.onmessage=null,(_ref47=>{let{transmuxedData:transmuxedData,callback:callback}=_ref47;transmuxedData.buffer=[],callback(transmuxedData)})({transmuxedData:transmuxedData,callback:onDone}),dequeue(transmuxer))))},audioAppendStart&&transmuxer.postMessage({action:"setAudioAppendStart",appendStart:audioAppendStart}),Array.isArray(gopsToAlignWith)&&transmuxer.postMessage({action:"alignGopsWith",gopsToAlignWith:gopsToAlignWith}),void 0!==remux&&transmuxer.postMessage({action:"setRemux",remux:remux}),bytes.byteLength){const buffer=bytes instanceof ArrayBuffer?bytes:bytes.buffer,byteOffset=bytes instanceof ArrayBuff
er?0:bytes.byteOffset;transmuxer.postMessage({action:"push",data:buffer,byteOffset:byteOffset,byteLength:bytes.byteLength},[buffer])}isEndOfTimeline&&transmuxer.postMessage({action:"endTimeline"}),transmuxer.postMessage({action:"flush"})},dequeue=transmuxer=>{transmuxer.currentTransmux=null,transmuxer.transmuxQueue.length&&(transmuxer.currentTransmux=transmuxer.transmuxQueue.shift(),"function"==typeof transmuxer.currentTransmux?transmuxer.currentTransmux():processTransmux(transmuxer.currentTransmux))},processAction=(transmuxer,action)=>{transmuxer.postMessage({action:action}),dequeue(transmuxer)},enqueueAction=(action,transmuxer)=>{if(!transmuxer.currentTransmux)return transmuxer.currentTransmux=action,void processAction(transmuxer,action);transmuxer.transmuxQueue.push(processAction.bind(null,transmuxer,action))},transmux=options=>{if(!options.transmuxer.currentTransmux)return options.transmuxer.currentTransmux=options,void processTransmux(options);options.transmuxer.transmuxQueue.push(options)};var segmentT
ransmuxer_reset=transmuxer=>{enqueueAction("reset",transmuxer)},segmentTransmuxer_createTransmuxer=options=>{const transmuxer=new TransmuxWorker;transmuxer.currentTransmux=null,transmuxer.transmuxQueue=[];const term=transmuxer.terminate;return transmuxer.terminate=()=>(transmuxer.currentTransmux=null,transmuxer.transmuxQueue.length=0,term.call(transmuxer)),transmuxer.postMessage({action:"init",options:options}),transmuxer};const workerCallback=function(options){const transmuxer=options.transmuxer,endAction=options.endAction||options.action,callback=options.callback,message=_extends$1({},options,{endAction:null,transmuxer:null,callback:null}),listenForEndEvent=event=>{event.data.action===endAction&&(transmuxer.removeEventListener("message",listenForEndEvent),event.data.data&&(event.data.data=new Uint8Array(event.data.data,options.byteOffset||0,options.byteLength||event.data.data.byteLength),options.data&&(options.data=event.data.data)),callback(event.data))};if(transmuxer.addEventListener("message",listenForE
ndEvent),options.data){const isArrayBuffer=options.data instanceof ArrayBuffer;message.byteOffset=isArrayBuffer?0:options.data.byteOffset,message.byteLength=options.data.byteLength;const transfers=[isArrayBuffer?options.data:options.data.buffer];transmuxer.postMessage(message,transfers)}else transmuxer.postMessage(message)},REQUEST_ERRORS_FAILURE=2,REQUEST_ERRORS_TIMEOUT=-101,REQUEST_ERRORS_ABORTED=-102,abortAll=activeXhrs=>{activeXhrs.forEach((xhr=>{xhr.abort()}))},handleErrors=(error,request)=>request.timedout?{status:request.status,message:"HLS request timed-out at URL: "+request.uri,code:REQUEST_ERRORS_TIMEOUT,xhr:request}:request.aborted?{status:request.status,message:"HLS request aborted at URL: "+request.uri,code:REQUEST_ERRORS_ABORTED,xhr:request}:error?{status:request.status,message:"HLS request errored at URL: "+request.uri,code:REQUEST_ERRORS_FAILURE,xhr:request}:"arraybuffer"===request.responseType&&0===request.response.byteLength?{status:request.status,message:"Empty HLS response at URL: "+reque
st.uri,code:REQUEST_ERRORS_FAILURE,xhr:request}:null,handleKeyResponse=(segment,objects,finishProcessingFn)=>(error,request)=>{const response=request.response,errorObj=handleErrors(error,request);if(errorObj)return finishProcessingFn(errorObj,segment);if(16!==response.byteLength)return finishProcessingFn({status:request.status,message:"Invalid HLS key at URL: "+request.uri,code:REQUEST_ERRORS_FAILURE,xhr:request},segment);const view=new DataView(response),bytes=new Uint32Array([view.getUint32(0),view.getUint32(4),view.getUint32(8),view.getUint32(12)]);for(let i=0;i<objects.length;i++)objects[i].bytes=bytes;return finishProcessingFn(null,segment)},parseInitSegment=(segment,callback)=>{const type=detectContainerForBytes(segment.map.bytes);if("mp4"!==type){const uri=segment.map.resolvedUri||segment.map.uri;return callback({internal:!0,message:"Found unsupported ".concat(type||"unknown"," container for initialization segment at URL: ").concat(uri),code:REQUEST_ERRORS_FAILURE})}workerCallback({action:"probeMp4Tra
cks",data:segment.map.bytes,transmuxer:segment.transmuxer,callback:_ref48=>{let{tracks:tracks,data:data}=_ref48;return segment.map.bytes=data,tracks.forEach((function(track){segment.map.tracks=segment.map.tracks||{},segment.map.tracks[track.type]||(segment.map.tracks[track.type]=track,"number"==typeof track.id&&track.timescale&&(segment.map.timescales=segment.map.timescales||{},segment.map.timescales[track.id]=track.timescale))})),callback(null)}})},handleSegmentResponse=_ref50=>{let{segment:segment,finishProcessingFn:finishProcessingFn,responseType:responseType}=_ref50;return(error,request)=>{const errorObj=handleErrors(error,request);if(errorObj)return finishProcessingFn(errorObj,segment);const newBytes="arraybuffer"!==responseType&&request.responseText?(string=>{const view=new Uint8Array(new ArrayBuffer(string.length));for(let i=0;i<string.length;i++)view[i]=string.charCodeAt(i);return view.buffer})(request.responseText.substring(segment.lastReachedChar||0)):request.response;return segment.stats=(request=
>({bandwidth:request.bandwidth,bytesReceived:request.bytesReceived||0,roundTripTime:request.roundTripTime||0}))(request),segment.key?segment.encryptedBytes=new Uint8Array(newBytes):segment.bytes=new Uint8Array(newBytes),finishProcessingFn(null,segment)}},transmuxAndNotify=_ref51=>{let{segment:segment,bytes:bytes,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,endedTimelineFn:endedTimelineFn,dataFn:dataFn,doneFn:doneFn,onTransmuxerLog:onTransmuxerLog}=_ref51;const fmp4Tracks=segment.map&&segment.map.tracks||{},isMuxed=Boolean(fmp4Tracks.audio&&fmp4Tracks.video);let audioStartFn=timingInfoFn.bind(null,segment,"audio","start");const audioEndFn=timingInfoFn.bind(null,segment,"audio","end");let videoStartFn=timingInfoFn.bind(null,segment,"video","start");const videoEndFn=timingInfoFn.bind(null,segment,"video","end");workerCallback({action:"probeTs"
,transmuxer:segment.transmuxer,data:bytes,baseStartTime:segment.baseStartTime,callback:data=>{segment.bytes=bytes=data.data;const probeResult=data.result;probeResult&&(trackInfoFn(segment,{hasAudio:probeResult.hasAudio,hasVideo:probeResult.hasVideo,isMuxed:isMuxed}),trackInfoFn=null),transmux({bytes:bytes,transmuxer:segment.transmuxer,audioAppendStart:segment.audioAppendStart,gopsToAlignWith:segment.gopsToAlignWith,remux:isMuxed,onData:result=>{result.type="combined"===result.type?"video":result.type,dataFn(segment,result)},onTrackInfo:trackInfo=>{trackInfoFn&&(isMuxed&&(trackInfo.isMuxed=!0),trackInfoFn(segment,trackInfo))},onAudioTimingInfo:audioTimingInfo=>{audioStartFn&&void 0!==audioTimingInfo.start&&(audioStartFn(audioTimingInfo.start),audioStartFn=null),audioEndFn&&void 0!==audioTimingInfo.end&&audioEndFn(audioTimingInfo.end)},onVideoTimingInfo:videoTimingInfo=>{videoStartFn&&void 0!==videoTimingInfo.start&&(videoStartFn(videoTimingInfo.start),videoStartFn=null),videoEndFn&&void 0!==videoTimingInfo.en
d&&videoEndFn(videoTimingInfo.end)},onVideoSegmentTimingInfo:videoSegmentTimingInfo=>{videoSegmentTimingInfoFn(videoSegmentTimingInfo)},onAudioSegmentTimingInfo:audioSegmentTimingInfo=>{audioSegmentTimingInfoFn(audioSegmentTimingInfo)},onId3:(id3Frames,dispatchType)=>{id3Fn(segment,id3Frames,dispatchType)},onCaptions:captions=>{captionsFn(segment,[captions])},isEndOfTimeline:isEndOfTimeline,onEndedTimeline:()=>{endedTimelineFn()},onTransmuxerLog:onTransmuxerLog,onDone:result=>{doneFn&&(result.type="combined"===result.type?"video":result.type,doneFn(null,segment,result))}})}})},handleSegmentBytes=_ref52=>{let{segment:segment,bytes:bytes,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,endedTimelineFn:endedTimelineFn,dataFn:dataFn,doneFn:doneFn,onTransmuxerLog:onTransmuxerLog}=_ref52,bytesAsUint8Array=new Uint8Array(bytes);if(function(bytes){retu
rn findBox(bytes,["moof"]).length>0}(bytesAsUint8Array)){segment.isFmp4=!0;const{tracks:tracks}=segment.map,trackInfo={isFmp4:!0,hasVideo:!!tracks.video,hasAudio:!!tracks.audio};tracks.audio&&tracks.audio.codec&&"enca"!==tracks.audio.codec&&(trackInfo.audioCodec=tracks.audio.codec),tracks.video&&tracks.video.codec&&"encv"!==tracks.video.codec&&(trackInfo.videoCodec=tracks.video.codec),tracks.video&&tracks.audio&&(trackInfo.isMuxed=!0),trackInfoFn(segment,trackInfo);const finishLoading=(captions,id3Frames)=>{dataFn(segment,{data:bytesAsUint8Array,type:trackInfo.hasAudio&&!trackInfo.isMuxed?"audio":"video"}),id3Frames&&id3Frames.length&&id3Fn(segment,id3Frames),captions&&captions.length&&captionsFn(segment,captions),doneFn(null,segment,{})};workerCallback({action:"probeMp4StartTime",timescales:segment.map.timescales,data:bytesAsUint8Array,transmuxer:segment.transmuxer,callback:_ref53=>{let{data:data,startTime:startTime}=_ref53;bytes=data.buffer,segment.bytes=bytesAsUint8Array=data,trackInfo.hasAudio&&!trackInf
o.isMuxed&&timingInfoFn(segment,"audio","start",startTime),trackInfo.hasVideo&&timingInfoFn(segment,"video","start",startTime),workerCallback({action:"probeEmsgID3",data:bytesAsUint8Array,transmuxer:segment.transmuxer,offset:startTime,callback:_ref54=>{let{emsgData:emsgData,id3Frames:id3Frames}=_ref54;bytes=emsgData.buffer,segment.bytes=bytesAsUint8Array=emsgData,tracks.video&&emsgData.byteLength&&segment.transmuxer?workerCallback({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:segment.transmuxer,data:bytesAsUint8Array,timescales:segment.map.timescales,trackIds:[tracks.video.id],callback:message=>{bytes=message.data.buffer,segment.bytes=bytesAsUint8Array=message.data,message.logs.forEach((function(log){onTransmuxerLog(merge(log,{stream:"mp4CaptionParser"}))})),finishLoading(message.captions,id3Frames)}}):finishLoading(void 0,id3Frames)}})}})}else if(segment.transmuxer){if(void 0===segment.container&&(segment.container=detectContainerForBytes(bytesAsUint8Array)),"ts"!==segment.container&&"aac"!==
segment.container)return trackInfoFn(segment,{hasAudio:!1,hasVideo:!1}),void doneFn(null,segment,{});transmuxAndNotify({segment:segment,bytes:bytes,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,endedTimelineFn:endedTimelineFn,dataFn:dataFn,doneFn:doneFn,onTransmuxerLog:onTransmuxerLog})}else doneFn(null,segment,{})},decrypt=function(_ref55,callback){let{id:id,key:key,encryptedBytes:encryptedBytes,decryptionWorker:decryptionWorker}=_ref55;const decryptionHandler=event=>{if(event.data.source===id){decryptionWorker.removeEventListener("message",decryptionHandler);const decrypted=event.data.decrypted;callback(new Uint8Array(decrypted.bytes,decrypted.byteOffset,decrypted.byteLength))}};let keyBytes;decryptionWorker.addEventListener("message",decryptionHandler),keyBytes=key.bytes.slice?key.bytes.slice():new Uint32Array(Array.prototype.slice.call(k
ey.bytes)),decryptionWorker.postMessage(createTransferableMessage({source:id,encrypted:encryptedBytes,key:keyBytes,iv:key.iv}),[encryptedBytes.buffer,keyBytes.buffer])},waitForCompletion=_ref57=>{let{activeXhrs:activeXhrs,decryptionWorker:decryptionWorker,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,endedTimelineFn:endedTimelineFn,dataFn:dataFn,doneFn:doneFn,onTransmuxerLog:onTransmuxerLog}=_ref57,count=0,didError=!1;return(error,segment)=>{if(!didError){if(error)return didError=!0,abortAll(activeXhrs),doneFn(error,segment);if(count+=1,count===activeXhrs.length){const segmentFinish=function(){if(segment.encryptedBytes)return(_ref56=>{let{decryptionWorker:decryptionWorker,segment:segment,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:
id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,endedTimelineFn:endedTimelineFn,dataFn:dataFn,doneFn:doneFn,onTransmuxerLog:onTransmuxerLog}=_ref56;decrypt({id:segment.requestId,key:segment.key,encryptedBytes:segment.encryptedBytes,decryptionWorker:decryptionWorker},(decryptedBytes=>{segment.bytes=decryptedBytes,handleSegmentBytes({segment:segment,bytes:segment.bytes,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,endedTimelineFn:endedTimelineFn,dataFn:dataFn,doneFn:doneFn,onTransmuxerLog:onTransmuxerLog})}))})({decryptionWorker:decryptionWorker,segment:segment,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,endedTimelineFn:endedTimelineFn,dataFn:dataFn,doneFn:doneFn
,onTransmuxerLog:onTransmuxerLog});handleSegmentBytes({segment:segment,bytes:segment.bytes,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,endedTimelineFn:endedTimelineFn,dataFn:dataFn,doneFn:doneFn,onTransmuxerLog:onTransmuxerLog})};if(segment.endOfAllRequests=Date.now(),segment.map&&segment.map.encryptedBytes&&!segment.map.bytes)return decrypt({decryptionWorker:decryptionWorker,id:segment.requestId+"-init",encryptedBytes:segment.map.encryptedBytes,key:segment.map.key},(decryptedBytes=>{segment.map.bytes=decryptedBytes,parseInitSegment(segment,(parseError=>{if(parseError)return abortAll(activeXhrs),doneFn(parseError,segment);segmentFinish()}))}));segmentFinish()}}}},handleProgress=_ref59=>{let{segment:segment,progressFn:progressFn,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentT
imingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,endedTimelineFn:endedTimelineFn,dataFn:dataFn}=_ref59;return event=>{if(!event.target.aborted)return segment.stats=merge(segment.stats,(progressEvent=>{const request=progressEvent.target,stats={bandwidth:1/0,bytesReceived:0,roundTripTime:Date.now()-request.requestTime||0};return stats.bytesReceived=progressEvent.loaded,stats.bandwidth=Math.floor(stats.bytesReceived/stats.roundTripTime*8*1e3),stats})(event)),!segment.stats.firstBytesReceivedAt&&segment.stats.bytesReceived&&(segment.stats.firstBytesReceivedAt=Date.now()),progressFn(event,segment)}},mediaSegmentRequest=_ref60=>{let{xhr:xhr,xhrOptions:xhrOptions,decryptionWorker:decryptionWorker,segment:segment,abortFn:abortFn,progressFn:progressFn,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,
endedTimelineFn:endedTimelineFn,dataFn:dataFn,doneFn:doneFn,onTransmuxerLog:onTransmuxerLog}=_ref60;const activeXhrs=[],finishProcessingFn=waitForCompletion({activeXhrs:activeXhrs,decryptionWorker:decryptionWorker,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,endedTimelineFn:endedTimelineFn,dataFn:dataFn,doneFn:doneFn,onTransmuxerLog:onTransmuxerLog});if(segment.key&&!segment.key.bytes){const objects=[segment.key];segment.map&&!segment.map.bytes&&segment.map.key&&segment.map.key.resolvedUri===segment.key.resolvedUri&&objects.push(segment.map.key);const keyXhr=xhr(merge(xhrOptions,{uri:segment.key.resolvedUri,responseType:"arraybuffer"}),handleKeyResponse(segment,objects,finishProcessingFn));activeXhrs.push(keyXhr)}if(segment.map&&!segment.map.bytes){if(segment.map.key&&(!segment.key||segment.key.resolvedUri!==segment.map.key.resolvedUri)){co
nst mapKeyXhr=xhr(merge(xhrOptions,{uri:segment.map.key.resolvedUri,responseType:"arraybuffer"}),handleKeyResponse(segment,[segment.map.key],finishProcessingFn));activeXhrs.push(mapKeyXhr)}const initSegmentOptions=merge(xhrOptions,{uri:segment.map.resolvedUri,responseType:"arraybuffer",headers:segmentXhrHeaders(segment.map)}),initSegmentRequestCallback=(_ref49=>{let{segment:segment,finishProcessingFn:finishProcessingFn}=_ref49;return(error,request)=>{const errorObj=handleErrors(error,request);if(errorObj)return finishProcessingFn(errorObj,segment);const bytes=new Uint8Array(request.response);if(segment.map.key)return segment.map.encryptedBytes=bytes,finishProcessingFn(null,segment);segment.map.bytes=bytes,parseInitSegment(segment,(function(parseError){if(parseError)return parseError.xhr=request,parseError.status=request.status,finishProcessingFn(parseError,segment);finishProcessingFn(null,segment)}))}})({segment:segment,finishProcessingFn:finishProcessingFn}),initSegmentXhr=xhr(initSegmentOptions,initSegment
RequestCallback);activeXhrs.push(initSegmentXhr)}const segmentRequestOptions=merge(xhrOptions,{uri:segment.part&&segment.part.resolvedUri||segment.resolvedUri,responseType:"arraybuffer",headers:segmentXhrHeaders(segment)}),segmentXhr=xhr(segmentRequestOptions,handleSegmentResponse({segment:segment,finishProcessingFn:finishProcessingFn,responseType:segmentRequestOptions.responseType}));segmentXhr.addEventListener("progress",handleProgress({segment:segment,progressFn:progressFn,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,isEndOfTimeline:isEndOfTimeline,endedTimelineFn:endedTimelineFn,dataFn:dataFn})),activeXhrs.push(segmentXhr);const loadendState={};return activeXhrs.forEach((activeXhr=>{activeXhr.addEventListener("loadend",(_ref58=>{let{loadendState:loadendState,abortFn:abortFn}=_ref58;return event=>{event.target.aborted&&abortFn&&!loadendState.calledAbortFn&&(abortFn(),l
oadendState.calledAbortFn=!0)}})({loadendState:loadendState,abortFn:abortFn}))})),()=>abortAll(activeXhrs)},logFn$1=logger("CodecUtils"),isMaat=(main,media)=>{const mediaAttributes=media.attributes||{};return main&&main.mediaGroups&&main.mediaGroups.AUDIO&&mediaAttributes.AUDIO&&main.mediaGroups.AUDIO[mediaAttributes.AUDIO]},unwrapCodecList=function(codecList){const codecs={};return codecList.forEach((_ref61=>{let{mediaType:mediaType,type:type,details:details}=_ref61;codecs[mediaType]=codecs[mediaType]||[],codecs[mediaType].push(translateLegacyCodec("".concat(type).concat(details)))})),Object.keys(codecs).forEach((function(mediaType){if(codecs[mediaType].length>1)return logFn$1("multiple ".concat(mediaType," codecs found as attributes: ").concat(codecs[mediaType].join(", "),". Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.")),void(codecs[mediaType]=null);codecs[mediaType]=codecs[mediaType][0]})),codecs},codecCount=function(codecObj){let count=0;return codecObj.a
udio&&count++,codecObj.video&&count++,count},codecsForPlaylist=function(main,media){const mediaAttributes=media.attributes||{},codecInfo=unwrapCodecList(function(media){const mediaAttributes=media.attributes||{};if(mediaAttributes.CODECS)return parseCodecs(mediaAttributes.CODECS)}(media)||[]);if(isMaat(main,media)&&!codecInfo.audio&&!((main,media)=>{if(!isMaat(main,media))return!0;const mediaAttributes=media.attributes||{},audioGroup=main.mediaGroups.AUDIO[mediaAttributes.AUDIO];for(const groupId in audioGroup)if(!audioGroup[groupId].uri&&!audioGroup[groupId].playlists)return!0;return!1})(main,media)){const defaultCodecs=unwrapCodecList(function(master,audioGroupId){if(!master.mediaGroups.AUDIO||!audioGroupId)return null;var audioGroup=master.mediaGroups.AUDIO[audioGroupId];if(!audioGroup)return null;for(var name in audioGroup){var audioType=audioGroup[name];if(audioType.default&&audioType.playlists)return parseCodecs(audioType.playlists[0].attributes.CODECS)}return null}(main,mediaAttributes.AUDIO)||[]);def
aultCodecs.audio&&(codecInfo.audio=defaultCodecs.audio)}return codecInfo},logFn=logger("PlaylistSelector"),representationToString=function(representation){if(!representation||!representation.playlist)return;const playlist=representation.playlist;return JSON.stringify({id:playlist.id,bandwidth:representation.bandwidth,width:representation.width,height:representation.height,codecs:playlist.attributes&&playlist.attributes.CODECS||""})},safeGetComputedStyle=function(el,property){if(!el)return"";const result=window.getComputedStyle(el);return result?result[property]:""},stableSort=function(array,sortFn){const newArray=array.slice();array.sort((function(left,right){const cmp=sortFn(left,right);return 0===cmp?newArray.indexOf(left)-newArray.indexOf(right):cmp}))},comparePlaylistBandwidth=function(left,right){let leftBandwidth,rightBandwidth;return left.attributes.BANDWIDTH&&(leftBandwidth=left.attributes.BANDWIDTH),leftBandwidth=leftBandwidth||window.Number.MAX_VALUE,right.attributes.BANDWIDTH&&(rightBandwidth=righ
t.attributes.BANDWIDTH),rightBandwidth=rightBandwidth||window.Number.MAX_VALUE,leftBandwidth-rightBandwidth};let simpleSelector=function(main,playerBandwidth,playerWidth,playerHeight,limitRenditionByPlayerDimensions,playlistController){if(!main)return;const options={bandwidth:playerBandwidth,width:playerWidth,height:playerHeight,limitRenditionByPlayerDimensions:limitRenditionByPlayerDimensions};let playlists=main.playlists;Playlist.isAudioOnly(main)&&(playlists=playlistController.getAudioTrackPlaylists_(),options.audioOnly=!0);let sortedPlaylistReps=playlists.map((playlist=>{let bandwidth;const width=playlist.attributes&&playlist.attributes.RESOLUTION&&playlist.attributes.RESOLUTION.width,height=playlist.attributes&&playlist.attributes.RESOLUTION&&playlist.attributes.RESOLUTION.height;return bandwidth=playlist.attributes&&playlist.attributes.BANDWIDTH,bandwidth=bandwidth||window.Number.MAX_VALUE,{bandwidth:bandwidth,width:width,height:height,playlist:playlist}}));stableSort(sortedPlaylistReps,((left,right)=>
left.bandwidth-right.bandwidth)),sortedPlaylistReps=sortedPlaylistReps.filter((rep=>!Playlist.isIncompatible(rep.playlist)));let enabledPlaylistReps=sortedPlaylistReps.filter((rep=>Playlist.isEnabled(rep.playlist)));enabledPlaylistReps.length||(enabledPlaylistReps=sortedPlaylistReps.filter((rep=>!Playlist.isDisabled(rep.playlist))));const bandwidthPlaylistReps=enabledPlaylistReps.filter((rep=>rep.bandwidth*Config.BANDWIDTH_VARIANCE<playerBandwidth));let highestRemainingBandwidthRep=bandwidthPlaylistReps[bandwidthPlaylistReps.length-1];const bandwidthBestRep=bandwidthPlaylistReps.filter((rep=>rep.bandwidth===highestRemainingBandwidthRep.bandwidth))[0];if(!1===limitRenditionByPlayerDimensions){const chosenRep=bandwidthBestRep||enabledPlaylistReps[0]||sortedPlaylistReps[0];if(chosenRep&&chosenRep.playlist){let type="sortedPlaylistReps";return bandwidthBestRep&&(type="bandwidthBestRep"),enabledPlaylistReps[0]&&(type="enabledPlaylistReps"),logFn("choosing ".concat(representationToString(chosenRep)," using ").conc
at(type," with options"),options),chosenRep.playlist}return logFn("could not choose a playlist with options",options),null}const haveResolution=bandwidthPlaylistReps.filter((rep=>rep.width&&rep.height));stableSort(haveResolution,((left,right)=>left.width-right.width));const resolutionBestRepList=haveResolution.filter((rep=>rep.width===playerWidth&&rep.height===playerHeight));highestRemainingBandwidthRep=resolutionBestRepList[resolutionBestRepList.length-1];const resolutionBestRep=resolutionBestRepList.filter((rep=>rep.bandwidth===highestRemainingBandwidthRep.bandwidth))[0];let resolutionPlusOneList,resolutionPlusOneSmallest,resolutionPlusOneRep,leastPixelDiffRep;if(resolutionBestRep||(resolutionPlusOneList=haveResolution.filter((rep=>rep.width>playerWidth||rep.height>playerHeight)),resolutionPlusOneSmallest=resolutionPlusOneList.filter((rep=>rep.width===resolutionPlusOneList[0].width&&rep.height===resolutionPlusOneList[0].height)),highestRemainingBandwidthRep=resolutionPlusOneSmallest[resolutionPlusOneSmalle
st.length-1],resolutionPlusOneRep=resolutionPlusOneSmallest.filter((rep=>rep.bandwidth===highestRemainingBandwidthRep.bandwidth))[0]),playlistController.leastPixelDiffSelector){const leastPixelDiffList=haveResolution.map((rep=>(rep.pixelDiff=Math.abs(rep.width-playerWidth)+Math.abs(rep.height-playerHeight),rep)));stableSort(leastPixelDiffList,((left,right)=>left.pixelDiff===right.pixelDiff?right.bandwidth-left.bandwidth:left.pixelDiff-right.pixelDiff)),leastPixelDiffRep=leastPixelDiffList[0]}const chosenRep=leastPixelDiffRep||resolutionPlusOneRep||resolutionBestRep||bandwidthBestRep||enabledPlaylistReps[0]||sortedPlaylistReps[0];if(chosenRep&&chosenRep.playlist){let type="sortedPlaylistReps";return leastPixelDiffRep?type="leastPixelDiffRep":resolutionPlusOneRep?type="resolutionPlusOneRep":resolutionBestRep?type="resolutionBestRep":bandwidthBestRep?type="bandwidthBestRep":enabledPlaylistReps[0]&&(type="enabledPlaylistReps"),logFn("choosing ".concat(representationToString(chosenRep)," using ").concat(type," wi
th options"),options),chosenRep.playlist}return logFn("could not choose a playlist with options",options),null};const lastBandwidthSelector=function(){const pixelRatio=this.useDevicePixelRatio&&window.devicePixelRatio||1;return simpleSelector(this.playlists.main,this.systemBandwidth,parseInt(safeGetComputedStyle(this.tech_.el(),"width"),10)*pixelRatio,parseInt(safeGetComputedStyle(this.tech_.el(),"height"),10)*pixelRatio,this.limitRenditionByPlayerDimensions,this.playlistController_)},addMetadata=_ref63=>{let{inbandTextTracks:inbandTextTracks,metadataArray:metadataArray,timestampOffset:timestampOffset,videoDuration:videoDuration}=_ref63;if(!metadataArray)return;const Cue=window.WebKitDataCue||window.VTTCue,metadataTrack=inbandTextTracks.metadataTrack_;if(!metadataTrack)return;if(metadataArray.forEach((metadata=>{const time=metadata.cueTime+timestampOffset;!("number"!=typeof time||window.isNaN(time)||time<0)&&time<1/0&&metadata.frames&&metadata.frames.length&&metadata.frames.forEach((frame=>{const cue=new Cue
(time,time,frame.value||frame.url||frame.data||"");cue.frame=frame,cue.value=frame,function(cue){Object.defineProperties(cue.frame,{id:{get:()=>(videojs.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),cue.value.key)},value:{get:()=>(videojs.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),cue.value.data)},privateData:{get:()=>(videojs.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),cue.value.data)}})}(cue),metadataTrack.addCue(cue)}))})),!metadataTrack.cues||!metadataTrack.cues.length)return;const cues=metadataTrack.cues,cuesArray=[];for(let i=0;i<cues.length;i++)cues[i]&&cuesArray.push(cues[i]);const cuesGroupedByStartTime=cuesArray.reduce(((obj,cue)=>{const timeSlot=obj[cue.startTime]||[];return timeSlot.push(cue),obj[cue.startTime]=timeSlot,obj}),{}),sortedStartTimes=Object.keys(cuesGroupedByStartTime).sort(((a,b)=>Number(a)-Number(b)));sortedStartTimes.forEach(((startTime,idx)=>{const cueGroup=cuesGroupedByStartTime[startTime],finiteDu
ration=isFinite(videoDuration)?videoDuration:startTime,nextTime=Number(sortedStartTimes[idx+1])||finiteDuration;cueGroup.forEach((cue=>{cue.endTime=nextTime}))}))},dateRangeAttr={id:"ID",class:"CLASS",startDate:"START-DATE",duration:"DURATION",endDate:"END-DATE",endOnNext:"END-ON-NEXT",plannedDuration:"PLANNED-DURATION",scte35Out:"SCTE35-OUT",scte35In:"SCTE35-IN"},dateRangeKeysToOmit=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),createMetadataTrackIfNotExists=(inbandTextTracks,dispatchType,tech)=>{inbandTextTracks.metadataTrack_||(inbandTextTracks.metadataTrack_=tech.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,videojs.browser.IS_ANY_SAFARI||(inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType=dispatchType))},removeCuesFromTrack=function(start,end,track){let i,cue;if(track&&track.cues)for(i=track.cues.length;i--;)cue=track.cues[i],cue.startTime>=start&&cue.endTime<=end&&track.removeCue(cue)},finite=num=>"numb
er"==typeof num&&isFinite(num),segmentInfoString=segmentInfo=>{const{startOfSegment:startOfSegment,duration:duration,segment:segment,part:part,playlist:{mediaSequence:seq,id:id,segments:segments=[]},mediaIndex:index,partIndex:partIndex,timeline:timeline}=segmentInfo,segmentLen=segments.length-1;let selection="mediaIndex/partIndex increment";segmentInfo.getMediaInfoForTime?selection="getMediaInfoForTime (".concat(segmentInfo.getMediaInfoForTime,")"):segmentInfo.isSyncRequest&&(selection="getSyncSegmentCandidate (isSyncRequest)"),segmentInfo.independent&&(selection+=" with independent ".concat(segmentInfo.independent));const hasPartIndex="number"==typeof partIndex,name=segmentInfo.segment.uri?"segment":"pre-segment",zeroBasedPartCount=hasPartIndex?getKnownPartCount({preloadSegment:segment})-1:0;return"".concat(name," [").concat(seq+index,"/").concat(seq+segmentLen,"]")+(hasPartIndex?" part [".concat(partIndex,"/").concat(zeroBasedPartCount,"]"):"")+" segment start/end [".concat(segment.start," => ").concat(seg
ment.end,"]")+(hasPartIndex?" part start/end [".concat(part.start," => ").concat(part.end,"]"):"")+" startOfSegment [".concat(startOfSegment,"]")+" duration [".concat(duration,"]")+" timeline [".concat(timeline,"]")+" selected by [".concat(selection,"]")+" playlist [".concat(id,"]")},timingInfoPropertyForMedia=mediaType=>"".concat(mediaType,"TimingInfo"),shouldWaitForTimelineChange=_ref66=>{let{timelineChangeController:timelineChangeController,currentTimeline:currentTimeline,segmentTimeline:segmentTimeline,loaderType:loaderType,audioDisabled:audioDisabled}=_ref66;if(currentTimeline===segmentTimeline)return!1;if("audio"===loaderType){const lastMainTimelineChange=timelineChangeController.lastTimelineChange({type:"main"});return!lastMainTimelineChange||lastMainTimelineChange.to!==segmentTimeline}if("main"===loaderType&&audioDisabled){const pendingAudioTimelineChange=timelineChangeController.pendingTimelineChange({type:"audio"});return!pendingAudioTimelineChange||pendingAudioTimelineChange.to!==segmentTimeline}r
eturn!1},segmentTooLong=_ref67=>{let{segmentDuration:segmentDuration,maxDuration:maxDuration}=_ref67;return!!segmentDuration&&Math.round(segmentDuration)>maxDuration+.03333333333333333},getTroublesomeSegmentDurationMessage=(segmentInfo,sourceType)=>{if("hls"!==sourceType)return null;const segmentDuration=(timingInfos=>{let maxDuration=0;return["video","audio"].forEach((function(type){const typeTimingInfo=timingInfos["".concat(type,"TimingInfo")];if(!typeTimingInfo)return;const{start:start,end:end}=typeTimingInfo;let duration;"bigint"==typeof start||"bigint"==typeof end?duration=window.BigInt(end)-window.BigInt(start):"number"==typeof start&&"number"==typeof end&&(duration=end-start),void 0!==duration&&duration>maxDuration&&(maxDuration=duration)})),"bigint"==typeof maxDuration&&maxDuration<Number.MAX_SAFE_INTEGER&&(maxDuration=Number(maxDuration)),maxDuration})({audioTimingInfo:segmentInfo.audioTimingInfo,videoTimingInfo:segmentInfo.videoTimingInfo});if(!segmentDuration)return null;const targetDuration=segme
ntInfo.playlist.targetDuration,isSegmentWayTooLong=segmentTooLong({segmentDuration:segmentDuration,maxDuration:2*targetDuration}),isSegmentSlightlyTooLong=segmentTooLong({segmentDuration:segmentDuration,maxDuration:targetDuration}),segmentTooLongMessage="Segment with index ".concat(segmentInfo.mediaIndex," ")+"from playlist ".concat(segmentInfo.playlist.id," ")+"has a duration of ".concat(segmentDuration," ")+"when the reported duration is ".concat(segmentInfo.duration," ")+"and the target duration is ".concat(targetDuration,". ")+"For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1";return isSegmentWayTooLong||isSegmentSlightlyTooLong?{severity:isSegmentWayTooLong?"warn":"info",message:segmentTooLongMessage}:null};class SegmentLoader extends videojs.EventTarget{constructor(settings){if(super(),!settings)throw new T
ypeError("Initialization settings are required");if("function"!=typeof settings.currentTime)throw new TypeError("No currentTime getter specified");if(!settings.mediaSource)throw new TypeError("No MediaSource specified");this.bandwidth=settings.bandwidth,this.throughput={rate:0,count:0},this.roundTrip=NaN,this.resetStats_(),this.mediaIndex=null,this.partIndex=null,this.hasPlayed_=settings.hasPlayed,this.currentTime_=settings.currentTime,this.seekable_=settings.seekable,this.seeking_=settings.seeking,this.duration_=settings.duration,this.mediaSource_=settings.mediaSource,this.vhs_=settings.vhs,this.loaderType_=settings.loaderType,this.currentMediaInfo_=void 0,this.startingMediaInfo_=void 0,this.segmentMetadataTrack_=settings.segmentMetadataTrack,this.goalBufferLength_=settings.goalBufferLength,this.sourceType_=settings.sourceType,this.sourceUpdater_=settings.sourceUpdater,this.inbandTextTracks_=settings.inbandTextTracks,this.state_="INIT",this.timelineChangeController_=settings.timelineChangeController,this.sh
ouldSaveSegmentTimingInfo_=!0,this.parse708captions_=settings.parse708captions,this.useDtsForTimestampOffset_=settings.useDtsForTimestampOffset,this.captionServices_=settings.captionServices,this.exactManifestTimings=settings.exactManifestTimings,this.addMetadataToTextTrack=settings.addMetadataToTextTrack,this.checkBufferTimeout_=null,this.error_=void 0,this.currentTimeline_=-1,this.shouldForceTimestampOffsetAfterResync_=!1,this.pendingSegment_=null,this.xhrOptions_=null,this.pendingSegments_=[],this.audioDisabled_=!1,this.isPendingTimestampOffset_=!1,this.gopBuffer_=[],this.timeMapping_=0,this.safeAppend_=!1,this.appendInitSegment_={audio:!0,video:!0},this.playlistOfLastInitSegment_={audio:null,video:null},this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_={id3:[],caption:[]},this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=null,this.activeInitSegmentId_=null,this.initSegments_={},this.cacheEncryptionKeys_=settings.cacheEncryptionKeys,this.keyCache_={},this.decrypter_=settings.decrypter,
this.syncController_=settings.syncController,this.syncPoint_={segmentIndex:0,time:0},this.transmuxer_=this.createTransmuxer_(),this.triggerSyncInfoUpdate_=()=>this.trigger("syncinfoupdate"),this.syncController_.on("syncinfoupdate",this.triggerSyncInfoUpdate_),this.mediaSource_.addEventListener("sourceopen",(()=>{this.isEndOfStream_()||(this.ended_=!1)})),this.fetchAtBuffer_=!1,this.logger_=logger("SegmentLoader[".concat(this.loaderType_,"]")),Object.defineProperty(this,"state",{get(){return this.state_},set(newState){newState!==this.state_&&(this.logger_("".concat(this.state_," -> ").concat(newState)),this.state_=newState,this.trigger("statechange"))}}),this.sourceUpdater_.on("ready",(()=>{this.hasEnoughInfoToAppend_()&&this.processCallQueue_()})),"main"===this.loaderType_&&this.timelineChangeController_.on("pendingtimelinechange",(()=>{this.hasEnoughInfoToAppend_()&&this.processCallQueue_()})),"audio"===this.loaderType_&&this.timelineChangeController_.on("timelinechange",(()=>{this.hasEnoughInfoToLoad_()&&t
his.processLoadQueue_(),this.hasEnoughInfoToAppend_()&&this.processCallQueue_()}))}createTransmuxer_(){return segmentTransmuxer_createTransmuxer({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,captionServices:this.captionServices_})}resetStats_(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0}dispose(){this.trigger("dispose"),this.state="DISPOSED",this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&window.clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_),this.off()}setAudio(enable){this.audioDisabled_=!enable,enable?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){"WAITIN
G"===this.state?(this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_()):this.pendingSegment_&&(this.pendingSegment_=null)}abort_(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests(),this.pendingSegment_=null,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_),this.waitingOnRemove_=!1,window.clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(requestId){return"APPENDING"!==this.state||this.pendingSegment_?!this.pendingSegment_||this.pendingSegment_.requestId!==requestId:(this.state="READY",!0)}error(error){return void 0!==error&&(this.logger_("error occurred:",error),this.error_=error),this.pendingSegment_=null,this.error_}endOfStream(){this.ended_=!0,this.transmuxer_&&segmentTransmuxer_reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered
_(){const trackInfo=this.getMediaInfo_();if(!this.sourceUpdater_||!trackInfo)return createTimeRanges();if("main"===this.loaderType_){const{hasAudio:hasAudio,hasVideo:hasVideo,isMuxed:isMuxed}=trackInfo;if(hasVideo&&hasAudio&&!this.audioDisabled_&&!isMuxed)return this.sourceUpdater_.buffered();if(hasVideo)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(map){let set=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!map)return null;const id=initSegmentId(map);let storedMap=this.initSegments_[id];return set&&!storedMap&&map.bytes&&(this.initSegments_[id]=storedMap={resolvedUri:map.resolvedUri,byterange:map.byterange,bytes:map.bytes,tracks:map.tracks,timescales:map.timescales}),storedMap||map}segmentKey(key){let set=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!key)return null;const id=segmentKeyId(key);let storedKey=this.keyCache_[id];this.cacheEncryptionKeys_&&set&&!storedKey&&key.bytes&&(this.keyCache_[id]=storedKey={resolvedUri:ke
y.resolvedUri,bytes:key.bytes});const result={resolvedUri:(storedKey||key).resolvedUri};return storedKey&&(result.bytes=storedKey.bytes),result}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),this.playlist_)return"INIT"===this.state&&this.couldBeginLoading_()?this.init_():void(!this.couldBeginLoading_()||"READY"!==this.state&&"INIT"!==this.state||(this.state="READY"))}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}playlist(newPlaylist){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!newPlaylist)return;const oldPlaylist=this.playlist_,segmentInfo=this.pendingSegment_;this.playlist_=newPlaylist,this.xhrOptions_=options,"INIT"===this.state&&(newPlaylist.syncInfo={mediaSequence:newPlaylist.mediaSequence,time:0},"main"===this.loaderType_&&this.syncController_.setDateTimeMappingForStart(newPlaylist));let oldId=null;if(oldPlaylist&&(oldPlaylist.id?oldId=oldPlaylist.id:oldPlaylist.uri&&(oldId=oldPlaylist.uri)),this.l
ogger_("playlist update [".concat(oldId," => ").concat(newPlaylist.id||newPlaylist.uri,"]")),this.syncController_.updateMediaSequenceMap(newPlaylist,this.currentTime_(),this.loaderType_),this.trigger("syncinfoupdate"),"INIT"===this.state&&this.couldBeginLoading_())return this.init_();if(!oldPlaylist||oldPlaylist.uri!==newPlaylist.uri){if(null!==this.mediaIndex){!newPlaylist.endList&&"number"==typeof newPlaylist.partTargetDuration?this.resetLoader():this.resyncLoader()}return this.currentMediaInfo_=void 0,void this.trigger("playlistupdate")}const mediaSequenceDiff=newPlaylist.mediaSequence-oldPlaylist.mediaSequence;if(this.logger_("live window shift [".concat(mediaSequenceDiff,"]")),null!==this.mediaIndex)if(this.mediaIndex-=mediaSequenceDiff,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{const segment=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!segment.parts||!segment.parts.length||!segment.parts[this.partIndex])){const mediaIndex=this.mediaIndex;this.logger_("currently pro
cessing part (index ".concat(this.partIndex,") no longer exists.")),this.resetLoader(),this.mediaIndex=mediaIndex}}segmentInfo&&(segmentInfo.mediaIndex-=mediaSequenceDiff,segmentInfo.mediaIndex<0?(segmentInfo.mediaIndex=null,segmentInfo.partIndex=null):(segmentInfo.mediaIndex>=0&&(segmentInfo.segment=newPlaylist.segments[segmentInfo.mediaIndex]),segmentInfo.partIndex>=0&&segmentInfo.segment.parts&&(segmentInfo.part=segmentInfo.segment.parts[segmentInfo.partIndex]))),this.syncController_.saveExpiredSegmentInfo(oldPlaylist,newPlaylist)}pause(){this.checkBufferTimeout_&&(window.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=null)}paused(){return null===this.checkBufferTimeout_}resetEverything(done){this.ended_=!1,this.activeInitSegmentId_=null,this.appendInitSegment_={audio:!0,video:!0},this.resetLoader(),this.remove(0,1/0,done),this.transmuxer_&&(this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.transmuxer_.postMessage({action:"reset"}))}resetLoader(){this.fetchAtBuffer_=!1,thi
s.resyncLoader()}resyncLoader(){this.transmuxer_&&segmentTransmuxer_reset(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1,this.shouldForceTimestampOffsetAfterResync_=!0,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}remove(start,end){let done=arguments.length>2&&void 0!==arguments[2]?arguments[2]:()=>{},force=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(end===1/0&&(end=this.duration_()),end<=start)return void this.logger_("skipping remove because end ${end} is <= start ${start}");if(!this.sourceUpdater_||!this.getMediaInfo_())return void this.logger_("skipping remove because no source updater or starting media info");let removesRemaining=1;const removeFinished=()=>{removesRemaining--,0===removesRemaining&&done()};!force&&this.audioDisabled_||(removesRemaining++,this.sourceUpdater_.removeA
udio(start,end,removeFinished)),(force||"main"===this.loaderType_)&&(this.gopBuffer_=((buffer,start,end,mapping)=>{const startPts=Math.ceil((start-mapping)*clock_1),endPts=Math.ceil((end-mapping)*clock_1),updatedBuffer=buffer.slice();let i=buffer.length;for(;i--&&!(buffer[i].pts<=endPts););if(-1===i)return updatedBuffer;let j=i+1;for(;j--&&!(buffer[j].pts<=startPts););return j=Math.max(j,0),updatedBuffer.splice(j,i-j+1),updatedBuffer})(this.gopBuffer_,start,end,this.timeMapping_),removesRemaining++,this.sourceUpdater_.removeVideo(start,end,removeFinished));for(const track in this.inbandTextTracks_)removeCuesFromTrack(start,end,this.inbandTextTracks_[track]);removeCuesFromTrack(start,end,this.segmentMetadataTrack_),removeFinished()}monitorBuffer_(){this.checkBufferTimeout_&&window.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=window.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){"READY"===this.state&&this.fillBuffer_(),this.checkBufferTimeout_&&window.clearTimeout(this
.checkBufferTimeout_),this.checkBufferTimeout_=window.setTimeout(this.monitorBufferTick_.bind(this),500)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const segmentInfo=this.chooseNextRequest_();segmentInfo&&("number"==typeof segmentInfo.timestampOffset&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:segmentInfo.timeline})),this.loadSegment_(segmentInfo))}isEndOfStream_(){let mediaIndex=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.mediaIndex,playlist=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.playlist_,partIndex=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.partIndex;if(!playlist||!this.mediaSource_)return!1;const segment="number"==typeof mediaIndex&&playlist.segments[mediaIndex],appendedLastSegment=mediaIndex+1===playlist.segments.length,appendedLastPart=!segment||!segment.parts||partIndex+1===segment.parts.length;return playlist.endList&&"open"===this.mediaSou
rce_.readyState&&appendedLastSegment&&appendedLastPart}chooseNextRequest_(){const buffered=this.buffered_(),bufferedEnd=lastBufferedEnd(buffered)||0,bufferedTime=timeAheadOf(buffered,this.currentTime_()),preloaded=!this.hasPlayed_()&&bufferedTime>=1,haveEnoughBuffer=bufferedTime>=this.goalBufferLength_(),segments=this.playlist_.segments;if(!segments.length||preloaded||haveEnoughBuffer)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);const next={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:Boolean(!this.syncPoint_)};if(next.isSyncRequest)next.mediaIndex=function(currentTimeline,segments,targetTime){segments=segments||[];const timelineSegments=[];let time=0;for(let i=0;i<segments.length;i++){const segment=segments[i];if(currentTimeline===segment.timeline&&(timelineSegments.push(i),time+=segment.duration,time>targetTime))return i}return 0===timelin
eSegments.length?0:timelineSegments[timelineSegments.length-1]}(this.currentTimeline_,segments,bufferedEnd),this.logger_("choose next request. Can not find sync point. Fallback to media Index: ".concat(next.mediaIndex));else if(null!==this.mediaIndex){const segment=segments[this.mediaIndex],partIndex="number"==typeof this.partIndex?this.partIndex:-1;next.startOfSegment=segment.end?segment.end:bufferedEnd,segment.parts&&segment.parts[partIndex+1]?(next.mediaIndex=this.mediaIndex,next.partIndex=partIndex+1):next.mediaIndex=this.mediaIndex+1}else{const{segmentIndex:segmentIndex,startTime:startTime,partIndex:partIndex}=Playlist.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:this.fetchAtBuffer_?bufferedEnd:this.currentTime_(),startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});next.getMediaInfoForTime=this.fetchAtBuffer_?"bufferedEnd ".concat(bufferedEnd):"currentTime ".concat(this.c
urrentTime_()),next.mediaIndex=segmentIndex,next.startOfSegment=startTime,next.partIndex=partIndex,this.logger_("choose next request. Playlist switched and we have a sync point. Media Index: ".concat(next.mediaIndex," "))}const nextSegment=segments[next.mediaIndex];let nextPart=nextSegment&&"number"==typeof next.partIndex&&nextSegment.parts&&nextSegment.parts[next.partIndex];if(!nextSegment||"number"==typeof next.partIndex&&!nextPart)return null;"number"!=typeof next.partIndex&&nextSegment.parts&&(next.partIndex=0,nextPart=nextSegment.parts[0]);const hasIndependentSegments=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!bufferedTime&&nextPart&&!hasIndependentSegments&&!nextPart.independent)if(0===next.partIndex){const lastSegment=segments[next.mediaIndex-1],lastSegmentLastPart=lastSegment.parts&&lastSegment.parts.length&&lastSegment.parts[lastSegment.parts.length-1];lastSegmentLastPart&&lastSegmentLastPart.independent&&(next.
mediaIndex-=1,next.partIndex=lastSegment.parts.length-1,next.independent="previous segment")}else nextSegment.parts[next.partIndex-1].independent&&(next.partIndex-=1,next.independent="previous part");const ended=this.mediaSource_&&"ended"===this.mediaSource_.readyState;return next.mediaIndex>=segments.length-1&&ended&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,next.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync")),this.generateSegmentInfo_(next))}generateSegmentInfo_(options){const{independent:independent,playlist:playlist,mediaIndex:mediaIndex,startOfSegment:startOfSegment,isSyncRequest:isSyncRequest,partIndex:partIndex,forceTimestampOffset:forceTimestampOffset,getMediaInfoForTime:getMediaInfoForTime}=options,segment=playlist.segments[mediaIndex],part="number"==typeof partIndex&&segment.parts[partIndex],segmentInfo={requestId:"segment-loader-"+Math.random(),uri:part&&part.resolvedU
ri||segment.resolvedUri,mediaIndex:mediaIndex,partIndex:part?partIndex:null,isSyncRequest:isSyncRequest,startOfSegment:startOfSegment,playlist:playlist,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:segment.timeline,duration:part&&part.duration||segment.duration,segment:segment,part:part,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:getMediaInfoForTime,independent:independent},overrideCheck=void 0!==forceTimestampOffset?forceTimestampOffset:this.isPendingTimestampOffset_;segmentInfo.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:segment.timeline,currentTimeline:this.currentTimeline_,startOfSegment:startOfSegment,buffered:this.buffered_(),overrideCheck:overrideCheck});const audioBufferedEnd=lastBufferedEnd(this.sourceUpdater_.audioBuffered());return"number"==typeof audioBufferedEnd&&(segmentInfo.audioAppendStart=audioBufferedEnd-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(segmentInfo.gopsToAlignWith=((buffer,currentTim
e,mapping)=>{if(null==currentTime||!buffer.length)return[];const currentTimePts=Math.ceil((currentTime-mapping+3)*clock_1);let i;for(i=0;i<buffer.length&&!(buffer[i].pts>currentTimePts);i++);return buffer.slice(i)})(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),segmentInfo}timestampOffsetForSegment_(options){return(_ref65=>{let{segmentTimeline:segmentTimeline,currentTimeline:currentTimeline,startOfSegment:startOfSegment,buffered:buffered,overrideCheck:overrideCheck}=_ref65;return overrideCheck||segmentTimeline!==currentTimeline?segmentTimeline<currentTimeline?startOfSegment:buffered.length?buffered.end(buffered.length-1):startOfSegment:null})(options)}earlyAbortWhenNeeded_(stats){if(this.vhs_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH)return;if(Date.now()-(stats.firstBytesReceivedAt||Date.now())<1e3)return;const currentTime=this.currentTime_(),measuredBandwidth=stats.bandwidth,segmentDuration=this.pendingSegment_.durati
on,requestTimeRemaining=Playlist.estimateSegmentRequestTime(segmentDuration,measuredBandwidth,this.playlist_,stats.bytesReceived),timeUntilRebuffer$1=function(buffered,currentTime){let playbackRate=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return((buffered.length?buffered.end(buffered.length-1):0)-currentTime)/playbackRate}(this.buffered_(),currentTime,this.vhs_.tech_.playbackRate())-1;if(requestTimeRemaining<=timeUntilRebuffer$1)return;const switchCandidate=function(settings){const{main:main,currentTime:currentTime,bandwidth:bandwidth,duration:duration,segmentDuration:segmentDuration,timeUntilRebuffer:timeUntilRebuffer,currentTimeline:currentTimeline,syncController:syncController}=settings,compatiblePlaylists=main.playlists.filter((playlist=>!Playlist.isIncompatible(playlist)));let enabledPlaylists=compatiblePlaylists.filter(Playlist.isEnabled);enabledPlaylists.length||(enabledPlaylists=compatiblePlaylists.filter((playlist=>!Playlist.isDisabled(playlist))));const rebufferingEstimates=enabledP
laylists.filter(Playlist.hasAttribute.bind(null,"BANDWIDTH")).map((playlist=>{const numRequests=syncController.getSyncPoint(playlist,duration,currentTimeline,currentTime)?1:2;return{playlist:playlist,rebufferingImpact:Playlist.estimateSegmentRequestTime(segmentDuration,bandwidth,playlist)*numRequests-timeUntilRebuffer}})),noRebufferingPlaylists=rebufferingEstimates.filter((estimate=>estimate.rebufferingImpact<=0));return stableSort(noRebufferingPlaylists,((a,b)=>comparePlaylistBandwidth(b.playlist,a.playlist))),noRebufferingPlaylists.length?noRebufferingPlaylists[0]:(stableSort(rebufferingEstimates,((a,b)=>a.rebufferingImpact-b.rebufferingImpact)),rebufferingEstimates[0]||null)}({main:this.vhs_.playlists.main,currentTime:currentTime,bandwidth:measuredBandwidth,duration:this.duration_(),segmentDuration:segmentDuration,timeUntilRebuffer:timeUntilRebuffer$1,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!switchCandidate)return;const timeSavedBySwitching=requestTimeRemaining-timeU
ntilRebuffer$1-switchCandidate.rebufferingImpact;let minimumTimeSaving=.5;timeUntilRebuffer$1<=.03333333333333333&&(minimumTimeSaving=1),!switchCandidate.playlist||switchCandidate.playlist.uri===this.playlist_.uri||timeSavedBySwitching<minimumTimeSaving||(this.bandwidth=switchCandidate.playlist.attributes.BANDWIDTH*Config.BANDWIDTH_VARIANCE+1,this.trigger("earlyabort"))}handleAbort_(segmentInfo){this.logger_("Aborting ".concat(segmentInfoString(segmentInfo))),this.mediaRequestsAborted+=1}handleProgress_(event,simpleSegment){this.earlyAbortWhenNeeded_(simpleSegment.stats),this.checkForAbort_(simpleSegment.requestId)||this.trigger("progress")}handleTrackInfo_(simpleSegment,trackInfo){this.earlyAbortWhenNeeded_(simpleSegment.stats),this.checkForAbort_(simpleSegment.requestId)||this.checkForIllegalMediaSwitch(trackInfo)||(trackInfo=trackInfo||{},function(a,b){if(!a&&!b||!a&&b||a&&!b)return!1;if(a===b)return!0;const akeys=Object.keys(a).sort(),bkeys=Object.keys(b).sort();if(akeys.length!==bkeys.length)return!1;fo
r(let i=0;i<akeys.length;i++){const key=akeys[i];if(key!==bkeys[i])return!1;if(a[key]!==b[key])return!1}return!0}(this.currentMediaInfo_,trackInfo)||(this.appendInitSegment_={audio:!0,video:!0},this.startingMediaInfo_=trackInfo,this.currentMediaInfo_=trackInfo,this.logger_("trackinfo update",trackInfo),this.trigger("trackinfo")),this.checkForAbort_(simpleSegment.requestId)||(this.pendingSegment_.trackInfo=trackInfo,this.hasEnoughInfoToAppend_()&&this.processCallQueue_()))}handleTimingInfo_(simpleSegment,mediaType,timeType,time){if(this.earlyAbortWhenNeeded_(simpleSegment.stats),this.checkForAbort_(simpleSegment.requestId))return;const segmentInfo=this.pendingSegment_,timingInfoProperty=timingInfoPropertyForMedia(mediaType);segmentInfo[timingInfoProperty]=segmentInfo[timingInfoProperty]||{},segmentInfo[timingInfoProperty][timeType]=time,this.logger_("timinginfo: ".concat(mediaType," - ").concat(timeType," - ").concat(time)),this.hasEnoughInfoToAppend_()&&this.processCallQueue_()}handleCaptions_(simpleSegment,
captionData){if(this.earlyAbortWhenNeeded_(simpleSegment.stats),this.checkForAbort_(simpleSegment.requestId))return;if(0===captionData.length)return void this.logger_("SegmentLoader received no captions from a caption event");if(!this.pendingSegment_.hasAppendedData_)return void this.metadataQueue_.caption.push(this.handleCaptions_.bind(this,simpleSegment,captionData));const timestampOffset=null===this.sourceUpdater_.videoTimestampOffset()?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset(),captionTracks={};captionData.forEach((caption=>{captionTracks[caption.stream]=captionTracks[caption.stream]||{startTime:1/0,captions:[],endTime:0};const captionTrack=captionTracks[caption.stream];captionTrack.startTime=Math.min(captionTrack.startTime,caption.startTime+timestampOffset),captionTrack.endTime=Math.max(captionTrack.endTime,caption.endTime+timestampOffset),captionTrack.captions.push(caption)})),Object.keys(captionTracks).forEach((trackName=>{const{startTime:startTime,endTime:en
dTime,captions:captions}=captionTracks[trackName],inbandTextTracks=this.inbandTextTracks_;this.logger_("adding cues from ".concat(startTime," -> ").concat(endTime," for ").concat(trackName)),function(inbandTextTracks,tech,captionStream){if(!inbandTextTracks[captionStream]){tech.trigger({type:"usage",name:"vhs-608"});let instreamId=captionStream;/^cc708_/.test(captionStream)&&(instreamId="SERVICE"+captionStream.split("_")[1]);const track=tech.textTracks().getTrackById(instreamId);if(track)inbandTextTracks[captionStream]=track;else{let label=captionStream,language=captionStream,def=!1;const captionService=(tech.options_.vhs&&tech.options_.vhs.captionServices||{})[instreamId];captionService&&(label=captionService.label,language=captionService.language,def=captionService.default),inbandTextTracks[captionStream]=tech.addRemoteTextTrack({kind:"captions",id:instreamId,default:def,label:label,language:language},!1).track}}}(inbandTextTracks,this.vhs_.tech_,trackName),removeCuesFromTrack(startTime,endTime,inbandTextT
racks[trackName]),function(_ref62){let{inbandTextTracks:inbandTextTracks,captionArray:captionArray,timestampOffset:timestampOffset}=_ref62;if(!captionArray)return;const Cue=window.WebKitDataCue||window.VTTCue;captionArray.forEach((caption=>{const track=caption.stream;caption.content?caption.content.forEach((value=>{const cue=new Cue(caption.startTime+timestampOffset,caption.endTime+timestampOffset,value.text);cue.line=value.line,cue.align="left",cue.position=value.position,cue.positionAlign="line-left",inbandTextTracks[track].addCue(cue)})):inbandTextTracks[track].addCue(new Cue(caption.startTime+timestampOffset,caption.endTime+timestampOffset,caption.text))}))}({captionArray:captions,inbandTextTracks:inbandTextTracks,timestampOffset:timestampOffset})})),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}handleId3_(simpleSegment,id3Frames,dispatchType){if(this.earlyAbortWhenNeeded_(simpleSegment.stats),this.checkForAbort_(simpleSegment.requestId))return;this.pendingSegment_.has
AppendedData_?this.addMetadataToTextTrack(dispatchType,id3Frames,this.duration_()):this.metadataQueue_.id3.push(this.handleId3_.bind(this,simpleSegment,id3Frames,dispatchType))}processMetadataQueue_(){this.metadataQueue_.id3.forEach((fn=>fn())),this.metadataQueue_.caption.forEach((fn=>fn())),this.metadataQueue_.id3=[],this.metadataQueue_.caption=[]}processCallQueue_(){const callQueue=this.callQueue_;this.callQueue_=[],callQueue.forEach((fun=>fun()))}processLoadQueue_(){const loadQueue=this.loadQueue_;this.loadQueue_=[],loadQueue.forEach((fun=>fun()))}hasEnoughInfoToLoad_(){if("audio"!==this.loaderType_)return!0;const segmentInfo=this.pendingSegment_;return!!segmentInfo&&(!this.getCurrentMediaInfo_()||!shouldWaitForTimelineChange({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:segmentInfo.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}getCurrentMediaInfo_(){let segmentInfo=arguments.length>0&&void 0!==arguments[0]?argume
nts[0]:this.pendingSegment_;return segmentInfo&&segmentInfo.trackInfo||this.currentMediaInfo_}getMediaInfo_(){let segmentInfo=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.pendingSegment_;return this.getCurrentMediaInfo_(segmentInfo)||this.startingMediaInfo_}getPendingSegmentPlaylist(){return this.pendingSegment_?this.pendingSegment_.playlist:null}hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready())return!1;if(this.waitingOnRemove_||this.quotaExceededErrorRetryTimeout_)return!1;const segmentInfo=this.pendingSegment_,trackInfo=this.getCurrentMediaInfo_();if(!segmentInfo||!trackInfo)return!1;const{hasAudio:hasAudio,hasVideo:hasVideo,isMuxed:isMuxed}=trackInfo;return!(hasVideo&&!segmentInfo.videoTimingInfo)&&(!(hasAudio&&!this.audioDisabled_&&!isMuxed&&!segmentInfo.audioTimingInfo)&&!shouldWaitForTimelineChange({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:segmentInfo.timeline,loaderType:this.loaderType_,audioDisabled:this.audio
Disabled_}))}handleData_(simpleSegment,result){if(this.earlyAbortWhenNeeded_(simpleSegment.stats),this.checkForAbort_(simpleSegment.requestId))return;if(this.callQueue_.length||!this.hasEnoughInfoToAppend_())return void this.callQueue_.push(this.handleData_.bind(this,simpleSegment,result));const segmentInfo=this.pendingSegment_;if(this.setTimeMapping_(segmentInfo.timeline),this.updateMediaSecondsLoaded_(segmentInfo.part||segmentInfo.segment),"closed"!==this.mediaSource_.readyState){if(simpleSegment.map&&(simpleSegment.map=this.initSegmentForMap(simpleSegment.map,!0),segmentInfo.segment.map=simpleSegment.map),simpleSegment.key&&this.segmentKey(simpleSegment.key,!0),segmentInfo.isFmp4=simpleSegment.isFmp4,segmentInfo.timingInfo=segmentInfo.timingInfo||{},segmentInfo.isFmp4)this.trigger("fmp4"),segmentInfo.timingInfo.start=segmentInfo[timingInfoPropertyForMedia(result.type)].start;else{const trackInfo=this.getCurrentMediaInfo_(),useVideoTimingInfo="main"===this.loaderType_&&trackInfo&&trackInfo.hasVideo;let fir
stVideoFrameTimeForData;useVideoTimingInfo&&(firstVideoFrameTimeForData=segmentInfo.videoTimingInfo.start),segmentInfo.timingInfo.start=this.trueSegmentStart_({currentStart:segmentInfo.timingInfo.start,playlist:segmentInfo.playlist,mediaIndex:segmentInfo.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:useVideoTimingInfo,firstVideoFrameTimeForData:firstVideoFrameTimeForData,videoTimingInfo:segmentInfo.videoTimingInfo,audioTimingInfo:segmentInfo.audioTimingInfo})}if(this.updateAppendInitSegmentStatus(segmentInfo,result.type),this.updateSourceBufferTimestampOffset_(segmentInfo),segmentInfo.isSyncRequest){this.updateTimingInfoEnd_(segmentInfo),this.syncController_.saveSegmentTimingInfo({segmentInfo:segmentInfo,shouldSaveTimelineMapping:"main"===this.loaderType_});const next=this.chooseNextRequest_();if(next.mediaIndex!==segmentInfo.mediaIndex||next.partIndex!==segmentInfo.partIndex)return void this.logger_("sync segment was incorrect, not appending");this.logg
er_("sync segment was correct, appending")}segmentInfo.hasAppendedData_=!0,this.processMetadataQueue_(),this.appendData_(segmentInfo,result)}}updateAppendInitSegmentStatus(segmentInfo,type){"main"!==this.loaderType_||"number"!=typeof segmentInfo.timestampOffset||segmentInfo.changedTimestampOffset||(this.appendInitSegment_={audio:!0,video:!0}),this.playlistOfLastInitSegment_[type]!==segmentInfo.playlist&&(this.appendInitSegment_[type]=!0)}getInitSegmentAndUpdateState_(_ref68){let{type:type,initSegment:initSegment,map:map,playlist:playlist}=_ref68;if(map){const id=initSegmentId(map);if(this.activeInitSegmentId_===id)return null;initSegment=this.initSegmentForMap(map,!0).bytes,this.activeInitSegmentId_=id}return initSegment&&this.appendInitSegment_[type]?(this.playlistOfLastInitSegment_[type]=playlist,this.appendInitSegment_[type]=!1,this.activeInitSegmentId_=null,initSegment):null}handleQuotaExceededError_(_ref69,error){let{segmentInfo:segmentInfo,type:type,bytes:bytes}=_ref69;const audioBuffered=this.sourceUp
dater_.audioBuffered(),videoBuffered=this.sourceUpdater_.videoBuffered();audioBuffered.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+timeRangesToArray(audioBuffered).join(", ")),videoBuffered.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+timeRangesToArray(videoBuffered).join(", "));const audioBufferStart=audioBuffered.length?audioBuffered.start(0):0,audioBufferEnd=audioBuffered.length?audioBuffered.end(audioBuffered.length-1):0,videoBufferStart=videoBuffered.length?videoBuffered.start(0):0,videoBufferEnd=videoBuffered.length?videoBuffered.end(videoBuffered.length-1):0;if(audioBufferEnd-audioBufferStart<=1&&videoBufferEnd-videoBufferStart<=1)return this.logger_("On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. "+"Appended byte length: ".concat(bytes.byteLength,", ")+"audio buffer: ".concat(timeRangesToArray(audioBuffered).join(", "),", ")+"video buffer: ".concat(timeRangesToArray(videoBuffered).join(
", "),", ")),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),void this.trigger("error");this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:segmentInfo,type:type,bytes:bytes}));const timeToRemoveUntil=this.currentTime_()-1;this.logger_("On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ".concat(timeToRemoveUntil)),this.remove(0,timeToRemoveUntil,(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, retrying append in ".concat(1,"s")),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=window.setTimeout((()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()}),1e3)}),!0)}handleAppendError_(_ref70,error){let{segmentInfo:segmentInfo,type:type,bytes:bytes}=_ref70;error&&(22!==error.code?(this.logger_("Received non QUOTA_EXCEEDED_ERR on append",error),this.error("".concat(type," append of ").concat(bytes.length,"b failed for segmen
t ")+"#".concat(segmentInfo.mediaIndex," in playlist ").concat(segmentInfo.playlist.id)),this.trigger("appenderror")):this.handleQuotaExceededError_({segmentInfo:segmentInfo,type:type,bytes:bytes}))}appendToSourceBuffer_(_ref71){let{segmentInfo:segmentInfo,type:type,initSegment:initSegment,data:data,bytes:bytes}=_ref71;if(!bytes){const segments=[data];let byteLength=data.byteLength;initSegment&&(segments.unshift(initSegment),byteLength+=initSegment.byteLength),bytes=(segmentObj=>{let tempBuffer,offset=0;return segmentObj.bytes&&(tempBuffer=new Uint8Array(segmentObj.bytes),segmentObj.segments.forEach((segment=>{tempBuffer.set(segment,offset),offset+=segment.byteLength}))),tempBuffer})({bytes:byteLength,segments:segments})}this.sourceUpdater_.appendBuffer({segmentInfo:segmentInfo,type:type,bytes:bytes},this.handleAppendError_.bind(this,{segmentInfo:segmentInfo,type:type,bytes:bytes}))}handleSegmentTimingInfo_(type,requestId,segmentTimingInfo){if(!this.pendingSegment_||requestId!==this.pendingSegment_.requestId
)return;const segment=this.pendingSegment_.segment,timingInfoProperty="".concat(type,"TimingInfo");segment[timingInfoProperty]||(segment[timingInfoProperty]={}),segment[timingInfoProperty].transmuxerPrependedSeconds=segmentTimingInfo.prependedContentDuration||0,segment[timingInfoProperty].transmuxedPresentationStart=segmentTimingInfo.start.presentation,segment[timingInfoProperty].transmuxedDecodeStart=segmentTimingInfo.start.decode,segment[timingInfoProperty].transmuxedPresentationEnd=segmentTimingInfo.end.presentation,segment[timingInfoProperty].transmuxedDecodeEnd=segmentTimingInfo.end.decode,segment[timingInfoProperty].baseMediaDecodeTime=segmentTimingInfo.baseMediaDecodeTime}appendData_(segmentInfo,result){const{type:type,data:data}=result;if(!data||!data.byteLength)return;if("audio"===type&&this.audioDisabled_)return;const initSegment=this.getInitSegmentAndUpdateState_({type:type,initSegment:result.initSegment,playlist:segmentInfo.playlist,map:segmentInfo.isFmp4?segmentInfo.segment.map:null});this.appen
dToSourceBuffer_({segmentInfo:segmentInfo,type:type,initSegment:initSegment,data:data})}loadSegment_(segmentInfo){this.state="WAITING",this.pendingSegment_=segmentInfo,this.trimBackBuffer_(segmentInfo),"number"==typeof segmentInfo.timestampOffset&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.hasEnoughInfoToLoad_()?this.updateTransmuxerAndRequestSegment_(segmentInfo):this.loadQueue_.push((()=>{const options=_extends$1({},segmentInfo,{forceTimestampOffset:!0});_extends$1(segmentInfo,this.generateSegmentInfo_(options)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(segmentInfo)}))}updateTransmuxerAndRequestSegment_(segmentInfo){this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)&&(this.gopBuffer_.length=0,segmentInfo.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:segmentInfo.timestampOffset}));const simpleSegment=t
his.createSimplifiedSegmentObj_(segmentInfo),isEndOfStream=this.isEndOfStream_(segmentInfo.mediaIndex,segmentInfo.playlist,segmentInfo.partIndex),isWalkingForward=null!==this.mediaIndex,isDiscontinuity=segmentInfo.timeline!==this.currentTimeline_&&segmentInfo.timeline>0,isEndOfTimeline=isEndOfStream||isWalkingForward&&isDiscontinuity;this.logger_("Requesting ".concat(segmentInfoString(segmentInfo))),simpleSegment.map&&!simpleSegment.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),segmentInfo.abortRequests=mediaSegmentRequest({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:simpleSegment,abortFn:this.handleAbort_.bind(this,segmentInfo),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",segmentInfo.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_
.bind(this,"audio",segmentInfo.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:isEndOfTimeline,endedTimelineFn:()=>{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:_ref72=>{let{message:message,level:level,stream:stream}=_ref72;this.logger_("".concat(segmentInfoString(segmentInfo)," logged from transmuxer stream ").concat(stream," as a ").concat(level,": ").concat(message))}})}trimBackBuffer_(segmentInfo){const removeToTime=((seekable,currentTime,targetDuration)=>{let trimTime=currentTime-Config.BACK_BUFFER_LENGTH;seekable.length&&(trimTime=Math.max(trimTime,seekable.start(0)));const maxTrimTime=currentTime-targetDuration;return Math.min(maxTrimTime,trimTime)})(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);removeToTime>0&&this.remove(0,removeToTime)}createSimplifiedSegmentObj_(segmentInfo){const segment=segmentInfo.segment,part=segm
entInfo.part,simpleSegment={resolvedUri:part?part.resolvedUri:segment.resolvedUri,byterange:part?part.byterange:segment.byterange,requestId:segmentInfo.requestId,transmuxer:segmentInfo.transmuxer,audioAppendStart:segmentInfo.audioAppendStart,gopsToAlignWith:segmentInfo.gopsToAlignWith,part:segmentInfo.part},previousSegment=segmentInfo.playlist.segments[segmentInfo.mediaIndex-1];if(previousSegment&&previousSegment.timeline===segment.timeline&&(previousSegment.videoTimingInfo?simpleSegment.baseStartTime=previousSegment.videoTimingInfo.transmuxedDecodeEnd:previousSegment.audioTimingInfo&&(simpleSegment.baseStartTime=previousSegment.audioTimingInfo.transmuxedDecodeEnd)),segment.key){const iv=segment.key.iv||new Uint32Array([0,0,0,segmentInfo.mediaIndex+segmentInfo.playlist.mediaSequence]);simpleSegment.key=this.segmentKey(segment.key),simpleSegment.key.iv=iv}return segment.map&&(simpleSegment.map=this.initSegmentForMap(segment.map)),simpleSegment}saveTransferStats_(stats){this.mediaRequests+=1,stats&&(this.media
BytesTransferred+=stats.bytesReceived,this.mediaTransferDuration+=stats.roundTripTime)}saveBandwidthRelatedStats_(duration,stats){this.pendingSegment_.byteLength=stats.bytesReceived,duration<.016666666666666666?this.logger_("Ignoring segment's bandwidth because its duration of ".concat(duration)+" is less than the min to record ".concat(.016666666666666666)):(this.bandwidth=stats.bandwidth,this.roundTrip=stats.roundTripTime)}handleTimeout_(){this.mediaRequestsTimedout+=1,this.bandwidth=1,this.roundTrip=NaN,this.trigger("bandwidthupdate"),this.trigger("timeout")}segmentRequestFinished_(error,simpleSegment,result){if(this.callQueue_.length)return void this.callQueue_.push(this.segmentRequestFinished_.bind(this,error,simpleSegment,result));if(this.saveTransferStats_(simpleSegment.stats),!this.pendingSegment_)return;if(simpleSegment.requestId!==this.pendingSegment_.requestId)return;if(error){if(this.pendingSegment_=null,this.state="READY",error.code===REQUEST_ERRORS_ABORTED)return;return this.pause(),error.code=
==REQUEST_ERRORS_TIMEOUT?void this.handleTimeout_():(this.mediaRequestsErrored+=1,this.error(error),void this.trigger("error"))}const segmentInfo=this.pendingSegment_;this.saveBandwidthRelatedStats_(segmentInfo.duration,simpleSegment.stats),segmentInfo.endOfAllRequests=simpleSegment.endOfAllRequests,result.gopInfo&&(this.gopBuffer_=((buffer,gops,replace)=>{if(!gops.length)return buffer;if(replace)return gops.slice();const start=gops[0].pts;let i=0;for(;i<buffer.length&&!(buffer[i].pts>=start);i++);return buffer.slice(0,i).concat(gops)})(this.gopBuffer_,result.gopInfo,this.safeAppend_)),this.state="APPENDING",this.trigger("appending"),this.waitForAppendsToComplete_(segmentInfo)}setTimeMapping_(timeline){const timelineMapping=this.syncController_.mappingForTimeline(timeline);null!==timelineMapping&&(this.timeMapping_=timelineMapping)}updateMediaSecondsLoaded_(segment){"number"==typeof segment.start&&"number"==typeof segment.end?this.mediaSecondsLoaded+=segment.end-segment.start:this.mediaSecondsLoaded+=segment
.duration}shouldUpdateTransmuxerTimestampOffset_(timestampOffset){return null!==timestampOffset&&("main"===this.loaderType_&×tampOffset!==this.sourceUpdater_.videoTimestampOffset()||!this.audioDisabled_&×tampOffset!==this.sourceUpdater_.audioTimestampOffset())}trueSegmentStart_(_ref73){let{currentStart:currentStart,playlist:playlist,mediaIndex:mediaIndex,firstVideoFrameTimeForData:firstVideoFrameTimeForData,currentVideoTimestampOffset:currentVideoTimestampOffset,useVideoTimingInfo:useVideoTimingInfo,videoTimingInfo:videoTimingInfo,audioTimingInfo:audioTimingInfo}=_ref73;if(void 0!==currentStart)return currentStart;if(!useVideoTimingInfo)return audioTimingInfo.start;const previousSegment=playlist.segments[mediaIndex-1];return 0!==mediaIndex&&previousSegment&&void 0!==previousSegment.start&&previousSegment.end===firstVideoFrameTimeForData+currentVideoTimestampOffset?videoTimingInfo.start:firstVideoFrameTimeForData}waitForAppendsToComplete_(segmentInfo){const trackInfo=this.getCurrentMediaInfo_(segmen
tInfo);if(!trackInfo)return this.error({message:"No starting media returned, likely due to an unsupported media format.",playlistExclusionDuration:1/0}),void this.trigger("error");const{hasAudio:hasAudio,hasVideo:hasVideo,isMuxed:isMuxed}=trackInfo,waitForVideo="main"===this.loaderType_&&hasVideo,waitForAudio=!this.audioDisabled_&&hasAudio&&!isMuxed;if(segmentInfo.waitingOnAppends=0,!segmentInfo.hasAppendedData_)return segmentInfo.timingInfo||"number"!=typeof segmentInfo.timestampOffset||(this.isPendingTimestampOffset_=!0),segmentInfo.timingInfo={start:0},segmentInfo.waitingOnAppends++,this.isPendingTimestampOffset_||(this.updateSourceBufferTimestampOffset_(segmentInfo),this.processMetadataQueue_()),void this.checkAppendsDone_(segmentInfo);waitForVideo&&segmentInfo.waitingOnAppends++,waitForAudio&&segmentInfo.waitingOnAppends++,waitForVideo&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,segmentInfo)),waitForAudio&&this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(th
is,segmentInfo))}checkAppendsDone_(segmentInfo){this.checkForAbort_(segmentInfo.requestId)||(segmentInfo.waitingOnAppends--,0===segmentInfo.waitingOnAppends&&this.handleAppendsDone_())}checkForIllegalMediaSwitch(trackInfo){const illegalMediaSwitchError=((loaderType,startingMedia,trackInfo)=>"main"===loaderType&&startingMedia&&trackInfo?trackInfo.hasAudio||trackInfo.hasVideo?startingMedia.hasVideo&&!trackInfo.hasVideo?"Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.":!startingMedia.hasVideo&&trackInfo.hasVideo?"Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.":null:"Neither audio nor video found in segment.":null)(this.loaderType_,this.getCurrentMediaInfo_(),trackInfo);return!!illegalMediaSwitchError&&(this.error({message:illegalMedi
aSwitchError,playlistExclusionDuration:1/0}),this.trigger("error"),!0)}updateSourceBufferTimestampOffset_(segmentInfo){if(null===segmentInfo.timestampOffset||"number"!=typeof segmentInfo.timingInfo.start||segmentInfo.changedTimestampOffset||"main"!==this.loaderType_)return;let didChange=!1;segmentInfo.timestampOffset-=this.getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:segmentInfo.segment.videoTimingInfo,audioTimingInfo:segmentInfo.segment.audioTimingInfo,timingInfo:segmentInfo.timingInfo}),segmentInfo.changedTimestampOffset=!0,segmentInfo.timestampOffset!==this.sourceUpdater_.videoTimestampOffset()&&(this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset),didChange=!0),segmentInfo.timestampOffset!==this.sourceUpdater_.audioTimestampOffset()&&(this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset),didChange=!0),didChange&&this.trigger("timestampoffset")}getSegmentStartTimeForTimestampOffsetCalculation_(_ref74){let{videoTimingInfo:videoTimingInfo,audioTimingInf
o:audioTimingInfo,timingInfo:timingInfo}=_ref74;return this.useDtsForTimestampOffset_?videoTimingInfo&&"number"==typeof videoTimingInfo.transmuxedDecodeStart?videoTimingInfo.transmuxedDecodeStart:audioTimingInfo&&"number"==typeof audioTimingInfo.transmuxedDecodeStart?audioTimingInfo.transmuxedDecodeStart:timingInfo.start:timingInfo.start}updateTimingInfoEnd_(segmentInfo){segmentInfo.timingInfo=segmentInfo.timingInfo||{};const trackInfo=this.getMediaInfo_(),prioritizedTimingInfo="main"===this.loaderType_&&trackInfo&&trackInfo.hasVideo&&segmentInfo.videoTimingInfo?segmentInfo.videoTimingInfo:segmentInfo.audioTimingInfo;prioritizedTimingInfo&&(segmentInfo.timingInfo.end="number"==typeof prioritizedTimingInfo.end?prioritizedTimingInfo.end:prioritizedTimingInfo.start+segmentInfo.duration)}handleAppendsDone_(){if(this.pendingSegment_&&this.trigger("appendsdone"),!this.pendingSegment_)return this.state="READY",void(this.paused()||this.monitorBuffer_());const segmentInfo=this.pendingSegment_;this.updateTimingInfoEnd
_(segmentInfo),this.shouldSaveSegmentTimingInfo_&&this.syncController_.saveSegmentTimingInfo({segmentInfo:segmentInfo,shouldSaveTimelineMapping:"main"===this.loaderType_});const segmentDurationMessage=getTroublesomeSegmentDurationMessage(segmentInfo,this.sourceType_);if(segmentDurationMessage&&("warn"===segmentDurationMessage.severity?videojs.log.warn(segmentDurationMessage.message):this.logger_(segmentDurationMessage.message)),this.recordThroughput_(segmentInfo),this.pendingSegment_=null,this.state="READY",segmentInfo.isSyncRequest&&(this.trigger("syncinfoupdate"),!segmentInfo.hasAppendedData_))return void this.logger_("Throwing away un-appended sync request ".concat(segmentInfoString(segmentInfo)));this.logger_("Appended ".concat(segmentInfoString(segmentInfo))),this.addSegmentMetadataCue_(segmentInfo),this.fetchAtBuffer_=!0,this.currentTimeline_!==segmentInfo.timeline&&(this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:segmentInfo.timeline}),"main"!==th
is.loaderType_||this.audioDisabled_||this.timelineChangeController_.lastTimelineChange({type:"audio",from:this.currentTimeline_,to:segmentInfo.timeline})),this.currentTimeline_=segmentInfo.timeline,this.trigger("syncinfoupdate");const segment=segmentInfo.segment,part=segmentInfo.part,badSegmentGuess=segment.end&&this.currentTime_()-segment.end>3*segmentInfo.playlist.targetDuration,badPartGuess=part&&part.end&&this.currentTime_()-part.end>3*segmentInfo.playlist.partTargetDuration;if(badSegmentGuess||badPartGuess)return this.logger_("bad ".concat(badSegmentGuess?"segment":"part"," ").concat(segmentInfoString(segmentInfo))),void this.resetEverything();null!==this.mediaIndex&&this.trigger("bandwidthupdate"),this.trigger("progress"),this.mediaIndex=segmentInfo.mediaIndex,this.partIndex=segmentInfo.partIndex,this.isEndOfStream_(segmentInfo.mediaIndex,segmentInfo.playlist,segmentInfo.partIndex)&&this.endOfStream(),this.trigger("appended"),segmentInfo.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitor
Buffer_()}recordThroughput_(segmentInfo){if(segmentInfo.duration<.016666666666666666)return void this.logger_("Ignoring segment's throughput because its duration of ".concat(segmentInfo.duration)+" is less than the min to record ".concat(.016666666666666666));const rate=this.throughput.rate,segmentProcessingTime=Date.now()-segmentInfo.endOfAllRequests+1,segmentProcessingThroughput=Math.floor(segmentInfo.byteLength/segmentProcessingTime*8*1e3);this.throughput.rate+=(segmentProcessingThroughput-rate)/++this.throughput.count}addSegmentMetadataCue_(segmentInfo){if(!this.segmentMetadataTrack_)return;const segment=segmentInfo.segment,start=segment.start,end=segment.end;if(!finite(start)||!finite(end))return;removeCuesFromTrack(start,end,this.segmentMetadataTrack_);const Cue=window.WebKitDataCue||window.VTTCue,value={custom:segment.custom,dateTimeObject:segment.dateTimeObject,dateTimeString:segment.dateTimeString,programDateTime:segment.programDateTime,bandwidth:segmentInfo.playlist.attributes.BANDWIDTH,resolution:
segmentInfo.playlist.attributes.RESOLUTION,codecs:segmentInfo.playlist.attributes.CODECS,byteLength:segmentInfo.byteLength,uri:segmentInfo.uri,timeline:segmentInfo.timeline,playlist:segmentInfo.playlist.id,start:start,end:end},cue=new Cue(start,end,JSON.stringify(value));cue.value=value,this.segmentMetadataTrack_.addCue(cue)}}function noop(){}const toTitleCase=function(string){return"string"!=typeof string?string:string.replace(/./,(w=>w.toUpperCase()))},bufferTypes=["video","audio"],updating=(type,sourceUpdater)=>{const sourceBuffer=sourceUpdater["".concat(type,"Buffer")];return sourceBuffer&&sourceBuffer.updating||sourceUpdater.queuePending[type]},shiftQueue=(type,sourceUpdater)=>{if(0===sourceUpdater.queue.length)return;let queueIndex=0,queueEntry=sourceUpdater.queue[queueIndex];if("mediaSource"!==queueEntry.type){if("mediaSource"!==type&&sourceUpdater.ready()&&"closed"!==sourceUpdater.mediaSource.readyState&&!updating(type,sourceUpdater)){if(queueEntry.type!==type){if(queueIndex=((type,queue)=>{for(let i
=0;i<queue.length;i++){const queueEntry=queue[i];if("mediaSource"===queueEntry.type)return null;if(queueEntry.type===type)return i}return null})(type,sourceUpdater.queue),null===queueIndex)return;queueEntry=sourceUpdater.queue[queueIndex]}return sourceUpdater.queue.splice(queueIndex,1),sourceUpdater.queuePending[type]=queueEntry,queueEntry.action(type,sourceUpdater),queueEntry.doneFn?void 0:(sourceUpdater.queuePending[type]=null,void shiftQueue(type,sourceUpdater))}}else sourceUpdater.updating()||"closed"===sourceUpdater.mediaSource.readyState||(sourceUpdater.queue.shift(),queueEntry.action(sourceUpdater),queueEntry.doneFn&&queueEntry.doneFn(),shiftQueue("audio",sourceUpdater),shiftQueue("video",sourceUpdater))},cleanupBuffer=(type,sourceUpdater)=>{const buffer=sourceUpdater["".concat(type,"Buffer")],titleType=toTitleCase(type);buffer&&(buffer.removeEventListener("updateend",sourceUpdater["on".concat(titleType,"UpdateEnd_")]),buffer.removeEventListener("error",sourceUpdater["on".concat(titleType,"Error_")]),
sourceUpdater.codecs[type]=null,sourceUpdater["".concat(type,"Buffer")]=null)},inSourceBuffers=(mediaSource,sourceBuffer)=>mediaSource&&sourceBuffer&&-1!==Array.prototype.indexOf.call(mediaSource.sourceBuffers,sourceBuffer),actions_appendBuffer=(bytes,segmentInfo,onError)=>(type,sourceUpdater)=>{const sourceBuffer=sourceUpdater["".concat(type,"Buffer")];if(inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)){sourceUpdater.logger_("Appending segment ".concat(segmentInfo.mediaIndex,"'s ").concat(bytes.length," bytes to ").concat(type,"Buffer"));try{sourceBuffer.appendBuffer(bytes)}catch(e){sourceUpdater.logger_("Error with code ".concat(e.code," ")+(22===e.code?"(QUOTA_EXCEEDED_ERR) ":"")+"when appending segment ".concat(segmentInfo.mediaIndex," to ").concat(type,"Buffer")),sourceUpdater.queuePending[type]=null,onError(e)}}},actions_remove=(start,end)=>(type,sourceUpdater)=>{const sourceBuffer=sourceUpdater["".concat(type,"Buffer")];if(inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)){sourceUpdater.
logger_("Removing ".concat(start," to ").concat(end," from ").concat(type,"Buffer"));try{sourceBuffer.remove(start,end)}catch(e){sourceUpdater.logger_("Remove ".concat(start," to ").concat(end," from ").concat(type,"Buffer failed"))}}},actions_timestampOffset=offset=>(type,sourceUpdater)=>{const sourceBuffer=sourceUpdater["".concat(type,"Buffer")];inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)&&(sourceUpdater.logger_("Setting ".concat(type,"timestampOffset to ").concat(offset)),sourceBuffer.timestampOffset=offset)},actions_callback=callback=>(type,sourceUpdater)=>{callback()},actions_endOfStream=error=>sourceUpdater=>{if("open"===sourceUpdater.mediaSource.readyState){sourceUpdater.logger_("Calling mediaSource endOfStream(".concat(error||"",")"));try{sourceUpdater.mediaSource.endOfStream(error)}catch(e){videojs.log.warn("Failed to call media source endOfStream",e)}}},actions_duration=duration=>sourceUpdater=>{sourceUpdater.logger_("Setting mediaSource duration to ".concat(duration));try{sourceUpdater
.mediaSource.duration=duration}catch(e){videojs.log.warn("Failed to set media source duration",e)}},actions_abort=()=>(type,sourceUpdater)=>{if("open"!==sourceUpdater.mediaSource.readyState)return;const sourceBuffer=sourceUpdater["".concat(type,"Buffer")];if(inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)){sourceUpdater.logger_("calling abort on ".concat(type,"Buffer"));try{sourceBuffer.abort()}catch(e){videojs.log.warn("Failed to abort on ".concat(type,"Buffer"),e)}}},actions_addSourceBuffer=(type,codec)=>sourceUpdater=>{const titleType=toTitleCase(type),mime=getMimeForCodec(codec);sourceUpdater.logger_("Adding ".concat(type,"Buffer with codec ").concat(codec," to mediaSource"));const sourceBuffer=sourceUpdater.mediaSource.addSourceBuffer(mime);sourceBuffer.addEventListener("updateend",sourceUpdater["on".concat(titleType,"UpdateEnd_")]),sourceBuffer.addEventListener("error",sourceUpdater["on".concat(titleType,"Error_")]),sourceUpdater.codecs[type]=codec,sourceUpdater["".concat(type,"Buffer")]=source
Buffer},actions_removeSourceBuffer=type=>sourceUpdater=>{const sourceBuffer=sourceUpdater["".concat(type,"Buffer")];if(cleanupBuffer(type,sourceUpdater),inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)){sourceUpdater.logger_("Removing ".concat(type,"Buffer with codec ").concat(sourceUpdater.codecs[type]," from mediaSource"));try{sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer)}catch(e){videojs.log.warn("Failed to removeSourceBuffer ".concat(type,"Buffer"),e)}}},actions_changeType=codec=>(type,sourceUpdater)=>{const sourceBuffer=sourceUpdater["".concat(type,"Buffer")],mime=getMimeForCodec(codec);if(inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)&&sourceUpdater.codecs[type]!==codec){sourceUpdater.logger_("changing ".concat(type,"Buffer codec from ").concat(sourceUpdater.codecs[type]," to ").concat(codec));try{sourceBuffer.changeType(mime),sourceUpdater.codecs[type]=codec}catch(e){videojs.log.warn("Failed to changeType on ".concat(type,"Buffer"),e)}}},pushQueue=_ref75=>{let{type:type,so
urceUpdater:sourceUpdater,action:action,doneFn:doneFn,name:name}=_ref75;sourceUpdater.queue.push({type:type,action:action,doneFn:doneFn,name:name}),shiftQueue(type,sourceUpdater)},onUpdateend=(type,sourceUpdater)=>e=>{if(sourceUpdater.queuePending[type]){const doneFn=sourceUpdater.queuePending[type].doneFn;sourceUpdater.queuePending[type]=null,doneFn&&doneFn(sourceUpdater["".concat(type,"Error_")])}shiftQueue(type,sourceUpdater)};class SourceUpdater extends videojs.EventTarget{constructor(mediaSource){super(),this.mediaSource=mediaSource,this.sourceopenListener_=()=>shiftQueue("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=logger("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=onUpdateend("video",this),this.onAudioUpdateEnd_=onUpdateend("audio",this),this.onVideoError_=e=>
{this.videoError_=e},this.onAudioError_=e=>{this.audioError_=e},this.createdSourceBuffers_=!1,this.initializedEme_=!1,this.triggeredReady_=!1}initializedEme(){this.initializedEme_=!0,this.triggerReady()}hasCreatedSourceBuffers(){return this.createdSourceBuffers_}hasInitializedAnyEme(){return this.initializedEme_}ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme()}createSourceBuffers(codecs){this.hasCreatedSourceBuffers()||(this.addOrChangeSourceBuffers(codecs),this.createdSourceBuffers_=!0,this.trigger("createdsourcebuffers"),this.triggerReady())}triggerReady(){this.ready()&&!this.triggeredReady_&&(this.triggeredReady_=!0,this.trigger("ready"))}addSourceBuffer(type,codec){pushQueue({type:"mediaSource",sourceUpdater:this,action:actions_addSourceBuffer(type,codec),name:"addSourceBuffer"})}abort(type){pushQueue({type:type,sourceUpdater:this,action:actions_abort(type),name:"abort"})}removeSourceBuffer(type){this.canRemoveSourceBuffer()?pushQueue({type:"mediaSource",sourceUpdater:this,actio
n:actions_removeSourceBuffer(type),name:"removeSourceBuffer"}):videojs.log.error("removeSourceBuffer is not supported!")}canRemoveSourceBuffer(){return!videojs.browser.IS_FIREFOX&&window.MediaSource&&window.MediaSource.prototype&&"function"==typeof window.MediaSource.prototype.removeSourceBuffer}static canChangeType(){return window.SourceBuffer&&window.SourceBuffer.prototype&&"function"==typeof window.SourceBuffer.prototype.changeType}canChangeType(){return this.constructor.canChangeType()}changeType(type,codec){this.canChangeType()?pushQueue({type:type,sourceUpdater:this,action:actions_changeType(codec),name:"changeType"}):videojs.log.error("changeType is not supported!")}addOrChangeSourceBuffers(codecs){if(!codecs||"object"!=typeof codecs||0===Object.keys(codecs).length)throw new Error("Cannot addOrChangeSourceBuffers to undefined codecs");Object.keys(codecs).forEach((type=>{const codec=codecs[type];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(type,codec);this.canChangeType()&&this.change
Type(type,codec)}))}appendBuffer(options,doneFn){const{segmentInfo:segmentInfo,type:type,bytes:bytes}=options;if(this.processedAppend_=!0,"audio"===type&&this.videoBuffer&&!this.videoAppendQueued_)return this.delayedAudioAppendQueue_.push([options,doneFn]),void this.logger_("delayed audio append of ".concat(bytes.length," until video append"));if(pushQueue({type:type,sourceUpdater:this,action:actions_appendBuffer(bytes,segmentInfo||{mediaIndex:-1},doneFn),doneFn:doneFn,name:"appendBuffer"}),"video"===type){if(this.videoAppendQueued_=!0,!this.delayedAudioAppendQueue_.length)return;const queue=this.delayedAudioAppendQueue_.slice();this.logger_("queuing delayed audio ".concat(queue.length," appendBuffers")),this.delayedAudioAppendQueue_.length=0,queue.forEach((que=>{this.appendBuffer.apply(this,que)}))}}audioBuffered(){return inSourceBuffers(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:createTimeRanges()}videoBuffered(){return inSourceBuffers(this.mediaSource,this.vide
oBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:createTimeRanges()}buffered(){const video=inSourceBuffers(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,audio=inSourceBuffers(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return audio&&!video?this.audioBuffered():video&&!audio?this.videoBuffered():function(bufferA,bufferB){let start=null,end=null,arity=0;const extents=[],ranges=[];if(!(bufferA&&bufferA.length&&bufferB&&bufferB.length))return createTimeRanges();let count=bufferA.length;for(;count--;)extents.push({time:bufferA.start(count),type:"start"}),extents.push({time:bufferA.end(count),type:"end"});for(count=bufferB.length;count--;)extents.push({time:bufferB.start(count),type:"start"}),extents.push({time:bufferB.end(count),type:"end"});for(extents.sort((function(a,b){return a.time-b.time})),count=0;count<extents.length;count++)"start"===extents[count].type?(arity++,2===arity&&(start=extents[count].time)):"end"===extents[count].type&&(arity--,1===arity&&(end=extents[count
].time)),null!==start&&null!==end&&(ranges.push([start,end]),start=null,end=null);return createTimeRanges(ranges)}(this.audioBuffered(),this.videoBuffered())}setDuration(duration){let doneFn=arguments.length>1&&void 0!==arguments[1]?arguments[1]:noop;pushQueue({type:"mediaSource",sourceUpdater:this,action:actions_duration(duration),name:"duration",doneFn:doneFn})}endOfStream(){let error=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,doneFn=arguments.length>1&&void 0!==arguments[1]?arguments[1]:noop;"string"!=typeof error&&(error=void 0),pushQueue({type:"mediaSource",sourceUpdater:this,action:actions_endOfStream(error),name:"endOfStream",doneFn:doneFn})}removeAudio(start,end){let done=arguments.length>2&&void 0!==arguments[2]?arguments[2]:noop;this.audioBuffered().length&&0!==this.audioBuffered().end(0)?pushQueue({type:"audio",sourceUpdater:this,action:actions_remove(start,end),doneFn:done,name:"remove"}):done()}removeVideo(start,end){let done=arguments.length>2&&void 0!==arguments[2]?arguments[2
]:noop;this.videoBuffered().length&&0!==this.videoBuffered().end(0)?pushQueue({type:"video",sourceUpdater:this,action:actions_remove(start,end),doneFn:done,name:"remove"}):done()}updating(){return!(!updating("audio",this)&&!updating("video",this))}audioTimestampOffset(offset){return void 0!==offset&&this.audioBuffer&&this.audioTimestampOffset_!==offset&&(pushQueue({type:"audio",sourceUpdater:this,action:actions_timestampOffset(offset),name:"timestampOffset"}),this.audioTimestampOffset_=offset),this.audioTimestampOffset_}videoTimestampOffset(offset){return void 0!==offset&&this.videoBuffer&&this.videoTimestampOffset!==offset&&(pushQueue({type:"video",sourceUpdater:this,action:actions_timestampOffset(offset),name:"timestampOffset"}),this.videoTimestampOffset_=offset),this.videoTimestampOffset_}audioQueueCallback(callback){this.audioBuffer&&pushQueue({type:"audio",sourceUpdater:this,action:actions_callback(callback),name:"callback"})}videoQueueCallback(callback){this.videoBuffer&&pushQueue({type:"video",sourceU
pdater:this,action:actions_callback(callback),name:"callback"})}dispose(){this.trigger("dispose"),bufferTypes.forEach((type=>{this.abort(type),this.canRemoveSourceBuffer()?this.removeSourceBuffer(type):this["".concat(type,"QueueCallback")]((()=>cleanupBuffer(type,this)))})),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const uint8ToUtf8=uintArray=>decodeURIComponent(escape(String.fromCharCode.apply(null,uintArray))),VTT_LINE_TERMINATORS=new Uint8Array("\n\n".split("").map((char=>char.charCodeAt(0))));class NoVttJsError extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class VTTSegmentLoader extends SegmentLoader{constructor(settings){super(settings,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}),this.mediaSource_=null,this.subtitlesTrack_=null,this.loaderType_="subtitle",this.featuresNativeTe
xtTracks_=settings.featuresNativeTextTracks,this.loadVttJs=settings.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}createTransmuxer_(){return null}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return createTimeRanges();const cues=this.subtitlesTrack_.cues;return createTimeRanges([[cues[0].startTime,cues[cues.length-1].startTime]])}initSegmentForMap(map){let set=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!map)return null;const id=initSegmentId(map);let storedMap=this.initSegments_[id];if(set&&!storedMap&&map.bytes){const combinedByteLength=VTT_LINE_TERMINATORS.byteLength+map.bytes.byteLength,combinedSegment=new Uint8Array(combinedByteLength);combinedSegment.set(map.bytes),combinedSegment.set(VTT_LINE_TERMINATORS,map.bytes.byteLength),this.initSegments_[id]=storedMap={resolvedUri:map.resolvedUri,byterange:map.byterange,bytes:combinedSegment}}return storedMap||map}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused(
)}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}track(track){return void 0===track||(this.subtitlesTrack_=track,"INIT"===this.state&&this.couldBeginLoading_()&&this.init_()),this.subtitlesTrack_}remove(start,end){removeCuesFromTrack(start,end,this.subtitlesTrack_)}fillBuffer_(){const segmentInfo=this.chooseNextRequest_();if(segmentInfo){if(null===this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline)){const checkTimestampOffset=()=>{this.state="READY",this.paused()||this.monitorBuffer_()};return this.syncController_.one("timestampoffset",checkTimestampOffset),void(this.state="WAITING_ON_TIMELINE")}this.loadSegment_(segmentInfo)}}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(segmentInfo){for(;segmentInfo&&segmentInfo.segment.empty;){if(segmentInfo.mediaIndex+1>=segmentInfo.playlist.segments.length){segmentInfo=null;break}segmentInfo=this.generateSegmentInfo_({playlist:s
egmentInfo.playlist,mediaIndex:segmentInfo.mediaIndex+1,startOfSegment:segmentInfo.startOfSegment+segmentInfo.duration,isSyncRequest:segmentInfo.isSyncRequest})}return segmentInfo}stopForError(error){this.error(error),this.state="READY",this.pause(),this.trigger("error")}segmentRequestFinished_(error,simpleSegment,result){if(!this.subtitlesTrack_)return void(this.state="READY");if(this.saveTransferStats_(simpleSegment.stats),!this.pendingSegment_)return this.state="READY",void(this.mediaRequestsAborted+=1);if(error)return error.code===REQUEST_ERRORS_TIMEOUT&&this.handleTimeout_(),error.code===REQUEST_ERRORS_ABORTED?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,void this.stopForError(error);const segmentInfo=this.pendingSegment_;this.saveBandwidthRelatedStats_(segmentInfo.duration,simpleSegment.stats),simpleSegment.key&&this.segmentKey(simpleSegment.key,!0),this.state="APPENDING",this.trigger("appending");const segment=segmentInfo.segment;if(segment.map&&(segment.map.bytes=simpleSegment.map.bytes)
,segmentInfo.bytes=simpleSegment.bytes,"function"!=typeof window.WebVTT&&"function"==typeof this.loadVttJs)return this.state="WAITING_ON_VTTJS",void this.loadVttJs().then((()=>this.segmentRequestFinished_(error,simpleSegment,result)),(()=>this.stopForError({message:"Error loading vtt.js"})));segment.requested=!0;try{this.parseVTTCues_(segmentInfo)}catch(e){return void this.stopForError({message:e.message})}if(this.updateTimeMapping_(segmentInfo,this.syncController_.timelines[segmentInfo.timeline],this.playlist_),segmentInfo.cues.length?segmentInfo.timingInfo={start:segmentInfo.cues[0].startTime,end:segmentInfo.cues[segmentInfo.cues.length-1].endTime}:segmentInfo.timingInfo={start:segmentInfo.startOfSegment,end:segmentInfo.startOfSegment+segmentInfo.duration},segmentInfo.isSyncRequest)return this.trigger("syncinfoupdate"),this.pendingSegment_=null,void(this.state="READY");segmentInfo.byteLength=segmentInfo.bytes.byteLength,this.mediaSecondsLoaded+=segment.duration,segmentInfo.cues.forEach((cue=>{this.subtitle
sTrack_.addCue(this.featuresNativeTextTracks_?new window.VTTCue(cue.startTime,cue.endTime,cue.text):cue)})),function(track){const cues=track.cues;if(!cues)return;const uniqueCues={};for(let i=cues.length-1;i>=0;i--){const cue=cues[i],cueKey="".concat(cue.startTime,"-").concat(cue.endTime,"-").concat(cue.text);uniqueCues[cueKey]?track.removeCue(cue):uniqueCues[cueKey]=cue}}(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(){}updateTimingInfoEnd_(){}parseVTTCues_(segmentInfo){let decoder,decodeBytesToString=!1;if("function"!=typeof window.WebVTT)throw new NoVttJsError;"function"==typeof window.TextDecoder?decoder=new window.TextDecoder("utf8"):(decoder=window.WebVTT.StringDecoder(),decodeBytesToString=!0);const parser=new window.WebVTT.Parser(window,window.vttjs,decoder);if(segmentInfo.cues=[],segmentInfo.timestampmap={MPEGTS:0,LOCAL:0},parser.oncue=segmentInfo.cues.push.bind(segmentInfo.cues),parser.ontimestampmap=map=>{segmentInfo.timestampmap=map},parser.onparsingerror=error=>{videojs.log.warn("E
rror encountered when parsing cues: "+error.message)},segmentInfo.segment.map){let mapData=segmentInfo.segment.map.bytes;decodeBytesToString&&(mapData=uint8ToUtf8(mapData)),parser.parse(mapData)}let segmentData=segmentInfo.bytes;decodeBytesToString&&(segmentData=uint8ToUtf8(segmentData)),parser.parse(segmentData),parser.flush()}updateTimeMapping_(segmentInfo,mappingObj,playlist){const segment=segmentInfo.segment;if(!mappingObj)return;if(!segmentInfo.cues.length)return void(segment.empty=!0);const{MPEGTS:MPEGTS,LOCAL:LOCAL}=segmentInfo.timestampmap,diff=MPEGTS/clock_1-LOCAL+mappingObj.mapping;if(segmentInfo.cues.forEach((cue=>{const duration=cue.endTime-cue.startTime,startTime=0===MPEGTS?cue.startTime+diff:this.handleRollover_(cue.startTime+diff,mappingObj.time);cue.startTime=Math.max(startTime,0),cue.endTime=Math.max(startTime+duration,0)})),!playlist.syncInfo){const firstStart=segmentInfo.cues[0].startTime,lastStart=segmentInfo.cues[segmentInfo.cues.length-1].startTime;playlist.syncInfo={mediaSequence:playl
ist.mediaSequence+segmentInfo.mediaIndex,time:Math.min(firstStart,lastStart-segment.duration)}}}handleRollover_(value,reference){if(null===reference)return value;let valueIn90khz=value*clock_1;const referenceIn90khz=reference*clock_1;let offset;for(offset=referenceIn90khz<valueIn90khz?-8589934592:8589934592;Math.abs(valueIn90khz-referenceIn90khz)>4294967296;)valueIn90khz+=offset;return valueIn90khz/clock_1}}const findAdCue=function(track,mediaTime){const cues=track.cues;for(let i=0;i<cues.length;i++){const cue=cues[i];if(mediaTime>=cue.adStartTime&&mediaTime<=cue.adEndTime)return cue}return null},syncPointStrategies=[{name:"VOD",run:(syncController,playlist,duration,currentTimeline,currentTime)=>{if(duration!==1/0){return{time:0,segmentIndex:0,partIndex:null}}return null}},{name:"MediaSequence",run:(syncController,playlist,duration,currentTimeline,currentTime,type)=>{if(!type)return null;const mediaSequenceMap=syncController.getMediaSequenceMap(type);if(!mediaSequenceMap||0===mediaSequenceMap.size)return nul
l;if(void 0===playlist.mediaSequence||!Array.isArray(playlist.segments)||!playlist.segments.length)return null;let currentMediaSequence=playlist.mediaSequence,segmentIndex=0;for(const segment of playlist.segments){const range=mediaSequenceMap.get(currentMediaSequence);if(!range)break;if(currentTime>=range.start&¤tTime<range.end){if(Array.isArray(segment.parts)&&segment.parts.length){let currentPartStart=range.start,partIndex=0;for(const part of segment.parts){const start=currentPartStart,end=start+part.duration;if(currentTime>=start&¤tTime<end)return{time:range.start,segmentIndex:segmentIndex,partIndex:partIndex};partIndex++,currentPartStart=end}}return{time:range.start,segmentIndex:segmentIndex,partIndex:null}}segmentIndex++,currentMediaSequence++}return null}},{name:"ProgramDateTime",run:(syncController,playlist,duration,currentTimeline,currentTime)=>{if(!Object.keys(syncController.timelineToDatetimeMappings).length)return null;let syncPoint=null,lastDistance=null;const partsAndSegments=getPart
sAndSegments(playlist);currentTime=currentTime||0;for(let i=0;i<partsAndSegments.length;i++){const partAndSegment=partsAndSegments[playlist.endList||0===currentTime?i:partsAndSegments.length-(i+1)],segment=partAndSegment.segment,datetimeMapping=syncController.timelineToDatetimeMappings[segment.timeline];if(!datetimeMapping||!segment.dateTimeObject)continue;let start=segment.dateTimeObject.getTime()/1e3+datetimeMapping;if(segment.parts&&"number"==typeof partAndSegment.partIndex)for(let z=0;z<partAndSegment.partIndex;z++)start+=segment.parts[z].duration;const distance=Math.abs(currentTime-start);if(null!==lastDistance&&(0===distance||lastDistance<distance))break;lastDistance=distance,syncPoint={time:start,segmentIndex:partAndSegment.segmentIndex,partIndex:partAndSegment.partIndex}}return syncPoint}},{name:"Segment",run:(syncController,playlist,duration,currentTimeline,currentTime)=>{let syncPoint=null,lastDistance=null;currentTime=currentTime||0;const partsAndSegments=getPartsAndSegments(playlist);for(let i=0;
i<partsAndSegments.length;i++){const partAndSegment=partsAndSegments[playlist.endList||0===currentTime?i:partsAndSegments.length-(i+1)],segment=partAndSegment.segment,start=partAndSegment.part&&partAndSegment.part.start||segment&&segment.start;if(segment.timeline===currentTimeline&&void 0!==start){const distance=Math.abs(currentTime-start);if(null!==lastDistance&&lastDistance<distance)break;(!syncPoint||null===lastDistance||lastDistance>=distance)&&(lastDistance=distance,syncPoint={time:start,segmentIndex:partAndSegment.segmentIndex,partIndex:partAndSegment.partIndex})}}return syncPoint}},{name:"Discontinuity",run:(syncController,playlist,duration,currentTimeline,currentTime)=>{let syncPoint=null;if(currentTime=currentTime||0,playlist.discontinuityStarts&&playlist.discontinuityStarts.length){let lastDistance=null;for(let i=0;i<playlist.discontinuityStarts.length;i++){const segmentIndex=playlist.discontinuityStarts[i],discontinuity=playlist.discontinuitySequence+i+1,discontinuitySync=syncController.discontinu
ities[discontinuity];if(discontinuitySync){const distance=Math.abs(currentTime-discontinuitySync.time);if(null!==lastDistance&&lastDistance<distance)break;(!syncPoint||null===lastDistance||lastDistance>=distance)&&(lastDistance=distance,syncPoint={time:discontinuitySync.time,segmentIndex:segmentIndex,partIndex:null})}}}return syncPoint}},{name:"Playlist",run:(syncController,playlist,duration,currentTimeline,currentTime)=>{if(playlist.syncInfo){return{time:playlist.syncInfo.time,segmentIndex:playlist.syncInfo.mediaSequence-playlist.mediaSequence,partIndex:null}}return null}}];class SyncController extends videojs.EventTarget{constructor(){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={},this.mediaSequenceStorage_=new Map,this.logger_=logger("SyncController")}getMediaSequenceMap(type){return this.mediaSequenceStorage_.get(type)}updateMediaSequenceMap(playlist,currentTime,type){if(void 0===playlist.mediaSequence||!Array.isArray(playlist.segments)||!playlist.segments.length)ret
urn;const currentMap=this.getMediaSequenceMap(type),result=new Map;let currentBaseTime,currentMediaSequence=playlist.mediaSequence;currentMap?currentMap.has(playlist.mediaSequence)?currentBaseTime=currentMap.get(playlist.mediaSequence).start:(this.logger_("MediaSequence sync for ".concat(type," segment loader - received a gap between playlists.\nFallback base time to: ").concat(currentTime,".\nReceived media sequence: ").concat(currentMediaSequence,".\nCurrent map: "),currentMap),currentBaseTime=currentTime):currentBaseTime=0,this.logger_("MediaSequence sync for ".concat(type," segment loader.\nReceived media sequence: ").concat(currentMediaSequence,".\nbase time is ").concat(currentBaseTime,"\nCurrent map: "),currentMap),playlist.segments.forEach((segment=>{const start=currentBaseTime,end=start+segment.duration,range={start:start,end:end};result.set(currentMediaSequence,range),currentMediaSequence++,currentBaseTime=end})),this.mediaSequenceStorage_.set(type,result)}getSyncPoint(playlist,duration,currentTime
line,currentTime,type){if(duration!==1/0){return syncPointStrategies.find((_ref76=>{let{name:name}=_ref76;return"VOD"===name})).run(this,playlist,duration)}const syncPoints=this.runStrategies_(playlist,duration,currentTimeline,currentTime,type);if(!syncPoints.length)return null;for(const syncPointInfo of syncPoints){const{syncPoint:syncPoint,strategy:strategy}=syncPointInfo,{segmentIndex:segmentIndex,time:time}=syncPoint;if(segmentIndex<0)continue;const start=time,end=start+playlist.segments[segmentIndex].duration;if(this.logger_("Strategy: ".concat(strategy,". Current time: ").concat(currentTime,". selected segment: ").concat(segmentIndex,". Time: [").concat(start," -> ").concat(end,"]}")),currentTime>=start&¤tTime<end)return this.logger_("Found sync point with exact match: ",syncPoint),syncPoint}return this.selectSyncPoint_(syncPoints,{key:"time",value:currentTime})}getExpiredTime(playlist,duration){if(!playlist||!playlist.segments)return null;const syncPoints=this.runStrategies_(playlist,duration,pl
aylist.discontinuitySequence,0,"main");if(!syncPoints.length)return null;const syncPoint=this.selectSyncPoint_(syncPoints,{key:"segmentIndex",value:0});return syncPoint.segmentIndex>0&&(syncPoint.time*=-1),Math.abs(syncPoint.time+sumDurations({defaultDuration:playlist.targetDuration,durationList:playlist.segments,startIndex:syncPoint.segmentIndex,endIndex:0}))}runStrategies_(playlist,duration,currentTimeline,currentTime,type){const syncPoints=[];for(let i=0;i<syncPointStrategies.length;i++){const strategy=syncPointStrategies[i],syncPoint=strategy.run(this,playlist,duration,currentTimeline,currentTime,type);syncPoint&&(syncPoint.strategy=strategy.name,syncPoints.push({strategy:strategy.name,syncPoint:syncPoint}))}return syncPoints}selectSyncPoint_(syncPoints,target){let bestSyncPoint=syncPoints[0].syncPoint,bestDistance=Math.abs(syncPoints[0].syncPoint[target.key]-target.value),bestStrategy=syncPoints[0].strategy;for(let i=1;i<syncPoints.length;i++){const newDistance=Math.abs(syncPoints[i].syncPoint[target.ke
y]-target.value);newDistance<bestDistance&&(bestDistance=newDistance,bestSyncPoint=syncPoints[i].syncPoint,bestStrategy=syncPoints[i].strategy)}return this.logger_("syncPoint for [".concat(target.key,": ").concat(target.value,"] chosen with strategy")+" [".concat(bestStrategy,"]: [time:").concat(bestSyncPoint.time,",")+" segmentIndex:".concat(bestSyncPoint.segmentIndex)+("number"==typeof bestSyncPoint.partIndex?",partIndex:".concat(bestSyncPoint.partIndex):"")+"]"),bestSyncPoint}saveExpiredSegmentInfo(oldPlaylist,newPlaylist){const mediaSequenceDiff=newPlaylist.mediaSequence-oldPlaylist.mediaSequence;if(mediaSequenceDiff>86400)videojs.log.warn("Not saving expired segment info. Media sequence gap ".concat(mediaSequenceDiff," is too large."));else for(let i=mediaSequenceDiff-1;i>=0;i--){const lastRemovedSegment=oldPlaylist.segments[i];if(lastRemovedSegment&&void 0!==lastRemovedSegment.start){newPlaylist.syncInfo={mediaSequence:oldPlaylist.mediaSequence+i,time:lastRemovedSegment.start},this.logger_("playlist re
fresh sync: [time:".concat(newPlaylist.syncInfo.time,",")+" mediaSequence: ".concat(newPlaylist.syncInfo.mediaSequence,"]")),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(playlist){if(this.timelineToDatetimeMappings={},playlist.segments&&playlist.segments.length&&playlist.segments[0].dateTimeObject){const firstSegment=playlist.segments[0],playlistTimestamp=firstSegment.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[firstSegment.timeline]=-playlistTimestamp}}saveSegmentTimingInfo(_ref77){let{segmentInfo:segmentInfo,shouldSaveTimelineMapping:shouldSaveTimelineMapping}=_ref77;const didCalculateSegmentTimeMapping=this.calculateSegmentTimeMapping_(segmentInfo,segmentInfo.timingInfo,shouldSaveTimelineMapping),segment=segmentInfo.segment;didCalculateSegmentTimeMapping&&(this.saveDiscontinuitySyncInfo_(segmentInfo),segmentInfo.playlist.syncInfo||(segmentInfo.playlist.syncInfo={mediaSequence:segmentInfo.playlist.mediaSequence+segmentInfo.mediaIndex,time:segment.start}));const dateTim
e=segment.dateTimeObject;segment.discontinuity&&shouldSaveTimelineMapping&&dateTime&&(this.timelineToDatetimeMappings[segment.timeline]=-dateTime.getTime()/1e3)}timestampOffsetForTimeline(timeline){return void 0===this.timelines[timeline]?null:this.timelines[timeline].time}mappingForTimeline(timeline){return void 0===this.timelines[timeline]?null:this.timelines[timeline].mapping}calculateSegmentTimeMapping_(segmentInfo,timingInfo,shouldSaveTimelineMapping){const segment=segmentInfo.segment,part=segmentInfo.part;let start,end,mappingObj=this.timelines[segmentInfo.timeline];if("number"==typeof segmentInfo.timestampOffset)mappingObj={time:segmentInfo.startOfSegment,mapping:segmentInfo.startOfSegment-timingInfo.start},shouldSaveTimelineMapping&&(this.timelines[segmentInfo.timeline]=mappingObj,this.trigger("timestampoffset"),this.logger_("time mapping for timeline ".concat(segmentInfo.timeline,": ")+"[time: ".concat(mappingObj.time,"] [mapping: ").concat(mappingObj.mapping,"]"))),start=segmentInfo.startOfSegment,
end=timingInfo.end+mappingObj.mapping;else{if(!mappingObj)return!1;start=timingInfo.start+mappingObj.mapping,end=timingInfo.end+mappingObj.mapping}return part&&(part.start=start,part.end=end),(!segment.start||start<segment.start)&&(segment.start=start),segment.end=end,!0}saveDiscontinuitySyncInfo_(segmentInfo){const playlist=segmentInfo.playlist,segment=segmentInfo.segment;if(segment.discontinuity)this.discontinuities[segment.timeline]={time:segment.start,accuracy:0};else if(playlist.discontinuityStarts&&playlist.discontinuityStarts.length)for(let i=0;i<playlist.discontinuityStarts.length;i++){const segmentIndex=playlist.discontinuityStarts[i],discontinuity=playlist.discontinuitySequence+i+1,mediaIndexDiff=segmentIndex-segmentInfo.mediaIndex,accuracy=Math.abs(mediaIndexDiff);if(!this.discontinuities[discontinuity]||this.discontinuities[discontinuity].accuracy>accuracy){let time;time=mediaIndexDiff<0?segment.start-sumDurations({defaultDuration:playlist.targetDuration,durationList:playlist.segments,startIndex:
segmentInfo.mediaIndex,endIndex:segmentIndex}):segment.end+sumDurations({defaultDuration:playlist.targetDuration,durationList:playlist.segments,startIndex:segmentInfo.mediaIndex+1,endIndex:segmentIndex}),this.discontinuities[discontinuity]={time:time,accuracy:accuracy}}}}dispose(){this.trigger("dispose"),this.off()}}class TimelineChangeController extends videojs.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(type){this.pendingTimelineChanges_[type]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange(_ref78){let{type:type,from:from,to:to}=_ref78;return"number"==typeof from&&"number"==typeof to&&(this.pendingTimelineChanges_[type]={type:type,from:from,to:to},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[type]}lastTimelineChange(_ref79){let{type:type,from:from,to:to}=_ref79;return"number"==typeof from&&"number"==typeof to&&(this.lastTimelineChanges_[type]={type:type,from:from,to:to},delete this.pendingT
imelineChanges_[type],this.trigger("timelinechange")),this.lastTimelineChanges_[type]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const workerCode=transform(getWorkerString((function(){var Stream=function(){function Stream(){this.listeners={}}var _proto=Stream.prototype;return _proto.on=function(type,listener){this.listeners[type]||(this.listeners[type]=[]),this.listeners[type].push(listener)},_proto.off=function(type,listener){if(!this.listeners[type])return!1;var index=this.listeners[type].indexOf(listener);return this.listeners[type]=this.listeners[type].slice(0),this.listeners[type].splice(index,1),index>-1},_proto.trigger=function(type){var callbacks=this.listeners[type];if(callbacks)if(2===arguments.length)for(var length=callbacks.length,i=0;i<length;++i)callbacks[i].call(this,arguments[1]);else for(var args=Array.prototype.slice.call(arguments,1),_length=callbacks.length,_i=0;_i<_length;++_i)callbacks[_i].apply(this,args)},_proto.dispose=f
unction(){this.listeners={}},_proto.pipe=function(destination){this.on("data",(function(data){destination.push(data)}))},Stream}();
/*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */let aesTables=null;class AES{constructor(key){let i,j,tmp;aesTables||(aesTables=function(){const tables=[[[],[],[],[],[]],[[],[],[],[],[]]],encTable=tables[0],decTable=tables[1],sbox=encTable[4],sboxInv=decTable[4];let i,x,xInv;const d=[],th=[];let x2,x4,x8,s,tEnc,tDec;for(i=0;i<256;i++)th[(d[i]=i<<1^283*(i>>7))^i]=i;for(x=xInv=0;!sbox[x];x^=x2||1,xInv=th[xInv]||1)for(s=xInv^xInv<<1^xInv<<2^xInv<<3^xInv<<4,s=s>>8^255&s^99,sbox[x]=s,sboxInv[s]=x,x8=d[x4=d[x2=d[x]]],tDec=16843009*x8^65537*x4^257*x2^16843008*x,tEnc=257*d[s]^16843008*s,i=0;i<4;i++)encTable[i][x]=tEnc=tEnc<<24^tEnc>>>8,decTable[i][s]=tDec=tDec<<24^tDec>>>8;for(i=0;i<5;i++)encTable[i]=encTable[i].slice(0),decTable[i]=decTable[i].slice(0);return tables}()),this._tables=[[aesTables[0][0].slice(),aesTables[0][1].slice(),aesTables[0][2].slice(),aesTables[0][3].slice(),aesTables[0][4].slice()],[aesTables[1][0].slice(),aesTables[1][1].slice(),aesTables[1][2].slice(),aesTables[1][3].slice(),aesTables[1
][4].slice()]];const sbox=this._tables[0][4],decTable=this._tables[1],keyLen=key.length;let rcon=1;if(4!==keyLen&&6!==keyLen&&8!==keyLen)throw new Error("Invalid aes key size");const encKey=key.slice(0),decKey=[];for(this._key=[encKey,decKey],i=keyLen;i<4*keyLen+28;i++)tmp=encKey[i-1],(i%keyLen==0||8===keyLen&&i%keyLen==4)&&(tmp=sbox[tmp>>>24]<<24^sbox[tmp>>16&255]<<16^sbox[tmp>>8&255]<<8^sbox[255&tmp],i%keyLen==0&&(tmp=tmp<<8^tmp>>>24^rcon<<24,rcon=rcon<<1^283*(rcon>>7))),encKey[i]=encKey[i-keyLen]^tmp;for(j=0;i;j++,i--)tmp=encKey[3&j?i:i-4],decKey[j]=i<=4||j<4?tmp:decTable[0][sbox[tmp>>>24]]^decTable[1][sbox[tmp>>16&255]]^decTable[2][sbox[tmp>>8&255]]^decTable[3][sbox[255&tmp]]}decrypt(encrypted0,encrypted1,encrypted2,encrypted3,out,offset){const key=this._key[1];let a2,b2,c2,a=encrypted0^key[0],b=encrypted3^key[1],c=encrypted2^key[2],d=encrypted1^key[3];const nInnerRounds=key.length/4-2;let i,kIndex=4;const table=this._tables[1],table0=table[0],table1=table[1],table2=table[2],table3=table[3],sbox=table[4]
;for(i=0;i<nInnerRounds;i++)a2=table0[a>>>24]^table1[b>>16&255]^table2[c>>8&255]^table3[255&d]^key[kIndex],b2=table0[b>>>24]^table1[c>>16&255]^table2[d>>8&255]^table3[255&a]^key[kIndex+1],c2=table0[c>>>24]^table1[d>>16&255]^table2[a>>8&255]^table3[255&b]^key[kIndex+2],d=table0[d>>>24]^table1[a>>16&255]^table2[b>>8&255]^table3[255&c]^key[kIndex+3],kIndex+=4,a=a2,b=b2,c=c2;for(i=0;i<4;i++)out[(3&-i)+offset]=sbox[a>>>24]<<24^sbox[b>>16&255]<<16^sbox[c>>8&255]<<8^sbox[255&d]^key[kIndex++],a2=a,a=b,b=c,c=d,d=a2}}class AsyncStream extends Stream{constructor(){super(Stream),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(job){this.jobs.push(job),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const ntoh=function(word){return word<<24|(65280&word)<<8|(16711680&word)>>8|word>>>24};class Decrypter{constructor(encrypted,key,initVector,done){const ste
p=Decrypter.STEP,encrypted32=new Int32Array(encrypted.buffer),decrypted=new Uint8Array(encrypted.byteLength);let i=0;for(this.asyncStream_=new AsyncStream,this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i,i+step),key,initVector,decrypted)),i=step;i<encrypted32.length;i+=step)initVector=new Uint32Array([ntoh(encrypted32[i-4]),ntoh(encrypted32[i-3]),ntoh(encrypted32[i-2]),ntoh(encrypted32[i-1])]),this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i,i+step),key,initVector,decrypted));this.asyncStream_.push((function(){var padded;
/*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */done(null,(padded=decrypted).subarray(0,padded.byteLength-padded[padded.byteLength-1]))}))}static get STEP(){return 32e3}decryptChunk_(encrypted,key,initVector,decrypted){return function(){const bytes=function(encrypted,key,initVector){const encrypted32=new Int32Array(encrypted.buffer,encrypted.byteOffset,encrypted.byteLength>>2),decipher=new AES(Array.prototype.slice.call(key)),decrypted=new Uint8Array(encrypted.byteLength),decrypted32=new Int32Array(decrypted.buffer);let init0,init1,init2,init3,encrypted0,encrypted1,encrypted2,encrypted3,wordIx;for(init0=initVector[0],init1=initVector[1],init2=initVector[2],init3=initVector[3],wordIx=0;wordIx<encrypted32.length;wordIx+=4)encrypted0=ntoh(encrypted32[wordIx]),encrypted1=ntoh(encrypted32[wordIx+1]),encrypted2=ntoh(encrypted32[wordIx+2]),encrypted3=ntoh(encrypted32[wordIx+3]),decipher.decrypt(encrypted0,encrypted1,encrypted2,encrypted3,decrypted32,wordIx),decrypted32[wordIx]=ntoh(decrypted32[wordIx]^
init0),decrypted32[wordIx+1]=ntoh(decrypted32[wordIx+1]^init1),decrypted32[wordIx+2]=ntoh(decrypted32[wordIx+2]^init2),decrypted32[wordIx+3]=ntoh(decrypted32[wordIx+3]^init3),init0=encrypted0,init1=encrypted1,init2=encrypted2,init3=encrypted3;return decrypted}(encrypted,key,initVector);decrypted.set(bytes,encrypted.byteOffset)}}}var win,commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};win="undefined"!=typeof window?window:void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:{};var BigInt=win.BigInt||Number;BigInt("0x1"),BigInt("0x100"),BigInt("0x10000"),BigInt("0x1000000"),BigInt("0x100000000"),BigInt("0x10000000000"),BigInt("0x1000000000000"),BigInt("0x100000000000000"),BigInt("0x10000000000000000"),function(){var a=new Uint16Array([65484]),b=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);255===b[0]||b[0]}();const createTransferableMessage=function(message){const transferable={};r
eturn Object.keys(message).forEach((key=>{const value=message[key];var obj;obj=value,("function"===ArrayBuffer.isView?ArrayBuffer.isView(obj):obj&&obj.buffer instanceof ArrayBuffer)?transferable[key]={bytes:value.buffer,byteOffset:value.byteOffset,byteLength:value.byteLength}:transferable[key]=value})),transferable};self.onmessage=function(event){const data=event.data,encrypted=new Uint8Array(data.encrypted.bytes,data.encrypted.byteOffset,data.encrypted.byteLength),key=new Uint32Array(data.key.bytes,data.key.byteOffset,data.key.byteLength/4),iv=new Uint32Array(data.iv.bytes,data.iv.byteOffset,data.iv.byteLength/4);new Decrypter(encrypted,key,iv,(function(err,bytes){self.postMessage(createTransferableMessage({source:data.source,decrypted:bytes}),[bytes.buffer])}))}})));var Decrypter=factory(workerCode);const audioTrackKind_=properties=>{let kind=properties.default?"main":"alternative";return properties.characteristics&&properties.characteristics.indexOf("public.accessibility.describes-video")>=0&&(kind="main-
desc"),kind},stopLoaders=(segmentLoader,mediaType)=>{segmentLoader.abort(),segmentLoader.pause(),mediaType&&mediaType.activePlaylistLoader&&(mediaType.activePlaylistLoader.pause(),mediaType.activePlaylistLoader=null)},startLoaders=(playlistLoader,mediaType)=>{mediaType.activePlaylistLoader=playlistLoader,playlistLoader.load()},onError={AUDIO:(type,settings)=>()=>{const{mediaTypes:{[type]:mediaType},excludePlaylist:excludePlaylist}=settings,activeTrack=mediaType.activeTrack(),activeGroup=mediaType.activeGroup(),id=(activeGroup.filter((group=>group.default))[0]||activeGroup[0]).id,defaultTrack=mediaType.tracks[id];if(activeTrack!==defaultTrack){videojs.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const trackId in mediaType.tracks)mediaType.tracks[trackId].enabled=mediaType.tracks[trackId]===defaultTrack;mediaType.onTrackChanged()}else excludePlaylist({error:{message:"Problem encountered loading the default audio track."}})},SUBTITLES:(type,settings)=>()=>{con
st{mediaTypes:{[type]:mediaType}}=settings;videojs.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const track=mediaType.activeTrack();track&&(track.mode="disabled"),mediaType.onTrackChanged()}},setupListeners={AUDIO:(type,playlistLoader,settings)=>{if(!playlistLoader)return;const{tech:tech,requestOptions:requestOptions,segmentLoaders:{[type]:segmentLoader}}=settings;playlistLoader.on("loadedmetadata",(()=>{const media=playlistLoader.media();segmentLoader.playlist(media,requestOptions),(!tech.paused()||media.endList&&"none"!==tech.preload())&&segmentLoader.load()})),playlistLoader.on("loadedplaylist",(()=>{segmentLoader.playlist(playlistLoader.media(),requestOptions),tech.paused()||segmentLoader.load()})),playlistLoader.on("error",onError[type](type,settings))},SUBTITLES:(type,playlistLoader,settings)=>{const{tech:tech,requestOptions:requestOptions,segmentLoaders:{[type]:segmentLoader},mediaTypes:{[type]:mediaType}}=settings;playlistLoader.on("loadedmetadata",(()=>{const
media=playlistLoader.media();segmentLoader.playlist(media,requestOptions),segmentLoader.track(mediaType.activeTrack()),(!tech.paused()||media.endList&&"none"!==tech.preload())&&segmentLoader.load()})),playlistLoader.on("loadedplaylist",(()=>{segmentLoader.playlist(playlistLoader.media(),requestOptions),tech.paused()||segmentLoader.load()})),playlistLoader.on("error",onError[type](type,settings))}},initialize={AUDIO:(type,settings)=>{const{vhs:vhs,sourceType:sourceType,segmentLoaders:{[type]:segmentLoader},requestOptions:requestOptions,main:{mediaGroups:mediaGroups},mediaTypes:{[type]:{groups:groups,tracks:tracks,logger_:logger_}},mainPlaylistLoader:mainPlaylistLoader}=settings,audioOnlyMain=isAudioOnly(mainPlaylistLoader.main);mediaGroups[type]&&0!==Object.keys(mediaGroups[type]).length||(mediaGroups[type]={main:{default:{default:!0}}},audioOnlyMain&&(mediaGroups[type].main.default.playlists=mainPlaylistLoader.main.playlists));for(const groupId in mediaGroups[type]){groups[groupId]||(groups[groupId]=[]);for(
const variantLabel in mediaGroups[type][groupId]){let playlistLoader,properties=mediaGroups[type][groupId][variantLabel];if(audioOnlyMain?(logger_("AUDIO group '".concat(groupId,"' label '").concat(variantLabel,"' is a main playlist")),properties.isMainPlaylist=!0,playlistLoader=null):playlistLoader="vhs-json"===sourceType&&properties.playlists?new PlaylistLoader(properties.playlists[0],vhs,requestOptions):properties.resolvedUri?new PlaylistLoader(properties.resolvedUri,vhs,requestOptions):properties.playlists&&"dash"===sourceType?new DashPlaylistLoader(properties.playlists[0],vhs,requestOptions,mainPlaylistLoader):null,properties=merge({id:variantLabel,playlistLoader:playlistLoader},properties),setupListeners[type](type,properties.playlistLoader,settings),groups[groupId].push(properties),void 0===tracks[variantLabel]){const track=new videojs.AudioTrack({id:variantLabel,kind:audioTrackKind_(properties),enabled:!1,language:properties.language,default:properties.default,label:variantLabel});tracks[variantLabel
]=track}}}segmentLoader.on("error",onError[type](type,settings))},SUBTITLES:(type,settings)=>{const{tech:tech,vhs:vhs,sourceType:sourceType,segmentLoaders:{[type]:segmentLoader},requestOptions:requestOptions,main:{mediaGroups:mediaGroups},mediaTypes:{[type]:{groups:groups,tracks:tracks}},mainPlaylistLoader:mainPlaylistLoader}=settings;for(const groupId in mediaGroups[type]){groups[groupId]||(groups[groupId]=[]);for(const variantLabel in mediaGroups[type][groupId]){if(!vhs.options_.useForcedSubtitles&&mediaGroups[type][groupId][variantLabel].forced)continue;let playlistLoader,properties=mediaGroups[type][groupId][variantLabel];if("hls"===sourceType)playlistLoader=new PlaylistLoader(properties.resolvedUri,vhs,requestOptions);else if("dash"===sourceType){if(!properties.playlists.filter((p=>p.excludeUntil!==1/0)).length)return;playlistLoader=new DashPlaylistLoader(properties.playlists[0],vhs,requestOptions,mainPlaylistLoader)}else"vhs-json"===sourceType&&(playlistLoader=new PlaylistLoader(properties.playlists?pr
operties.playlists[0]:properties.resolvedUri,vhs,requestOptions));if(properties=merge({id:variantLabel,playlistLoader:playlistLoader},properties),setupListeners[type](type,properties.playlistLoader,settings),groups[groupId].push(properties),void 0===tracks[variantLabel]){const track=tech.addRemoteTextTrack({id:variantLabel,kind:"subtitles",default:properties.default&&properties.autoselect,language:properties.language,label:variantLabel},!1).track;tracks[variantLabel]=track}}}segmentLoader.on("error",onError[type](type,settings))},"CLOSED-CAPTIONS":(type,settings)=>{const{tech:tech,main:{mediaGroups:mediaGroups},mediaTypes:{[type]:{groups:groups,tracks:tracks}}}=settings;for(const groupId in mediaGroups[type]){groups[groupId]||(groups[groupId]=[]);for(const variantLabel in mediaGroups[type][groupId]){const properties=mediaGroups[type][groupId][variantLabel];if(!/^(?:CC|SERVICE)/.test(properties.instreamId))continue;const captionServices=tech.options_.vhs&&tech.options_.vhs.captionServices||{};let newProps={la
bel:variantLabel,language:properties.language,instreamId:properties.instreamId,default:properties.default&&properties.autoselect};if(captionServices[newProps.instreamId]&&(newProps=merge(newProps,captionServices[newProps.instreamId])),void 0===newProps.default&&delete newProps.default,groups[groupId].push(merge({id:variantLabel},properties)),void 0===tracks[variantLabel]){const track=tech.addRemoteTextTrack({id:newProps.instreamId,kind:"captions",default:newProps.default,language:newProps.language,label:newProps.label},!1).track;tracks[variantLabel]=track}}}}},groupMatch=(list,media)=>{for(let i=0;i<list.length;i++){if(playlistMatch(media,list[i]))return!0;if(list[i].playlists&&groupMatch(list[i].playlists,media))return!0}return!1},activeTrack={AUDIO:(type,settings)=>()=>{const{mediaTypes:{[type]:{tracks:tracks}}}=settings;for(const id in tracks)if(tracks[id].enabled)return tracks[id];return null},SUBTITLES:(type,settings)=>()=>{const{mediaTypes:{[type]:{tracks:tracks}}}=settings;for(const id in tracks)if("s
howing"===tracks[id].mode||"hidden"===tracks[id].mode)return tracks[id];return null}},setupMediaGroups=settings=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((type=>{initialize[type](type,settings)}));const{mediaTypes:mediaTypes,mainPlaylistLoader:mainPlaylistLoader,tech:tech,vhs:vhs,segmentLoaders:{AUDIO:audioSegmentLoader,main:mainSegmentLoader}}=settings;["AUDIO","SUBTITLES"].forEach((type=>{mediaTypes[type].activeGroup=((type,settings)=>track=>{const{mainPlaylistLoader:mainPlaylistLoader,mediaTypes:{[type]:{groups:groups}}}=settings,media=mainPlaylistLoader.media();if(!media)return null;let variants=null;media.attributes[type]&&(variants=groups[media.attributes[type]]);const groupKeys=Object.keys(groups);if(!variants)if("AUDIO"===type&&groupKeys.length>1&&isAudioOnly(settings.main))for(let i=0;i<groupKeys.length;i++){const groupPropertyList=groups[groupKeys[i]];if(groupMatch(groupPropertyList,media)){variants=groupPropertyList;break}}else groups.main?variants=groups.main:1===groupKeys.length&&(varian
ts=groups[groupKeys[0]]);return void 0===track?variants:null!==track&&variants&&variants.filter((props=>props.id===track.id))[0]||null})(type,settings),mediaTypes[type].activeTrack=activeTrack[type](type,settings),mediaTypes[type].onGroupChanged=((type,settings)=>()=>{const{segmentLoaders:{[type]:segmentLoader,main:mainSegmentLoader},mediaTypes:{[type]:mediaType}}=settings,activeTrack=mediaType.activeTrack(),activeGroup=mediaType.getActiveGroup(),previousActiveLoader=mediaType.activePlaylistLoader,lastGroup=mediaType.lastGroup_;activeGroup&&lastGroup&&activeGroup.id===lastGroup.id||(mediaType.lastGroup_=activeGroup,mediaType.lastTrack_=activeTrack,stopLoaders(segmentLoader,mediaType),activeGroup&&!activeGroup.isMainPlaylist&&(activeGroup.playlistLoader?(segmentLoader.resyncLoader(),startLoaders(activeGroup.playlistLoader,mediaType)):previousActiveLoader&&mainSegmentLoader.resetEverything()))})(type,settings),mediaTypes[type].onGroupChanging=((type,settings)=>()=>{const{segmentLoaders:{[type]:segmentLoader},m
ediaTypes:{[type]:mediaType}}=settings;mediaType.lastGroup_=null,segmentLoader.abort(),segmentLoader.pause()})(type,settings),mediaTypes[type].onTrackChanged=((type,settings)=>()=>{const{mainPlaylistLoader:mainPlaylistLoader,segmentLoaders:{[type]:segmentLoader,main:mainSegmentLoader},mediaTypes:{[type]:mediaType}}=settings,activeTrack=mediaType.activeTrack(),activeGroup=mediaType.getActiveGroup(),previousActiveLoader=mediaType.activePlaylistLoader,lastTrack=mediaType.lastTrack_;if((!lastTrack||!activeTrack||lastTrack.id!==activeTrack.id)&&(mediaType.lastGroup_=activeGroup,mediaType.lastTrack_=activeTrack,stopLoaders(segmentLoader,mediaType),activeGroup)){if(activeGroup.isMainPlaylist){if(!activeTrack||!lastTrack||activeTrack.id===lastTrack.id)return;const pc=settings.vhs.playlistController_,newPlaylist=pc.selectPlaylist();if(pc.media()===newPlaylist)return;return mediaType.logger_("track change. Switching main audio from ".concat(lastTrack.id," to ").concat(activeTrack.id)),mainPlaylistLoader.pause(),mainSe
gmentLoader.resetEverything(),void pc.fastQualityChange_(newPlaylist)}if("AUDIO"===type){if(!activeGroup.playlistLoader)return mainSegmentLoader.setAudio(!0),void mainSegmentLoader.resetEverything();segmentLoader.setAudio(!0),mainSegmentLoader.setAudio(!1)}previousActiveLoader!==activeGroup.playlistLoader?(segmentLoader.track&&segmentLoader.track(activeTrack),segmentLoader.resetEverything(),startLoaders(activeGroup.playlistLoader,mediaType)):startLoaders(activeGroup.playlistLoader,mediaType)}})(type,settings),mediaTypes[type].getActiveGroup=((type,_ref80)=>{let{mediaTypes:mediaTypes}=_ref80;return()=>{const activeTrack_=mediaTypes[type].activeTrack();return activeTrack_?mediaTypes[type].activeGroup(activeTrack_):null}})(type,settings)}));const audioGroup=mediaTypes.AUDIO.activeGroup();if(audioGroup){const groupId=(audioGroup.filter((group=>group.default))[0]||audioGroup[0]).id;mediaTypes.AUDIO.tracks[groupId].enabled=!0,mediaTypes.AUDIO.onGroupChanged(),mediaTypes.AUDIO.onTrackChanged();mediaTypes.AUDIO.getA
ctiveGroup().playlistLoader?(mainSegmentLoader.setAudio(!1),audioSegmentLoader.setAudio(!0)):mainSegmentLoader.setAudio(!0)}mainPlaylistLoader.on("mediachange",(()=>{["AUDIO","SUBTITLES"].forEach((type=>mediaTypes[type].onGroupChanged()))})),mainPlaylistLoader.on("mediachanging",(()=>{["AUDIO","SUBTITLES"].forEach((type=>mediaTypes[type].onGroupChanging()))}));const onAudioTrackChanged=()=>{mediaTypes.AUDIO.onTrackChanged(),tech.trigger({type:"usage",name:"vhs-audio-change"})};tech.audioTracks().addEventListener("change",onAudioTrackChanged),tech.remoteTextTracks().addEventListener("change",mediaTypes.SUBTITLES.onTrackChanged),vhs.on("dispose",(()=>{tech.audioTracks().removeEventListener("change",onAudioTrackChanged),tech.remoteTextTracks().removeEventListener("change",mediaTypes.SUBTITLES.onTrackChanged)})),tech.clearTracks("audio");for(const id in mediaTypes.AUDIO.tracks)tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id])};class SteeringManifest{constructor(){this.priority_=[],this.pathwayClones_=new
Map}set version(number){1===number&&(this.version_=number)}set ttl(seconds){this.ttl_=seconds||300}set reloadUri(uri){uri&&(this.reloadUri_=resolveUrl(this.reloadUri_,uri))}set priority(array){array&&array.length&&(this.priority_=array)}set pathwayClones(array){array&&array.length&&(this.pathwayClones_=new Map(array.map((clone=>[clone.ID,clone]))))}get version(){return this.version_}get ttl(){return this.ttl_}get reloadUri(){return this.reloadUri_}get priority(){return this.priority_}get pathwayClones(){return this.pathwayClones_}}class ContentSteeringController extends videojs.EventTarget{constructor(xhr,bandwidth){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new SteeringManifest,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=logger("Content Steering"),thi
s.xhr_=xhr,this.getBandwidth_=bandwidth}assignTagProperties(baseUrl,steeringTag){this.manifestType_=steeringTag.serverUri?"HLS":"DASH";const steeringUri=steeringTag.serverUri||steeringTag.serverURL;if(!steeringUri)return this.logger_("steering manifest URL is ".concat(steeringUri,", cannot request steering manifest.")),void this.trigger("error");steeringUri.startsWith("data:")?this.decodeDataUriManifest_(steeringUri.substring(steeringUri.indexOf(",")+1)):(this.steeringManifest.reloadUri=resolveUrl(baseUrl,steeringUri),this.defaultPathway=steeringTag.pathwayId||steeringTag.defaultServiceLocation,this.queryBeforeStart=steeringTag.queryBeforeStart,this.proxyServerUrl_=steeringTag.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering"))}requestSteeringManifest(initial){const reloadUri=this.steeringManifest.reloadUri;if(!reloadUri)return;const uri=initial?reloadUri:this.getRequestURI(reloadUri);if(!uri)return this.logger_("No valid content steering manifest URIs. Stopping cont
ent steering."),this.trigger("error"),void this.dispose();this.request_=this.xhr_({uri:uri},((error,errorInfo)=>{if(error){if(410===errorInfo.status)return this.logger_("manifest request 410 ".concat(error,".")),this.logger_("There will be no more content steering requests to ".concat(uri," this session.")),void this.excludedSteeringManifestURLs.add(uri);if(429===errorInfo.status){const retrySeconds=errorInfo.responseHeaders["retry-after"];return this.logger_("manifest request 429 ".concat(error,".")),this.logger_("content steering will retry in ".concat(retrySeconds," seconds.")),void this.startTTLTimeout_(parseInt(retrySeconds,10))}return this.logger_("manifest failed to load ".concat(error,".")),void this.startTTLTimeout_()}const steeringManifestJson=JSON.parse(this.request_.responseText);this.assignSteeringProperties_(steeringManifestJson),this.startTTLTimeout_()}))}setProxyServerUrl_(steeringUrl){const steeringUrlObject=new window.URL(steeringUrl),proxyServerUrlObject=new window.URL(this.proxyServerUrl_
);return proxyServerUrlObject.searchParams.set("url",encodeURI(steeringUrlObject.toString())),this.setSteeringParams_(proxyServerUrlObject.toString())}decodeDataUriManifest_(dataUri){const steeringManifestJson=JSON.parse(window.atob(dataUri));this.assignSteeringProperties_(steeringManifestJson)}setSteeringParams_(url){const urlObject=new window.URL(url),path=this.getPathway(),networkThroughput=this.getBandwidth_();if(path){const pathwayKey="_".concat(this.manifestType_,"_pathway");urlObject.searchParams.set(pathwayKey,path)}if(networkThroughput){const throughputKey="_".concat(this.manifestType_,"_throughput");urlObject.searchParams.set(throughputKey,networkThroughput)}return urlObject.toString()}assignSteeringProperties_(steeringJson){if(this.steeringManifest.version=steeringJson.VERSION,!this.steeringManifest.version)return this.logger_("manifest version is ".concat(steeringJson.VERSION,", which is not supported.")),void this.trigger("error");this.steeringManifest.ttl=steeringJson.TTL,this.steeringManifest.
reloadUri=steeringJson["RELOAD-URI"],this.steeringManifest.priority=steeringJson["PATHWAY-PRIORITY"]||steeringJson["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=steeringJson["PATHWAY-CLONES"],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_("There are no available pathways for content steering. Ending content steering."),this.trigger("error"),this.dispose());const nextPathway=(pathwaysByPriority=>{for(const path of pathwaysByPriority)if(this.availablePathways_.has(path))return path;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==nextPathway&&(this.currentPathway=nextPathway,this.trigger("content-steering"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(reloadUri){if(!reloadUri)return null;const isExcluded=uri=>this.excludedSteeringManifestURLs.has(uri);if(this.proxyServerUrl_){const proxyURI=this.setProxyServerUrl_(reloadUri);if(!isExcluded(proxyURI))return proxy
URI}const steeringURI=this.setSteeringParams_(reloadUri);return isExcluded(steeringURI)?null:steeringURI}startTTLTimeout_(){const ttlMS=1e3*(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.steeringManifest.ttl);this.ttlTimeout_=window.setTimeout((()=>{this.requestSteeringManifest()}),ttlMS)}clearTTLTimeout_(){window.clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off("content-steering"),this.off("error"),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new SteeringManifest}addAvailablePathway(pathway){pathway&&this.availablePathways_.add(pathway)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(pathway){return this.availablePathways_.delete(pat
hway)}didDASHTagChange(baseURL,newTag){return!newTag&&this.steeringManifest.reloadUri||newTag&&(resolveUrl(baseURL,newTag.serverURL)!==this.steeringManifest.reloadUri||newTag.defaultServiceLocation!==this.defaultPathway||newTag.queryBeforeStart!==this.queryBeforeStart||newTag.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}}let Vhs$1;const loaderStats=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],sumLoaderStat=function(stat){return this.audioSegmentLoader_[stat]+this.mainSegmentLoader_[stat]};class PlaylistController extends videojs.EventTarget{constructor(options){super();const{src:src,withCredentials:withCredentials,tech:tech,bandwidth:bandwidth,externVhs:externVhs,useCueTags:useCueTags,playlistExclusionDuration:playlistExclusionDuration,enableLowInitialPlaylist:enableLowInitialPlaylist,sourceType:sourceType,cacheEncryptionKeys:cacheEncryptionKeys,bufferBased
ABR:bufferBasedABR,leastPixelDiffSelector:leastPixelDiffSelector,captionServices:captionServices}=options;if(!src)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:maxPlaylistRetries}=options;null==maxPlaylistRetries&&(maxPlaylistRetries=1/0),Vhs$1=externVhs,this.bufferBasedABR=Boolean(bufferBasedABR),this.leastPixelDiffSelector=Boolean(leastPixelDiffSelector),this.withCredentials=withCredentials,this.tech_=tech,this.vhs_=tech.vhs,this.sourceType_=sourceType,this.useCueTags_=useCueTags,this.playlistExclusionDuration=playlistExclusionDuration,this.maxPlaylistRetries=maxPlaylistRetries,this.enableLowInitialPlaylist=enableLowInitialPlaylist,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:withCredentials,maxPlaylistRetries:maxPlaylistRetries,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=(()=>{const mediaTypes={};r
eturn["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((type=>{mediaTypes[type]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:noop,activeTrack:noop,getActiveGroup:noop,onGroupChanged:noop,onTrackChanged:noop,lastTrack_:null,logger_:logger("MediaGroups[".concat(type,"]"))}})),mediaTypes})(),this.mediaSource=new window.MediaSource,this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.seekable_=createTimeRanges(),this.hasPlayed_=!1,this.syncController_=new SyncController(options),this.segmentMetadataTrack_=tech.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.decrypter_=new Decrypter,this.sourceUpdater_=new SourceUpdater(thi
s.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new TimelineChangeController,this.keyStatusMap_=new Map;const segmentLoaderSettings={vhs:this.vhs_,parse708captions:options.parse708captions,useDtsForTimestampOffset:options.useDtsForTimestampOffset,captionServices:captionServices,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:bandwidth,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:cacheEncryptionKeys,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:options.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_="dash"===this.sourceType_?new DashPlaylistLoader(src,th
is.vhs_,merge(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new PlaylistLoader(src,this.vhs_,merge(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new SegmentLoader(merge(segmentLoaderSettings,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),options),this.audioSegmentLoader_=new SegmentLoader(merge(segmentLoaderSettings,{loaderType:"audio"}),options),this.subtitleSegmentLoader_=new VTTSegmentLoader(merge(segmentLoaderSettings,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise(((resolve,reject)=>{function onLoad(){tech.off("vttjserror",onError),resolve()}function onError(){tech.off("vttjsloaded",onLoad),reject()}tech.one("vttjsloaded",onLoad),tech.one("vttjserror",onError),tech.addWebVttScript_()}))}),options);this.contentSteeringController_=new ContentSteeringController(this.vhs_.xhr,(()=
>this.mainSegmentLoader_.bandwidth)),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",(()=>this.startABRTimer_())),this.tech_.on("pause",(()=>this.stopABRTimer_())),this.tech_.on("play",(()=>this.startABRTimer_()))),loaderStats.forEach((stat=>{this[stat+"_"]=sumLoaderStat.bind(this,stat)})),this.logger_=logger("pc"),this.triggeredFmp4Usage=!1,"none"===this.tech_.preload()?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;const event="none"===this.tech_.preload()?"play":"loadstart";this.tech_.one(event,(()=>{const timeToLoadedDataStart=Date.now();this.tech_.one("loadeddata",(()=>{this.timeToLoadedData__=Date.now()-timeToLoadedDataStart,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.med
iaAppends}))}))}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const main=this.mainAppendsToLoadedData_(),audio=this.audioAppendsToLoadedData_();return-1===main||-1===audio?-1:main+audio}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(){let reason=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"abr";const nextPlaylist=this.selectPlaylist();nextPlaylist&&this.shouldSwitchToMedia_(nextPlaylist)&&this.switchMedia_(nextPlaylist,reason)}switchMedia_(playlist,cause,delay){const oldMedia=this.media(),oldId=oldMedia&&(oldMedia.id||oldMedia.uri),newId=playlist&&(playlist.id||playlist.uri);oldId&&oldId!==newId&&(this.logger_("switch media ".concat(oldId," -> ").concat(newId," from ").concat(cause)),this.tech_.trigger({type:"usage",name:"vhs-rendition-change-".concat(cause)})),this.mainPlaylistLoader_.media(playlist,delay)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPT
IONS"].forEach((type=>{const mediaType=this.mediaTypes_[type],activeGroup=mediaType?mediaType.activeGroup():null,pathway=this.contentSteeringController_.getPathway();if(activeGroup&&pathway){const dashMediaPlaylists=(activeGroup.length?activeGroup[0].playlists:activeGroup.playlists).filter((p=>p.attributes.serviceLocation===pathway));dashMediaPlaylists.length&&this.mediaTypes_[type].activePlaylistLoader.media(dashMediaPlaylists[0])}}))}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=window.setInterval((()=>this.checkABR_()),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(window.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const main=this.main(),defaultPlaylists=main&&main.playlists||[];if(!main||!main.mediaGroups||!main.mediaGroups.AUDIO)return defaultPlaylists;const AUDIO=main.mediaGroups.AUDIO,groupKeys=Object.keys(AUDIO);let track;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)track=this.mediaTypes_.AUDIO.activeTrack();else{const defaultGroup=
AUDIO.main||groupKeys.length&&AUDIO[groupKeys[0]];for(const label in defaultGroup)if(defaultGroup[label].default){track={label:label};break}}if(!track)return defaultPlaylists;const playlists=[];for(const group in AUDIO)if(AUDIO[group][track.label]){const properties=AUDIO[group][track.label];if(properties.playlists&&properties.playlists.length)playlists.push.apply(playlists,properties.playlists);else if(properties.uri)playlists.push(properties);else if(main.playlists.length)for(let i=0;i<main.playlists.length;i++){const playlist=main.playlists[i];playlist.attributes&&playlist.attributes.AUDIO&&playlist.attributes.AUDIO===group&&playlists.push(playlist)}}return playlists.length?playlists:defaultPlaylists}setupMainPlaylistLoaderListeners_(){this.mainPlaylistLoader_.on("loadedmetadata",(()=>{const media=this.mainPlaylistLoader_.media(),requestTimeout=1.5*media.targetDuration*1e3;isLowestEnabledRendition(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOpt
ions_.timeout=requestTimeout,media.endList&&"none"!==this.tech_.preload()&&(this.mainSegmentLoader_.playlist(media,this.requestOptions_),this.mainSegmentLoader_.load()),setupMediaGroups({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),media),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger("selectedinitialmedia"):this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",(()=>{this.trigger("selectedinitialmedia")}))})),this.mainPlaylistLoader_.on("loadedplaylist",(()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let updatedPlaylist=this.mainPlaylistLoader_.media();if(!updat
edPlaylist){let selectedMedia;if(this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_(),this.enableLowInitialPlaylist&&(selectedMedia=this.selectInitialPlaylist()),selectedMedia||(selectedMedia=this.selectPlaylist()),!selectedMedia||!this.shouldSwitchToMedia_(selectedMedia))return;this.initialMedia_=selectedMedia,this.switchMedia_(this.initialMedia_,"initial");if(!("vhs-json"===this.sourceType_&&this.initialMedia_.segments))return;updatedPlaylist=this.initialMedia_}this.handleUpdatedMediaPlaylist(updatedPlaylist)})),this.mainPlaylistLoader_.on("error",(()=>{const error=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:error.playlist,error:error})})),this.mainPlaylistLoader_.on("mediachanging",(()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()})),this.mainPlaylistLoader_.on("mediachange",(()=>{const media=this.mainPlaylistLoader_.media(),requestTimeout=1.5*media.targetDuration*1e3;isLowestEnabledRendition(this.mai
nPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=requestTimeout,"dash"===this.sourceType_&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(media,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})})),this.mainPlaylistLoader_.on("playlistunchanged",(()=>{const updatedPlaylist=this.mainPlaylistLoader_.media();if("playlist-unchanged"===updatedPlaylist.lastExcludeReason_)return;this.stuckAtPlaylistEnd_(updatedPlaylist)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))})),this.mainPlaylistLoader_.on("renditiondisabled",(()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})})),this.mainPlaylistLoader_.on("renditionenabled",(()=>{this.tech_.trigger({type:"usage",name:"vhs-ren
dition-enabled"})}))}handleUpdatedMediaPlaylist(updatedPlaylist){this.useCueTags_&&this.updateAdCues_(updatedPlaylist),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(updatedPlaylist,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!updatedPlaylist.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(main,media){const mediaGroups=main.mediaGroups||{};let defaultDemuxed=!0;const audioGroupKeys=Object.keys(mediaGroups.AUDIO);for(const mediaGroup in mediaGroups.AUDIO)for(const label in mediaGroups.AUDIO[mediaGroup]){mediaGroups.AUDIO[mediaGroup][label].uri||(defaultDemuxed=!1)}defaultDemuxed&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(mediaGroups.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),Vhs$1.Playlist.isAes(media)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),audioGroupKeys.length&&
Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(nextPlaylist){const currentPlaylist=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,currentTime=this.tech_.currentTime(),bufferLowWaterLine=this.bufferLowWaterLine(),bufferHighWaterLine=this.bufferHighWaterLine();return function(_ref81){let{currentPlaylist:currentPlaylist,buffered:buffered,currentTime:currentTime,nextPlaylist:nextPlaylist,bufferLowWaterLine:bufferLowWaterLine,bufferHighWaterLine:bufferHighWaterLine,duration:duration,bufferBasedABR:bufferBasedABR,log:log}=_ref81;if(!nextPlaylist)return videojs.log.warn("We received no playlist to switch to. Please check your stream."),!1;const sharedLogLine="allowing switch ".concat(currentPlaylist&¤tPlaylist.id||"null"," -> ").concat(nextPlaylist.id);if(!currentPlaylist)return log("".concat(sharedLogLine,"
as current playlist is not set")),!0;if(nextPlaylist.id===currentPlaylist.id)return!1;const isBuffered=Boolean(findRange(buffered,currentTime).length);if(!currentPlaylist.endList)return isBuffered||"number"!=typeof currentPlaylist.partTargetDuration?(log("".concat(sharedLogLine," as current playlist is live")),!0):(log("not ".concat(sharedLogLine," as current playlist is live llhls, but currentTime isn't in buffered.")),!1);const forwardBuffer=timeAheadOf(buffered,currentTime),maxBufferLowWaterLine=bufferBasedABR?Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:Config.MAX_BUFFER_LOW_WATER_LINE;if(duration<maxBufferLowWaterLine)return log("".concat(sharedLogLine," as duration < max low water line (").concat(duration," < ").concat(maxBufferLowWaterLine,")")),!0;const nextBandwidth=nextPlaylist.attributes.BANDWIDTH,currBandwidth=currentPlaylist.attributes.BANDWIDTH;if(nextBandwidth<currBandwidth&&(!bufferBasedABR||forwardBuffer<bufferHighWaterLine)){let logLine="".concat(sharedLogLine," as next bandwidth < current
bandwidth (").concat(nextBandwidth," < ").concat(currBandwidth,")");return bufferBasedABR&&(logLine+=" and forwardBuffer < bufferHighWaterLine (".concat(forwardBuffer," < ").concat(bufferHighWaterLine,")")),log(logLine),!0}if((!bufferBasedABR||nextBandwidth>currBandwidth)&&forwardBuffer>=bufferLowWaterLine){let logLine="".concat(sharedLogLine," as forwardBuffer >= bufferLowWaterLine (").concat(forwardBuffer," >= ").concat(bufferLowWaterLine,")");return bufferBasedABR&&(logLine+=" and next bandwidth > current bandwidth (".concat(nextBandwidth," > ").concat(currBandwidth,")")),log(logLine),!0}return log("not ".concat(sharedLogLine," as no switching criteria met")),!1}({buffered:this.tech_.buffered(),currentTime:currentTime,currentPlaylist:currentPlaylist,nextPlaylist:nextPlaylist,bufferLowWaterLine:bufferLowWaterLine,bufferHighWaterLine:bufferHighWaterLine,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",
(()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")})),this.mainSegmentLoader_.on("timeout",(()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()})),this.bufferBasedABR||this.mainSegmentLoader_.on("progress",(()=>{this.trigger("progress")})),this.mainSegmentLoader_.on("error",(()=>{const error=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:error.playlist,error:error})})),this.mainSegmentLoader_.on("appenderror",(()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")})),this.mainSegmentLoader_.on("syncinfoupdate",(()=>{this.onSyncInfoUpdate_()})),this.mainSegmentLoader_.on("timestampoffset",(()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})})),this.audioSegmentLoader_.on("syncinfoupdate",(()=>{this.onSyncInfoUpdate_()})),this.audioSegmentLoader_.on("appenderror",(()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")})),this.mainSegmentLoader_.on("ended",(()=>{this.logger_("main segment loader ended"),this.on
EndOfStream()})),this.mainSegmentLoader_.on("earlyabort",(event=>{this.bufferBasedABR||(this.delegateLoaders_("all",["abort"]),this.excludePlaylist({error:{message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},playlistExclusionDuration:10}))}));const updateCodecs=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const codecs=this.getCodecsOrExclude_();codecs&&this.sourceUpdater_.addOrChangeSourceBuffers(codecs)};this.mainSegmentLoader_.on("trackinfo",updateCodecs),this.audioSegmentLoader_.on("trackinfo",updateCodecs),this.mainSegmentLoader_.on("fmp4",(()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)})),this.audioSegmentLoader_.on("fmp4",(()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)})),this.audioSegmentLoader_.on("ended",(()=>{this.logger_("audioSegmentLoader ended"),this.onEndOfStream()})
)}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}fastQualityChange_(){let media=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.selectPlaylist();media&&media===this.mainPlaylistLoader_.media()?this.logger_("skipping fastQualityChange because new media is same as old"):(this.switchMedia_(media,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0)}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything((()=>{this.tech_.setCurrentTime(this.tech_.currentTime())}))}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();const seekable=this.tech_.seekable();return this.tech_
.duration()===1/0&&this.tech_.currentTime()<seekable.start(0)?this.tech_.setCurrentTime(seekable.end(seekable.length-1)):void 0}setupFirstPlay(){const media=this.mainPlaylistLoader_.media();if(!media||this.tech_.paused()||this.hasPlayed_)return!1;if(!media.endList||media.start){const seekable=this.seekable();if(!seekable.length)return!1;const seekableEnd=seekable.end(0);let startPoint=seekableEnd;if(media.start){const offset=media.start.timeOffset;startPoint=offset<0?Math.max(seekableEnd+offset,seekable.start(0)):Math.min(seekableEnd,offset)}this.trigger("firstplay"),this.tech_.setCurrentTime(startPoint)}return this.hasPlayed_=!0,this.load(),!0}handleSourceOpen_(){if(this.tryToCreateSourceBuffers_(),this.tech_.autoplay()){const playPromise=this.tech_.play();void 0!==playPromise&&"function"==typeof playPromise.then&&playPromise.then(null,(e=>{}))}this.trigger("sourceopen")}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;const cues=this.inbandTextTracks_.metadataTrack_.cues;if(!cues||!cue
s.length)return;const duration=this.duration();cues[cues.length-1].endTime=isNaN(duration)||Math.abs(duration)===1/0?Number.MAX_VALUE:duration}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let isEndOfStream=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){const mainMediaInfo=this.mainSegmentLoader_.getCurrentMediaInfo_();isEndOfStream=!mainMediaInfo||mainMediaInfo.hasVideo?isEndOfStream&&this.audioSegmentLoader_.ended_:this.audioSegmentLoader_.ended_}isEndOfStream&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(playlist){if(!this.seekable().length)return!1;const expired=this.syncController_.getExpiredTime(playlist,this.duration());if(null===expired)return!1;const absolutePlaylistEnd=Vhs$1.Playlist.playlistEnd(playlist,expired),currentTime=this.tech_.currentTime(),buffered=this.tech_.buffered();if(!buffered.length)return absolutePlaylistEnd-currentTime<=.1;const bufferedEnd=buffered.end(buffered.length-1);return buffere
dEnd-currentTime<=.1&&absolutePlaylistEnd-bufferedEnd<=.1}excludePlaylist(_ref82){let{playlistToExclude:playlistToExclude=this.mainPlaylistLoader_.media(),error:error={},playlistExclusionDuration:playlistExclusionDuration}=_ref82;if(playlistToExclude=playlistToExclude||this.mainPlaylistLoader_.media(),playlistExclusionDuration=playlistExclusionDuration||error.playlistExclusionDuration||this.playlistExclusionDuration,!playlistToExclude)return this.error=error,void("open"!==this.mediaSource.readyState?this.trigger("error"):this.sourceUpdater_.endOfStream("network"));playlistToExclude.playlistErrors_++;const playlists=this.mainPlaylistLoader_.main.playlists,enabledPlaylists=playlists.filter(isEnabled),isFinalRendition=1===enabledPlaylists.length&&enabledPlaylists[0]===playlistToExclude;if(1===playlists.length&&playlistExclusionDuration!==1/0)return videojs.log.warn("Problem encountered with playlist ".concat(playlistToExclude.id,". ")+"Trying again since it is the only playlist."),this.tech_.trigger("retryplayl
ist"),this.mainPlaylistLoader_.load(isFinalRendition);if(isFinalRendition){if(this.main().contentSteering){const pathway=this.pathwayAttribute_(playlistToExclude),reIncludeDelay=1e3*this.contentSteeringController_.steeringManifest.ttl;return this.contentSteeringController_.excludePathway(pathway),this.excludeThenChangePathway_(),void setTimeout((()=>{this.contentSteeringController_.addAvailablePathway(pathway)}),reIncludeDelay)}let reincluded=!1;playlists.forEach((playlist=>{if(playlist===playlistToExclude)return;const excludeUntil=playlist.excludeUntil;void 0!==excludeUntil&&excludeUntil!==1/0&&(reincluded=!0,delete playlist.excludeUntil)})),reincluded&&(videojs.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),this.tech_.trigger("retryplaylist"))}let excludeUntil;excludeUntil=playlistToExclude.playlistErrors_>this.maxPlaylistRetries?1/0:Date.now()+1e3*playlistExclusionDuration,playlistToExclude.excludeUntil=excludeUntil,error.reason&&(playlistT
oExclude.lastExcludeReason_=error.reason),this.tech_.trigger("excludeplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});const nextPlaylist=this.selectPlaylist();if(!nextPlaylist)return this.error="Playback cannot continue. No available working or supported playlists.",void this.trigger("error");const logFn=error.internal?this.logger_:videojs.log.warn,errorMessage=error.message?" "+error.message:"";logFn("".concat(error.internal?"Internal problem":"Problem"," encountered with playlist ").concat(playlistToExclude.id,".")+"".concat(errorMessage," Switching to playlist ").concat(nextPlaylist.id,".")),nextPlaylist.attributes.AUDIO!==playlistToExclude.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),nextPlaylist.attributes.SUBTITLES!==playlistToExclude.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);const delayDuration=nextPlaylist.targetDuration/2*1e3||5e3,shouldDelay="number"==typeof nextPlaylist.
lastRequest&&Date.now()-nextPlaylist.lastRequest<=delayDuration;return this.switchMedia_(nextPlaylist,"exclude",isFinalRendition||shouldDelay)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(filter,fnNames){const loaders=[],dontFilterPlaylist="all"===filter;(dontFilterPlaylist||"main"===filter)&&loaders.push(this.mainPlaylistLoader_);const mediaTypes=[];(dontFilterPlaylist||"audio"===filter)&&mediaTypes.push("AUDIO"),(dontFilterPlaylist||"subtitle"===filter)&&(mediaTypes.push("CLOSED-CAPTIONS"),mediaTypes.push("SUBTITLES")),mediaTypes.forEach((mediaType=>{const loader=this.mediaTypes_[mediaType]&&this.mediaTypes_[mediaType].activePlaylistLoader;loader&&loaders.push(loader)})),["main","audio","subtitle"].forEach((name=>{const loader=this["".concat(name,"SegmentLoader_")];!loader||filter!==name&&"all"!==filter||loaders.push(loader)})),loaders.forEach((loader=>fnNames.forEach((fnName=>{"function"==typeof loader[fnName]&&loader[fnName]()}))))}setCurrentTime(cur
rentTime){const buffered=findRange(this.tech_.buffered(),currentTime);return this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media()&&this.mainPlaylistLoader_.media().segments?buffered&&buffered.length?currentTime:(this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),void this.load()):0}duration(){if(!this.mainPlaylistLoader_)return 0;const media=this.mainPlaylistLoader_.media();return media?media.endList?this.mediaSource?this.mediaSource.duration:Vhs$1.Playlist.duration(media):1/0:0}seekable(){return this.seekable_}onSyncInfoUpdate_(){let audioSeekable;if(!this.mainPlaylistLoader_)return;let media=this.mainPlaylistLoader_.media();if(!media)return;let expired=this.syncController_.getExpiredTime(media,this.duration());if(null===expire
d)return;const main=this.mainPlaylistLoader_.main,mainSeekable=Vhs$1.Playlist.seekable(media,expired,Vhs$1.Playlist.liveEdgeDelay(main,media));if(0===mainSeekable.length)return;if(this.mediaTypes_.AUDIO.activePlaylistLoader){if(media=this.mediaTypes_.AUDIO.activePlaylistLoader.media(),expired=this.syncController_.getExpiredTime(media,this.duration()),null===expired)return;if(audioSeekable=Vhs$1.Playlist.seekable(media,expired,Vhs$1.Playlist.liveEdgeDelay(main,media)),0===audioSeekable.length)return}let oldEnd,oldStart;this.seekable_&&this.seekable_.length&&(oldEnd=this.seekable_.end(0),oldStart=this.seekable_.start(0)),audioSeekable?audioSeekable.start(0)>mainSeekable.end(0)||mainSeekable.start(0)>audioSeekable.end(0)?this.seekable_=mainSeekable:this.seekable_=createTimeRanges([[audioSeekable.start(0)>mainSeekable.start(0)?audioSeekable.start(0):mainSeekable.start(0),audioSeekable.end(0)<mainSeekable.end(0)?audioSeekable.end(0):mainSeekable.end(0)]]):this.seekable_=mainSeekable,this.seekable_&&this.seekable_
.length&&this.seekable_.end(0)===oldEnd&&this.seekable_.start(0)===oldStart||(this.logger_("seekable updated [".concat(printableRange(this.seekable_),"]")),this.tech_.trigger("seekablechanged"))}updateDuration(isLive){if(this.updateDuration_&&(this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.updateDuration_=null),"open"!==this.mediaSource.readyState)return this.updateDuration_=this.updateDuration.bind(this,isLive),void this.mediaSource.addEventListener("sourceopen",this.updateDuration_);if(isLive){const seekable=this.seekable();if(!seekable.length)return;return void((isNaN(this.mediaSource.duration)||this.mediaSource.duration<seekable.end(seekable.length-1))&&this.sourceUpdater_.setDuration(seekable.end(seekable.length-1)))}const buffered=this.tech_.buffered();let duration=Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());buffered.length>0&&(duration=Math.max(duration,buffered.end(buffered.length-1))),this.mediaSource.duration!==duration&&this.sourceUpdater_.setDuration(du
ration)}dispose(){this.trigger("dispose"),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach((type=>{const groups=this.mediaTypes_[type].groups;for(const id in groups)groups[id].forEach((group=>{group.playlistLoader&&group.playlistLoader.dispose()}))})),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.
mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){const usingAudioLoader=!!this.mediaTypes_.AUDIO.activePlaylistLoader,hasMainMediaInfo=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),hasAudioMediaInfo=!usingAudioLoader||!!this.audioSegmentLoader_.getCurrentMediaInfo_();return!(!hasMainMediaInfo||!hasAudioMediaInfo)}getCodecsOrExclude_(){const media={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},playlist=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();media.video=media.main;const playlistCodecs=codecsForPlaylist(this.main(),playlist),codecs={},usingAudioLoader=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(media.main.hasVideo&&(codecs.video=playlistCodecs.video||media.main.videoCodec||"avc1.4d400d"),media.main.isMuxed&&(codecs.video+=",".concat(playlistCodecs.audio||media.main.audioCodec||"mp4a.40.2")),(media.main.hasAudio&&!media.main.isMuxed||media.audio.hasAudio||usingAudioLoader)&&(codecs.audio=p
laylistCodecs.audio||media.main.audioCodec||media.audio.audioCodec||"mp4a.40.2",media.audio.isFmp4=media.main.hasAudio&&!media.main.isMuxed?media.main.isFmp4:media.audio.isFmp4),!codecs.audio&&!codecs.video)return void this.excludePlaylist({playlistToExclude:playlist,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});const unsupportedCodecs={};let unsupportedAudio;if(["video","audio"].forEach((function(type){if(codecs.hasOwnProperty(type)&&(isFmp4=media[type].isFmp4,codec=codecs[type],!(isFmp4?browserSupportsCodec(codec):muxerSupportsCodec(codec)))){const supporter=media[type].isFmp4?"browser":"muxer";unsupportedCodecs[supporter]=unsupportedCodecs[supporter]||[],unsupportedCodecs[supporter].push(codecs[type]),"audio"===type&&(unsupportedAudio=supporter)}var isFmp4,codec})),usingAudioLoader&&unsupportedAudio&&playlist.attributes.AUDIO){const audioGroup=playlist.attributes.AUDIO;this.main().playlists.forEach((variant=>{(variant.attributes&&variant.attributes.AUDIO)===aud
ioGroup&&variant!==playlist&&(variant.excludeUntil=1/0)})),this.logger_("excluding audio group ".concat(audioGroup," as ").concat(unsupportedAudio,' does not support codec(s): "').concat(codecs.audio,'"'))}if(!Object.keys(unsupportedCodecs).length){if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const switchMessages=[];if(["video","audio"].forEach((type=>{const newCodec=(parseCodecs(this.sourceUpdater_.codecs[type]||"")[0]||{}).type,oldCodec=(parseCodecs(codecs[type]||"")[0]||{}).type;newCodec&&oldCodec&&newCodec.toLowerCase()!==oldCodec.toLowerCase()&&switchMessages.push('"'.concat(this.sourceUpdater_.codecs[type],'" -> "').concat(codecs[type],'"'))})),switchMessages.length)return void this.excludePlaylist({playlistToExclude:playlist,error:{message:"Codec switching not supported: ".concat(switchMessages.join(", "),"."),internal:!0},playlistExclusionDuration:1/0})}return codecs}{const message=Object.keys(unsupportedCodecs).reduce(((acc,supporter)=>(acc&&(acc+=", "),acc
+="".concat(supporter,' does not support codec(s): "').concat(unsupportedCodecs[supporter].join(","),'"'))),"")+".";this.excludePlaylist({playlistToExclude:playlist,error:{internal:!0,message:message},playlistExclusionDuration:1/0})}}tryToCreateSourceBuffers_(){if("open"!==this.mediaSource.readyState||this.sourceUpdater_.hasCreatedSourceBuffers())return;if(!this.areMediaTypesKnown_())return;const codecs=this.getCodecsOrExclude_();if(!codecs)return;this.sourceUpdater_.createSourceBuffers(codecs);const codecString=[codecs.video,codecs.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(codecString)}excludeUnsupportedVariants_(){const playlists=this.main().playlists,ids=[];Object.keys(playlists).forEach((key=>{const variant=playlists[key];if(-1!==ids.indexOf(variant.id))return;ids.push(variant.id);const codecs=codecsForPlaylist(this.main,variant),unsupported=[];!codecs.audio||muxerSupportsCodec(codecs.audio)||browserSupportsCodec(codecs.audio)||unsupported.push("audio codec ".concat(codecs.audio)
),!codecs.video||muxerSupportsCodec(codecs.video)||browserSupportsCodec(codecs.video)||unsupported.push("video codec ".concat(codecs.video)),codecs.text&&"stpp.ttml.im1t"===codecs.text&&unsupported.push("text codec ".concat(codecs.text)),unsupported.length&&(variant.excludeUntil=1/0,this.logger_("excluding ".concat(variant.id," for unsupported: ").concat(unsupported.join(", "))))}))}excludeIncompatibleVariants_(codecString){const ids=[],playlists=this.main().playlists,codecs=unwrapCodecList(parseCodecs(codecString)),codecCount_=codecCount(codecs),videoDetails=codecs.video&&parseCodecs(codecs.video)[0]||null,audioDetails=codecs.audio&&parseCodecs(codecs.audio)[0]||null;Object.keys(playlists).forEach((key=>{const variant=playlists[key];if(-1!==ids.indexOf(variant.id)||variant.excludeUntil===1/0)return;ids.push(variant.id);const exclusionReasons=[],variantCodecs=codecsForPlaylist(this.mainPlaylistLoader_.main,variant),variantCodecCount=codecCount(variantCodecs);if(variantCodecs.audio||variantCodecs.video){if(va
riantCodecCount!==codecCount_&&exclusionReasons.push('codec count "'.concat(variantCodecCount,'" !== "').concat(codecCount_,'"')),!this.sourceUpdater_.canChangeType()){const variantVideoDetails=variantCodecs.video&&parseCodecs(variantCodecs.video)[0]||null,variantAudioDetails=variantCodecs.audio&&parseCodecs(variantCodecs.audio)[0]||null;variantVideoDetails&&videoDetails&&variantVideoDetails.type.toLowerCase()!==videoDetails.type.toLowerCase()&&exclusionReasons.push('video codec "'.concat(variantVideoDetails.type,'" !== "').concat(videoDetails.type,'"')),variantAudioDetails&&audioDetails&&variantAudioDetails.type.toLowerCase()!==audioDetails.type.toLowerCase()&&exclusionReasons.push('audio codec "'.concat(variantAudioDetails.type,'" !== "').concat(audioDetails.type,'"'))}exclusionReasons.length&&(variant.excludeUntil=1/0,this.logger_("excluding ".concat(variant.id,": ").concat(exclusionReasons.join(" && "))))}}))}updateAdCues_(media){let offset=0;const seekable=this.seekable();seekable.length&&(offset=seekab
le.start(0)),function(media,track){let offset=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(!media.segments)return;let cue,mediaTime=offset;for(let i=0;i<media.segments.length;i++){const segment=media.segments[i];if(cue||(cue=findAdCue(track,mediaTime+segment.duration/2)),cue){if("cueIn"in segment){cue.endTime=mediaTime,cue.adEndTime=mediaTime,mediaTime+=segment.duration,cue=null;continue}if(mediaTime<cue.endTime){mediaTime+=segment.duration;continue}cue.endTime+=segment.duration}else if("cueOut"in segment&&(cue=new window.VTTCue(mediaTime,mediaTime+segment.duration,segment.cueOut),cue.adStartTime=mediaTime,cue.adEndTime=mediaTime+parseFloat(segment.cueOut),track.addCue(cue)),"cueOutCont"in segment){const[adOffset,adTotal]=segment.cueOutCont.split("/").map(parseFloat);cue=new window.VTTCue(mediaTime,mediaTime+segment.duration,""),cue.adStartTime=mediaTime-adOffset,cue.adEndTime=cue.adStartTime+adTotal,track.addCue(cue)}mediaTime+=segment.duration}}(media,this.cueTagsTrack_,offset)}goalBufferLen
gth(){const currentTime=this.tech_.currentTime(),initial=Config.GOAL_BUFFER_LENGTH,rate=Config.GOAL_BUFFER_LENGTH_RATE,max=Math.max(initial,Config.MAX_GOAL_BUFFER_LENGTH);return Math.min(initial+currentTime*rate,max)}bufferLowWaterLine(){const currentTime=this.tech_.currentTime(),initial=Config.BUFFER_LOW_WATER_LINE,rate=Config.BUFFER_LOW_WATER_LINE_RATE,max=Math.max(initial,Config.MAX_BUFFER_LOW_WATER_LINE),newMax=Math.max(initial,Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(initial+currentTime*rate,this.bufferBasedABR?newMax:max)}bufferHighWaterLine(){return Config.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(dateRanges){createMetadataTrackIfNotExists(this.inbandTextTracks_,"com.apple.streaming",this.tech_),(_ref64=>{let{inbandTextTracks:inbandTextTracks,dateRanges:dateRanges}=_ref64;const metadataTrack=inbandTextTracks.metadataTrack_;if(!metadataTrack)return;const Cue=window.WebKitDataCue||window.VTTCue;dateRanges.forEach((dateRange=>{for(const key of Object.keys(dateRange)){if(dateR
angeKeysToOmit.has(key))continue;const cue=new Cue(dateRange.startTime,dateRange.endTime,"");cue.id=dateRange.id,cue.type="com.apple.quicktime.HLS",cue.value={key:dateRangeAttr[key],data:dateRange[key]},"scte35Out"!==key&&"scte35In"!==key||(cue.value.data=new Uint8Array(cue.value.data.match(/[\da-f]{2}/gi)).buffer),metadataTrack.addCue(cue)}dateRange.processDateRange()}))})({inbandTextTracks:this.inbandTextTracks_,dateRanges:dateRanges})}addMetadataToTextTrack(dispatchType,metadataArray,videoDuration){const timestampOffset=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();createMetadataTrackIfNotExists(this.inbandTextTracks_,dispatchType,this.tech_),addMetadata({inbandTextTracks:this.inbandTextTracks_,metadataArray:metadataArray,timestampOffset:timestampOffset,videoDuration:videoDuration})}pathwayAttribute_(playlist){return playlist.attributes["PATHWAY-ID"]||playlist.attributes.serviceLocation}initContentSteeringController_(){const main=this
.main();if(main.contentSteering){for(const playlist of main.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(playlist));this.contentSteeringController_.assignTagProperties(main.uri,main.contentSteering),this.contentSteeringController_.queryBeforeStart?this.contentSteeringController_.requestSteeringManifest(!0):this.tech_.one("canplay",(()=>{this.contentSteeringController_.requestSteeringManifest()}))}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on("content-steering",this.excludeThenChangePathway_.bind(this)),"dash"===this.sourceType_&&this.mainPlaylistLoader_.on("loadedplaylist",(()=>{const main=this.main();(this.contentSteeringController_.didDASHTagChange(main.uri,main.contentSteering)||(()=>{const availablePathways=this.contentSteeringController_.getAvailablePathways(),newPathways=
[];for(const playlist of main.playlists){const serviceLocation=playlist.attributes.serviceLocation;if(serviceLocation&&(newPathways.push(serviceLocation),!availablePathways.has(serviceLocation)))return!0}return!(newPathways.length||!availablePathways.size)})())&&this.resetContentSteeringController_()}))}excludeThenChangePathway_(){const currentPathway=this.contentSteeringController_.getPathway();if(!currentPathway)return;this.handlePathwayClones_();const playlists=this.main().playlists,ids=new Set;let didEnablePlaylists=!1;Object.keys(playlists).forEach((key=>{const variant=playlists[key],pathwayId=this.pathwayAttribute_(variant),differentPathwayId=pathwayId&¤tPathway!==pathwayId;variant.excludeUntil===1/0&&"content-steering"===variant.lastExcludeReason_&&!differentPathwayId&&(delete variant.excludeUntil,delete variant.lastExcludeReason_,didEnablePlaylists=!0);const noExcludeUntil=!variant.excludeUntil&&variant.excludeUntil!==1/0;!ids.has(variant.id)&&differentPathwayId&&noExcludeUntil&&(ids.add(varian
t.id),variant.excludeUntil=1/0,variant.lastExcludeReason_="content-steering",this.logger_("excluding ".concat(variant.id," for ").concat(variant.lastExcludeReason_)))})),"DASH"===this.contentSteeringController_.manifestType_&&Object.keys(this.mediaTypes_).forEach((key=>{const type=this.mediaTypes_[key];if(type.activePlaylistLoader){const currentPlaylist=type.activePlaylistLoader.media_;currentPlaylist&¤tPlaylist.attributes.serviceLocation!==currentPathway&&(didEnablePlaylists=!0)}})),didEnablePlaylists&&this.changeSegmentPathway_()}handlePathwayClones_(){const playlists=this.main().playlists,currentPathwayClones=this.contentSteeringController_.currentPathwayClones,nextPathwayClones=this.contentSteeringController_.nextPathwayClones;if(currentPathwayClones&¤tPathwayClones.size||nextPathwayClones&&nextPathwayClones.size){for(const[id,clone]of currentPathwayClones.entries()){nextPathwayClones.get(id)||(this.mainPlaylistLoader_.updateOrDeleteClone(clone),this.contentSteeringController_.excludePathway(
id))}for(const[id,clone]of nextPathwayClones.entries()){const oldClone=currentPathwayClones.get(id);if(oldClone)this.equalPathwayClones_(oldClone,clone)||(this.mainPlaylistLoader_.updateOrDeleteClone(clone,!0),this.contentSteeringController_.addAvailablePathway(id));else{playlists.filter((p=>p.attributes["PATHWAY-ID"]===clone["BASE-ID"])).forEach((p=>{this.mainPlaylistLoader_.addClonePathway(clone,p)})),this.contentSteeringController_.addAvailablePathway(id)}}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...nextPathwayClones])))}}equalPathwayClones_(a,b){if(a["BASE-ID"]!==b["BASE-ID"]||a.ID!==b.ID||a["URI-REPLACEMENT"].HOST!==b["URI-REPLACEMENT"].HOST)return!1;const aParams=a["URI-REPLACEMENT"].PARAMS,bParams=b["URI-REPLACEMENT"].PARAMS;for(const p in aParams)if(aParams[p]!==bParams[p])return!1;for(const p in bParams)if(aParams[p]!==bParams[p])return!1;return!0}changeSegmentPathway_(){const nextPlaylist=this.selectPlaylist();this.pauseLoading(),"DASH"===this.contentS
teeringController_.manifestType_&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(nextPlaylist,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let nonUsableKeyStatusCount=0;this.mainPlaylistLoader_.main.playlists.forEach((playlist=>{const keyIdSet=this.mainPlaylistLoader_.getKeyIdSet(playlist);keyIdSet&&keyIdSet.size&&keyIdSet.forEach((key=>{const hasUsableKeyStatus=this.keyStatusMap_.has(key)&&"usable"===this.keyStatusMap_.get(key),nonUsableExclusion="non-usable"===playlist.lastExcludeReason_&&playlist.excludeUntil===1/0;hasUsableKeyStatus?hasUsableKeyStatus&&nonUsableExclusion&&(delete playlist.excludeUntil,delete playlist.lastExcludeReason_,this.logger_("enabling playlist ".concat(playlist.id," because key ID ").concat(key," is ").concat("usable"))):(playlist.excludeUntil!==1/0&&"non-usable"!==playlist.lastExcludeReason_&&(playlist.excludeUntil=1/0,playlist.lastExcludeReason_="non-usable",this.logger_("excluding playli
st ".concat(playlist.id," because the key ID ").concat(key," doesn't exist in the keyStatusMap or is not ").concat("usable"))),nonUsableKeyStatusCount++)}))})),nonUsableKeyStatusCount>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach((playlist=>{const isNonHD=playlist&&playlist.attributes&&playlist.attributes.RESOLUTION&&playlist.attributes.RESOLUTION.height<720,excludedForNonUsableKey=playlist.excludeUntil===1/0&&"non-usable"===playlist.lastExcludeReason_;isNonHD&&excludedForNonUsableKey&&(delete playlist.excludeUntil,videojs.log.warn("enabling non-HD playlist ".concat(playlist.id," because all playlists were excluded due to ").concat("non-usable"," key IDs")))}))}addKeyStatus_(keyId,status){const formattedKeyIdString=("string"==typeof keyId?keyId:(buffer=>{const uInt8Buffer=new Uint8Array(buffer);return Array.from(uInt8Buffer).map((byte=>byte.toString(16).padStart(2,"0"))).join("")})(keyId)).slice(0,32).toLowerCase();this.logger_("KeyStatus '".concat(status,"'
with key ID ").concat(formattedKeyIdString," added to the keyStatusMap")),this.keyStatusMap_.set(formattedKeyIdString,status)}updatePlaylistByKeyStatus(keyId,status){this.addKeyStatus_(keyId,status),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}}class Representation{constructor(vhsHandler,playlist,id){const{playlistController_:pc}=vhsHandler,qualityChangeFunction=pc.fastQualityChange_.bind(pc);if(playlist.attributes){const resolution=playlist.attributes.RESOLUTION;this.width=resolution&&resolution.width,this.height=resolution&&resolution.height,this.bandwidth=playlist.attributes.BANDWIDTH,this.frameRate=playlist.attributes["FRAME-RATE"]}var loader,playlistID,changePlayl
istFn;this.codecs=codecsForPlaylist(pc.main(),playlist),this.playlist=playlist,this.id=id,this.enabled=(loader=vhsHandler.playlists,playlistID=playlist.id,changePlaylistFn=qualityChangeFunction,enable=>{const playlist=loader.main.playlists[playlistID],incompatible=isIncompatible(playlist),currentlyEnabled=isEnabled(playlist);return void 0===enable?currentlyEnabled:(enable?delete playlist.disabled:playlist.disabled=!0,enable===currentlyEnabled||incompatible||(changePlaylistFn(),enable?loader.trigger("renditionenabled"):loader.trigger("renditiondisabled")),enable)})}}const timerCancelEvents=["seeking","seeked","pause","playing","error"];class PlaybackWatcher{constructor(options){this.playlistController_=options.playlistController,this.tech_=options.tech,this.seekable=options.seekable,this.allowSeeksWithinUnsafeLiveWindow=options.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=options.liveRangeSafeTimeDelta,this.media=options.media,this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurr
entTimeTimeout_=null,this.logger_=logger("PlaybackWatcher"),this.logger_("initialize");const playHandler=()=>this.monitorCurrentTime_(),canPlayHandler=()=>this.monitorCurrentTime_(),waitingHandler=()=>this.techWaiting_(),cancelTimerHandler=()=>this.resetTimeUpdate_(),pc=this.playlistController_,loaderTypes=["main","subtitle","audio"],loaderChecks={};loaderTypes.forEach((type=>{loaderChecks[type]={reset:()=>this.resetSegmentDownloads_(type),updateend:()=>this.checkSegmentDownloads_(type)},pc["".concat(type,"SegmentLoader_")].on("appendsdone",loaderChecks[type].updateend),pc["".concat(type,"SegmentLoader_")].on("playlistupdate",loaderChecks[type].reset),this.tech_.on(["seeked","seeking"],loaderChecks[type].reset)}));const setSeekingHandlers=fn=>{["main","audio"].forEach((type=>{pc["".concat(type,"SegmentLoader_")][fn]("appended",this.seekingAppendCheck_)}))};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),setSeekingHandlers("off"))}
,this.clearSeekingAppendCheck_=()=>setSeekingHandlers("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),setSeekingHandlers("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",waitingHandler),this.tech_.on(timerCancelEvents,cancelTimerHandler),this.tech_.on("canplay",canPlayHandler),this.tech_.one("play",playHandler),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",waitingHandler),this.tech_.off(timerCancelEvents,cancelTimerHandler),this.tech_.off("canplay",canPlayHandler),this.tech_.off("play",playHandler),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),loaderTypes.forEach((type=>{pc["".concat(type,"SegmentLoader_")].off("appendsdone",loaderChecks[type].updateend),pc["".concat(type,"SegmentLoader_")].off("playlistupdate",loaderChecks[type].reset),this.tech_.off(["seeked","seeking"],loaderChecks[type].r
eset)})),this.checkCurrentTimeTimeout_&&window.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&window.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=window.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(type){const loader=this.playlistController_["".concat(type,"SegmentLoader_")];this["".concat(type,"StalledDownloads_")]>0&&this.logger_("resetting possible stalled download count for ".concat(type," loader")),this["".concat(type,"StalledDownloads_")]=0,this["".concat(type,"Buffered_")]=loader.buffered_()}checkSegmentDownloads_(type){const pc=this.playlistController_,loader=pc["".concat(type,"SegmentLoader_")],buffered=loader.buffered_(),isBufferedDifferent=function(a,b){if(a===b)return!1;if(!a&&b||!b&&a)return!0;if(a.length!==b.length)return!0;for(let i=0;i<a.length;i++)if(a.start(i)!==b.start(i)||a.end(i)!==b.end(i))return!0;return!1}(this["".concat(type,"B
uffered_")],buffered);this["".concat(type,"Buffered_")]=buffered,isBufferedDifferent?this.resetSegmentDownloads_(type):(this["".concat(type,"StalledDownloads_")]++,this.logger_("found #".concat(this["".concat(type,"StalledDownloads_")]," ").concat(type," appends that did not increase buffer (possible stalled download)"),{playlistId:loader.playlist_&&loader.playlist_.id,buffered:timeRangesToArray(buffered)}),this["".concat(type,"StalledDownloads_")]<10||(this.logger_("".concat(type," loader stalled download exclusion")),this.resetSegmentDownloads_(type),this.tech_.trigger({type:"usage",name:"vhs-".concat(type,"-download-exclusion")}),"subtitle"!==type&&pc.excludePlaylist({error:{message:"Excessive ".concat(type," segment downloading detected.")},playlistExclusionDuration:1/0})))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;const currentTime=this.tech_.currentTime(),buffered=this.tech_.buffered();if(this.lastRecordedTime===currentTime&&(!buffered.length||currentTime+.1>=buffered.end(
buffered.length-1)))return this.techWaiting_();this.consecutiveUpdates>=5&¤tTime===this.lastRecordedTime?(this.consecutiveUpdates++,this.waiting_()):currentTime===this.lastRecordedTime?this.consecutiveUpdates++:(this.consecutiveUpdates=0,this.lastRecordedTime=currentTime)}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;const seekable=this.seekable(),currentTime=this.tech_.currentTime();let seekTo;if(this.afterSeekableWindow_(seekable,currentTime,this.media(),this.allowSeeksWithinUnsafeLiveWindow)){seekTo=seekable.end(seekable.length-1)}if(this.beforeSeekableWindow_(seekable,currentTime)){const seekableStart=seekable.start(0);seekTo=seekableStart+(seekableStart===seekable.end(0)?0:.1)}if(void 0!==seekTo)return this.logger_("Trying to seek outside of seekable at time ".concat(currentTime," with ")+"seekable range ".concat(printableRange(seekable),". Seeking to ")+"".concat(seekTo,".")),this.tech_.setCurrentTime(seekTo),!0;const sourceUpdater=this.playlistCo
ntroller_.sourceUpdater_,buffered=this.tech_.buffered(),audioBuffered=sourceUpdater.audioBuffer?sourceUpdater.audioBuffered():null,videoBuffered=sourceUpdater.videoBuffer?sourceUpdater.videoBuffered():null,media=this.media(),minAppendedDuration=media.partTargetDuration?media.partTargetDuration:2*(media.targetDuration-.03333333333333333),bufferedToCheck=[audioBuffered,videoBuffered];for(let i=0;i<bufferedToCheck.length;i++){if(!bufferedToCheck[i])continue;if(timeAheadOf(bufferedToCheck[i],currentTime)<minAppendedDuration)return!1}const nextRange=findNextRange(buffered,currentTime);return 0!==nextRange.length&&(seekTo=nextRange.start(0)+.1,this.logger_("Buffered region starts (".concat(nextRange.start(0),") ")+" just beyond seek point (".concat(currentTime,"). Seeking to ").concat(seekTo,".")),this.tech_.setCurrentTime(seekTo),!0)}waiting_(){if(this.techWaiting_())return;const currentTime=this.tech_.currentTime(),buffered=this.tech_.buffered(),currentRange=findRange(buffered,currentTime);return currentRange.le
ngth&¤tTime+3<=currentRange.end(0)?(this.resetTimeUpdate_(),this.tech_.setCurrentTime(currentTime),this.logger_("Stopped at ".concat(currentTime," while inside a buffered region ")+"[".concat(currentRange.start(0)," -> ").concat(currentRange.end(0),"]. Attempting to resume ")+"playback by seeking to the current time."),void this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"})):void 0}techWaiting_(){const seekable=this.seekable(),currentTime=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(seekable,currentTime)){const livePoint=seekable.end(seekable.length-1);return this.logger_("Fell out of live window at time ".concat(currentTime,". Seeking to ")+"live point (seekable end) ".concat(livePoint)),this.resetTimeUpdate_(),this.tech_.setCurrentTime(livePoint),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}const sourceUpdater=this.tech_.vhs.playlistController_.sourceUpdater_,buffered=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:sou
rceUpdater.audioBuffered(),videoBuffered:sourceUpdater.videoBuffered(),currentTime:currentTime}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(currentTime),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;const nextRange=findNextRange(buffered,currentTime);return nextRange.length>0&&(this.logger_("Stopped at ".concat(currentTime," and seeking to ").concat(nextRange.start(0))),this.resetTimeUpdate_(),this.skipTheGap_(currentTime),!0)}afterSeekableWindow_(seekable,currentTime,playlist){let allowSeeksWithinUnsafeLiveWindow=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!seekable.length)return!1;let allowedEnd=seekable.end(seekable.length-1)+.1;const isLive=!playlist.endList,isLLHLS="number"==typeof playlist.partTargetDuration;return isLive&&(isLLHLS||allowSeeksWithinUnsafeLiveWindow)&&(allowedEnd=seekable.end(seekable.length-1)+3*playlist.targetDuration),currentTime>allowedEnd}beforeSeekableWindow_(seekable,currentTime){return!!(seekable.length&&seekable.start(0)>0&¤
tTime<seekable.start(0)-this.liveRangeSafeTimeDelta)}videoUnderflow_(_ref83){let gap,{videoBuffered:videoBuffered,audioBuffered:audioBuffered,currentTime:currentTime}=_ref83;if(videoBuffered){if(videoBuffered.length&&audioBuffered.length){const lastVideoRange=findRange(videoBuffered,currentTime-3),videoRange=findRange(videoBuffered,currentTime),audioRange=findRange(audioBuffered,currentTime);audioRange.length&&!videoRange.length&&lastVideoRange.length&&(gap={start:lastVideoRange.end(0),end:audioRange.end(0)})}else{findNextRange(videoBuffered,currentTime).length||(gap=this.gapFromVideoUnderflow_(videoBuffered,currentTime))}return!!gap&&(this.logger_("Encountered a gap in video from ".concat(gap.start," to ").concat(gap.end,". ")+"Seeking to current time ".concat(currentTime)),!0)}}skipTheGap_(scheduledCurrentTime){const buffered=this.tech_.buffered(),currentTime=this.tech_.currentTime(),nextRange=findNextRange(buffered,currentTime);this.resetTimeUpdate_(),0!==nextRange.length&¤tTime===scheduledCurrentTi
me&&(this.logger_("skipTheGap_:","currentTime:",currentTime,"scheduled currentTime:",scheduledCurrentTime,"nextRange start:",nextRange.start(0)),this.tech_.setCurrentTime(nextRange.start(0)+.03333333333333333),this.tech_.trigger({type:"usage",name:"vhs-gap-skip"}))}gapFromVideoUnderflow_(buffered,currentTime){const gaps=function(buffered){if(buffered.length<2)return createTimeRanges();const ranges=[];for(let i=1;i<buffered.length;i++){const start=buffered.end(i-1),end=buffered.start(i);ranges.push([start,end])}return createTimeRanges(ranges)}(buffered);for(let i=0;i<gaps.length;i++){const start=gaps.start(i),end=gaps.end(i);if(currentTime-start<4&¤tTime-start>2)return{start:start,end:end}}return null}}const defaultOptions={errorInterval:30,getSource(next){return next(this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource())}},initPlugin=function(player,options){let lastCalled=0,seekTo=0;const localOptions=merge(defaultOptions,options);player.ready((()=>{player.trigger({type:"usage"
,name:"vhs-error-reload-initialized"})}));const loadedMetadataHandler=function(){seekTo&&player.currentTime(seekTo)},setSource=function(sourceObj){null!=sourceObj&&(seekTo=player.duration()!==1/0&&player.currentTime()||0,player.one("loadedmetadata",loadedMetadataHandler),player.src(sourceObj),player.trigger({type:"usage",name:"vhs-error-reload"}),player.play())},errorHandler=function(){if(Date.now()-lastCalled<1e3*localOptions.errorInterval)player.trigger({type:"usage",name:"vhs-error-reload-canceled"});else{if(localOptions.getSource&&"function"==typeof localOptions.getSource)return lastCalled=Date.now(),localOptions.getSource.call(player,setSource);videojs.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!")}},cleanupEvents=function(){player.off("loadedmetadata",loadedMetadataHandler),player.off("error",errorHandler),player.off("dispose",cleanupEvents)};player.on("error",errorHandler),player.on("dispose",cleanupEvents),player.reloadSourceOnError=function(newOptions){cleanupEven
ts(),initPlugin(player,newOptions)}},reloadSourceOnError=function(options){initPlugin(this,options)};const Vhs={PlaylistLoader:PlaylistLoader,Playlist:Playlist,utils:utils,STANDARD_PLAYLIST_SELECTOR:lastBandwidthSelector,INITIAL_PLAYLIST_SELECTOR:function(){const playlists=this.playlists.main.playlists.filter(Playlist.isEnabled);stableSort(playlists,((a,b)=>comparePlaylistBandwidth(a,b)));return playlists.filter((playlist=>!!codecsForPlaylist(this.playlists.main,playlist).video))[0]||null},lastBandwidthSelector:lastBandwidthSelector,movingAverageBandwidthSelector:function(decay){let average=-1,lastSystemBandwidth=-1;if(decay<0||decay>1)throw new Error("Moving average bandwidth decay must be between 0 and 1.");return function(){const pixelRatio=this.useDevicePixelRatio&&window.devicePixelRatio||1;return average<0&&(average=this.systemBandwidth,lastSystemBandwidth=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==lastSystemBandwidth&&(average=decay*this.systemBandwidth+(1-decay)*average,last
SystemBandwidth=this.systemBandwidth),simpleSelector(this.playlists.main,average,parseInt(safeGetComputedStyle(this.tech_.el(),"width"),10)*pixelRatio,parseInt(safeGetComputedStyle(this.tech_.el(),"height"),10)*pixelRatio,this.limitRenditionByPlayerDimensions,this.playlistController_)}},comparePlaylistBandwidth:comparePlaylistBandwidth,comparePlaylistResolution:function(left,right){let leftWidth,rightWidth;return left.attributes.RESOLUTION&&left.attributes.RESOLUTION.width&&(leftWidth=left.attributes.RESOLUTION.width),leftWidth=leftWidth||window.Number.MAX_VALUE,right.attributes.RESOLUTION&&right.attributes.RESOLUTION.width&&(rightWidth=right.attributes.RESOLUTION.width),rightWidth=rightWidth||window.Number.MAX_VALUE,leftWidth===rightWidth&&left.attributes.BANDWIDTH&&right.attributes.BANDWIDTH?left.attributes.BANDWIDTH-right.attributes.BANDWIDTH:leftWidth-rightWidth},xhr:xhrFactory()};Object.keys(Config).forEach((prop=>{Object.defineProperty(Vhs,prop,{get:()=>(videojs.log.warn("using Vhs.".concat(prop," is U
NSAFE be sure you know what you are doing")),Config[prop]),set(value){videojs.log.warn("using Vhs.".concat(prop," is UNSAFE be sure you know what you are doing")),"number"!=typeof value||value<0?videojs.log.warn("value of Vhs.".concat(prop," must be greater than or equal to 0")):Config[prop]=value}})}));const handleVhsMediaChange=function(qualityLevels,playlistLoader){const newPlaylist=playlistLoader.media();let selectedIndex=-1;for(let i=0;i<qualityLevels.length;i++)if(qualityLevels[i].id===newPlaylist.id){selectedIndex=i;break}qualityLevels.selectedIndex_=selectedIndex,qualityLevels.trigger({selectedIndex:selectedIndex,type:"change"})};Vhs.canPlaySource=function(){return videojs.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const waitForKeySessionCreation=_ref84=>{let{player:player,sourceKeySystems:sourceKeySystems,audioMedia:audioMedia,mainPlaylists:mainPlaylists}=_ref84;if(!player.eme.initializeMediaKeys)return Promise.resolve();const keySystemsOptionsArr=((playlist
s,keySystems)=>playlists.reduce(((keySystemsArr,playlist)=>{if(!playlist.contentProtection)return keySystemsArr;const keySystemsOptions=keySystems.reduce(((keySystemsObj,keySystem)=>{const keySystemOptions=playlist.contentProtection[keySystem];return keySystemOptions&&keySystemOptions.pssh&&(keySystemsObj[keySystem]={pssh:keySystemOptions.pssh}),keySystemsObj}),{});return Object.keys(keySystemsOptions).length&&keySystemsArr.push(keySystemsOptions),keySystemsArr}),[]))(audioMedia?mainPlaylists.concat([audioMedia]):mainPlaylists,Object.keys(sourceKeySystems)),initializationFinishedPromises=[],keySessionCreatedPromises=[];return keySystemsOptionsArr.forEach((keySystemsOptions=>{keySessionCreatedPromises.push(new Promise(((resolve,reject)=>{player.tech_.one("keysessioncreated",resolve)}))),initializationFinishedPromises.push(new Promise(((resolve,reject)=>{player.eme.initializeMediaKeys({keySystems:keySystemsOptions},(err=>{err?reject(err):resolve()}))})))})),Promise.race([Promise.all(initializationFinishedPromi
ses),Promise.race(keySessionCreatedPromises)])},setupEmeOptions=_ref85=>{let{player:player,sourceKeySystems:sourceKeySystems,media:media,audioMedia:audioMedia}=_ref85;const sourceOptions=((keySystemOptions,mainPlaylist,audioPlaylist)=>{if(!keySystemOptions)return keySystemOptions;let codecs={};mainPlaylist&&mainPlaylist.attributes&&mainPlaylist.attributes.CODECS&&(codecs=unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS))),audioPlaylist&&audioPlaylist.attributes&&audioPlaylist.attributes.CODECS&&(codecs.audio=audioPlaylist.attributes.CODECS);const videoContentType=getMimeForCodec(codecs.video),audioContentType=getMimeForCodec(codecs.audio),keySystemContentTypes={};for(const keySystem in keySystemOptions)keySystemContentTypes[keySystem]={},audioContentType&&(keySystemContentTypes[keySystem].audioContentType=audioContentType),videoContentType&&(keySystemContentTypes[keySystem].videoContentType=videoContentType),mainPlaylist.contentProtection&&mainPlaylist.contentProtection[keySystem]&&mainPlaylist.con
tentProtection[keySystem].pssh&&(keySystemContentTypes[keySystem].pssh=mainPlaylist.contentProtection[keySystem].pssh),"string"==typeof keySystemOptions[keySystem]&&(keySystemContentTypes[keySystem].url=keySystemOptions[keySystem]);return merge(keySystemOptions,keySystemContentTypes)})(sourceKeySystems,media,audioMedia);return!!sourceOptions&&(player.currentSource().keySystems=sourceOptions,!(sourceOptions&&!player.eme)||(videojs.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1))},getVhsLocalStorage=()=>{if(!window.localStorage)return null;const storedObject=window.localStorage.getItem("videojs-vhs");if(!storedObject)return null;try{return JSON.parse(storedObject)}catch(e){return null}},addOnRequestHook=(xhr,callback)=>{xhr._requestCallbackSet||(xhr._requestCallbackSet=new Set),xhr._requestCallbackSet.add(callback)},addOnResponseHook=(xhr,callback)=>{xhr._responseCallbackSet||(xhr._responseCallbackSet=new Set),xhr._responseCallbackSet.add(callback)},removeOnRequestHook=(xhr,callba
ck)=>{xhr._requestCallbackSet&&(xhr._requestCallbackSet.delete(callback),xhr._requestCallbackSet.size||delete xhr._requestCallbackSet)},removeOnResponseHook=(xhr,callback)=>{xhr._responseCallbackSet&&(xhr._responseCallbackSet.delete(callback),xhr._responseCallbackSet.size||delete xhr._responseCallbackSet)};Vhs.supportsNativeHls=function(){if(!document||!document.createElement)return!1;const video=document.createElement("video");if(!videojs.getTech("Html5").isSupported())return!1;return["application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"].some((function(canItPlay){return/maybe|probably/i.test(video.canPlayType(canItPlay))}))}(),Vhs.supportsNativeDash=!!(document&&document.createElement&&videojs.getTech("Html5").isSupported())&&/maybe|probably/i.test(document.createElement("video").canPlayType("application/dash+xml")),Vhs.supportsTypeNatively=type=>"hls"===type?Vhs.supportsNativeHls:"dash"===type&&Vhs.supportsNativeDa
sh,Vhs.isSupported=function(){return videojs.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")},Vhs.xhr.onRequest=function(callback){addOnRequestHook(Vhs.xhr,callback)},Vhs.xhr.onResponse=function(callback){addOnResponseHook(Vhs.xhr,callback)},Vhs.xhr.offRequest=function(callback){removeOnRequestHook(Vhs.xhr,callback)},Vhs.xhr.offResponse=function(callback){removeOnResponseHook(Vhs.xhr,callback)};const Component=videojs.getComponent("Component");class VhsHandler extends Component{constructor(source,tech,options){if(super(tech,options.vhs),"number"==typeof options.initialBandwidth&&(this.options_.bandwidth=options.initialBandwidth),this.logger_=logger("VhsHandler"),tech.options_&&tech.options_.playerId){const _player=videojs.getPlayer(tech.options_.playerId);this.player_=_player}if(this.tech_=tech,this.source_=source,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&tech.overrideNativeAudioTracks&&tech.overrideNativeVideoTracks)tec
h.overrideNativeAudioTracks(!0),tech.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(tech.featuresNativeVideoTracks||tech.featuresNativeAudioTracks))throw new Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on(document,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],(event=>{const fullscreenElement=document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement;fullscreenElement&&fullscreenElement.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()})),this.on(this.tech_,"seeking",(function(){this.ignoreNextSeekingEvent_?this.ignoreNextSeekingEvent_=!1:this.setCurrentTime(this.tech_.currentTime())})),this.on(this.tech_,"error",(function(){this.tech_.error()&&this.playlistController_&&this.playlistController_.pauseLoading()})),this.on(this.tech_,"play",this.play)}setOptions_(){let options=arguments
.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.options_=merge(this.options_,options),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=!1!==this.options_.limitRenditionByPlayerDimensions,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.useBandwidthFromLocalStorage=void 0!==this.source_.useBandwidthFromLocalStorage?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=this.options_.useNetworkInformationApi||!1,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=!1!==this.options_.llhls,this.options_.bufferBasedAB
R=this.options_.bufferBasedABR||!1,"number"!=typeof this.options_.playlistExclusionDuration&&(this.options_.playlistExclusionDuration=60),"number"!=typeof this.options_.bandwidth&&this.options_.useBandwidthFromLocalStorage){const storedObject=getVhsLocalStorage();storedObject&&storedObject.bandwidth&&(this.options_.bandwidth=storedObject.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),storedObject&&storedObject.throughput&&(this.options_.throughput=storedObject.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"}))}"number"!=typeof this.options_.bandwidth&&(this.options_.bandwidth=Config.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===Config.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR
","liveRangeSafeTimeDelta","llhls","useForcedSubtitles","useNetworkInformationApi","useDtsForTimestampOffset","exactManifestTimings","leastPixelDiffSelector"].forEach((option=>{void 0!==this.source_[option]&&(this.options_[option]=this.source_[option])})),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio}setOptions(){let options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.setOptions_(options)}src(src,type){if(!src)return;var dataUri;this.setOptions_(),this.options_.src=0===(dataUri=this.source_.src).toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")?JSON.parse(dataUri.substring(dataUri.indexOf(",")+1)):dataUri,this.options_.tech=this.tech_,this.options_.externVhs=Vhs,this.options_.sourceType=simpleTypeFromSourceType(type),this.options_.seekTo=time=>{this.tech_.setCurrentTime(time)},this.playlistController_=new PlaylistController(this.options_);const playbackWatcherOptions=merge({liveR
angeSafeTimeDelta:.1},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new PlaybackWatcher(playbackWatcherOptions),this.playlistController_.on("error",(()=>{const player=videojs.players[this.tech_.options_.playerId];let error=this.playlistController_.error;"object"!=typeof error||error.code?"string"==typeof error&&(error={message:error,code:3}):error.code=3,player.error(error)}));const defaultSelector=this.options_.bufferBasedABR?Vhs.movingAverageBandwidthSelector(.55):Vhs.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):defaultSelector.bind(this),this.playlistController_.selectInitialPlaylist=Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPl
aylist},set(selectPlaylist){this.playlistController_.selectPlaylist=selectPlaylist.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(throughput){this.playlistController_.mainSegmentLoader_.throughput.rate=throughput,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let playerBandwidthEst=this.playlistController_.mainSegmentLoader_.bandwidth;const networkInformation=window.navigator.connection||window.navigator.mozConnection||window.navigator.webkitConnection;if(this.options_.useNetworkInformationApi&&networkInformation){const networkInfoBandwidthEstBitsPerSec=1e3*networkInformation.downlink*1e3;playerBandwidthEst=networkInfoBandwidthEstBitsPerSec>=1e7&&playerBandwidthEst>=1e7?Math.max(playerBandwidthEst,networkInfoBandwidthEstBitsPerSec):networkInfoBandwidthEstBitsPerSec}return playerBandwidthEst},set(bandwidth){this.playlistController_.mainSegmentLoader_.bandwidth=bandwidth,this.playlistController_.mainSegmentLoader_.throug
hput={rate:0,count:0}}},systemBandwidth:{get(){const invBandwidth=1/(this.bandwidth||1);let invThroughput;invThroughput=this.throughput>0?1/this.throughput:0;return Math.floor(1/(invBandwidth+invThroughput))},set(){videojs.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playl
istController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>timeRangesToArray(this.tech_.buffered()),enumerable:!0},currentTime:{get:()=>this.tech_.currentTime(),enumerable:!0},currentSource:{get:()=>this.tech_.currentSource_,enumerable:!0},currentTech:{get:()=>this.tech_.name_,enumerable:!0},duration:{get:()=>this.tech_.duration(),enumerable:!0},main:{get:()=>this.playlists.main,enumerable:!0},playerDimensions:{get:()=>this.tech_.curren
tDimensions(),enumerable:!0},seekable:{get:()=>timeRangesToArray(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one("canplay",this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on("bandwidthupdate",(()=>{this.options_.useBandwidthFromLocalStorage&&(options=>{if(!window.localStorage)return!1;let objectToStore=getVhsLocalStorage();objectToStore=objectToStore?merge(objectToStore,options):options;try{window.localStorage.setItem("videojs-vhs",JSON.stringify(objectToStore))}catch(e){return!1}})({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})})),this.playlistController_.on("selectedinitialmedia",(()=>{var vhsHandler;(vhsHandler=this).representations=()=>{const main=vhsHandler.playlistController_.main(),playlists=isAudioOnly(main)?vhsHandler.playlistController_.getAudioTrackPlaylists_():main.playlists;return playlists?playlists.filter((m
edia=>!isIncompatible(media))).map(((e,i)=>new Representation(vhsHandler,e,e.id))):[]}})),this.playlistController_.sourceUpdater_.on("createdsourcebuffers",(()=>{this.setupEme_()})),this.on(this.playlistController_,"progress",(function(){this.tech_.trigger("progress")})),this.on(this.playlistController_,"firstplay",(function(){this.ignoreNextSeekingEvent_=!0})),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=window.URL.createObjectURL(this.playlistController_.mediaSource),this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const audioPlaylistLoader=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),waitForKeySessionCreation({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:audioPlaylistLoader&&audioPlaylistLoader.media(),mainPlaylists:this.playlists.main.playlists}).then((()=>{this.logger_("created EME key session"),this.playlistController_.sourceUpdater_.initializedEme()})).catch((err=>{this.log
ger_("error while creating EME key session",err),this.player_.error({message:"Failed to initialize media keys for EME",code:3})}))}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){const audioPlaylistLoader=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,didSetupEmeOptions=setupEmeOptions({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:audioPlaylistLoader&&audioPlaylistLoader.media()});this.player_.tech_.on("keystatuschange",(e=>{this.playlistController_.updatePlaylistByKeyStatus(e.keyId,e.status)})),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),didSetupEmeOptions?this.createKeySessions_():this.playlistController_.sourceUpdater_.initializedEme()}setupQualityLevels_(){const player=videojs.players[this.tech_.options_.playerId];player&&player.qualityLevels&&!this.qualityLev
els_&&(this.qualityLevels_=player.qualityLevels(),this.playlistController_.on("selectedinitialmedia",(()=>{var qualityLevels,vhs;qualityLevels=this.qualityLevels_,(vhs=this).representations().forEach((rep=>{qualityLevels.addQualityLevel(rep)})),handleVhsMediaChange(qualityLevels,vhs.playlists)})),this.playlists.on("mediachange",(()=>{handleVhsMediaChange(this.qualityLevels_,this.playlists)})))}static version(){return{"@videojs/http-streaming":"3.10.0","mux.js":"7.0.2","mpd-parser":"1.3.0","m3u8-parser":"7.1.0","aes-decrypter":"4.0.1"}}version(){return this.constructor.version()}canChangeType(){return SourceUpdater.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(currentTime){this.playlistController_.setCurrentTime(currentTime)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.quali
tyLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&window.URL.revokeObjectURL&&(window.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(time,callback){return getProgramTime({playlist:this.playlistController_.media(),time:time,callback:callback})}seekToProgramTime(programTime,callback){let pauseAfterSeek=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],retryCount=arguments.length>3&&void 0!==arguments[3]?arguments[3]:2;return seekToProgramTime({programTime:programTime,playlist:this.playlistController_.media(),retryCount:retryCount,pauseAfterSeek:pauseAfterSeek,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:callback})}setupXhrHooks_(){this.xhr.onRequest=callback=>{addOnRequestHook(this.xhr,callback)},this.xhr.onResponse=callback=>{addOnResponseHook(this.xhr,callback)},this.xhr.offRequest=callback=>{removeOnRequestHook(thi
s.xhr,callback)},this.xhr.offResponse=callback=>{removeOnResponseHook(this.xhr,callback)},this.player_.trigger("xhr-hooks-ready")}}const VhsSourceHandler={name:"videojs-http-streaming",VERSION:"3.10.0",canHandleSource(srcObj){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const localOptions=merge(videojs.options,options);return VhsSourceHandler.canPlayType(srcObj.type,localOptions)},handleSource(source,tech){let options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const localOptions=merge(videojs.options,options);return tech.vhs=new VhsHandler(source,tech,localOptions),tech.vhs.xhr=xhrFactory(),tech.vhs.setupXhrHooks_(),tech.vhs.src(source.src,source.type),tech.vhs},canPlayType(type,options){const simpleType=simpleTypeFromSourceType(type);if(!simpleType)return"";const overrideNative=VhsSourceHandler.getOverrideNative(options);return!Vhs.supportsTypeNatively(simpleType)||overrideNative?"maybe":""},getOverrideNative(){let options=arguments.length>0&&void 0!==arguments[0]?arg
uments[0]:{};const{vhs:vhs={}}=options,defaultOverrideNative=!(videojs.browser.IS_ANY_SAFARI||videojs.browser.IS_IOS),{overrideNative:overrideNative=defaultOverrideNative}=vhs;return overrideNative}};return browserSupportsCodec("avc1.4d400d,mp4a.40.2")&&videojs.getTech("Html5").registerSourceHandler(VhsSourceHandler,0),videojs.VhsHandler=VhsHandler,videojs.VhsSourceHandler=VhsSourceHandler,videojs.Vhs=Vhs,videojs.use||videojs.registerComponent("Vhs",Vhs),videojs.options.vhs=videojs.options.vhs||{},videojs.getPlugin&&videojs.getPlugin("reloadSourceOnError")||videojs.registerPlugin("reloadSourceOnError",reloadSourceOnError),videojs}));
//# sourceMappingURL=video-lazy.min.js.map