
(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global=global||self,global.videojs=factory());}(this,(function(){'use strict';var version="7.11.4";var commonjsGlobal=typeof globalThis!=='undefined'?globalThis:typeof window!=='undefined'?window:typeof global!=='undefined'?global:typeof self!=='undefined'?self:{};function unwrapExports(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,'default')?x['default']:x;}
function createCommonjsModule(fn,module){return module={exports:{}},fn(module,module.exports),module.exports;}
var win;if(typeof window!=="undefined"){win=window;}else if(typeof commonjsGlobal!=="undefined"){win=commonjsGlobal;}else if(typeof self!=="undefined"){win=self;}else{win={};}
var window_1=win;var minDoc={};var topLevel=typeof commonjsGlobal!=='undefined'?commonjsGlobal:typeof window!=='undefined'?window:{};var doccy;if(typeof document!=='undefined'){doccy=document;}else{doccy=topLevel['__GLOBAL_DOCUMENT_CACHE@4'];if(!doccy){doccy=topLevel['__GLOBAL_DOCUMENT_CACHE@4']=minDoc;}}
var document_1=doccy;var history=[];var LogByTypeFactory=function LogByTypeFactory(name,log){return function(type,level,args){var lvl=log.levels[level];var lvlRegExp=new RegExp("^("+lvl+")$");if(type!=='log'){args.unshift(type.toUpperCase()+':');}
args.unshift(name+':');if(history){history.push([].concat(args));var splice=history.length-1000;history.splice(0,splice>0?splice:0);}
if(!window_1.console){return;}
var fn=window_1.console[type];if(!fn&&type==='debug'){fn=window_1.console.info||window_1.console.log;}
if(!fn||!lvl||!lvlRegExp.test(type)){return;}
fn[Array.isArray(args)?'apply':'call'](window_1.console,args);};};function createLogger(name){var level='info';var logByType;var log=function log(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}
logByType('log',level,args);};logByType=LogByTypeFactory(name,log);log.createLogger=function(subname){return createLogger(name+': '+subname);};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=function(lvl){if(typeof lvl==='string'){if(!log.levels.hasOwnProperty(lvl)){throw new Error("\""+lvl+"\" in not a valid log level");}
level=lvl;}
return level;};log.history=function(){return history?[].concat(history):[];};log.history.filter=function(fname){return(history||[]).filter(function(historyItem){return new RegExp(".*"+fname+".*").test(historyItem[0]);});};log.history.clear=function(){if(history){history.length=0;}};log.history.disable=function(){if(history!==null){history.length=0;history=null;}};log.history.enable=function(){if(history===null){history=[];}};log.error=function(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2];}
return logByType('error',level,args);};log.warn=function(){for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3];}
return logByType('warn',level,args);};log.debug=function(){for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4];}
return logByType('debug',level,args);};return log;}
var log=createLogger('VIDEOJS');var createLogger$1=log.createLogger;var _extends_1=createCommonjsModule(function(module){function _extends(){module.exports=_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}
return target;};return _extends.apply(this,arguments);}
module.exports=_extends;});var toString=Object.prototype.toString;var keys=function keys(object){return isObject(object)?Object.keys(object):[];};function each(object,fn){keys(object).forEach(function(key){return fn(object[key],key);});}
function reduce(object,fn,initial){if(initial===void 0){initial=0;}
return keys(object).reduce(function(accum,key){return fn(accum,object[key],key);},initial);}
function assign(target){for(var _len=arguments.length,sources=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){sources[_key-1]=arguments[_key];}
if(Object.assign){return _extends_1.apply(void 0,[target].concat(sources));}
sources.forEach(function(source){if(!source){return;}
each(source,function(value,key){target[key]=value;});});return target;}
function isObject(value){return!!value&&typeof value==='object';}
function isPlain(value){return isObject(value)&&toString.call(value)==='[object Object]'&&value.constructor===Object;}
function computedStyle(el,prop){if(!el||!prop){return'';}
if(typeof window_1.getComputedStyle==='function'){var computedStyleValue=window_1.getComputedStyle(el);return computedStyleValue?computedStyleValue.getPropertyValue(prop)||computedStyleValue[prop]:'';}
return'';}
function isNonBlankString(str){return typeof str==='string'&&Boolean(str.trim());}
function throwIfWhitespace(str){if(str.indexOf(' ')>=0){throw new Error('class has illegal whitespace characters');}}
function classRegExp(className){return new RegExp('(^|\\s)'+className+'($|\\s)');}
function isReal(){return document_1===window_1.document;}
function isEl(value){return isObject(value)&&value.nodeType===1;}
function isInFrame(){try{return window_1.parent!==window_1.self;}catch(x){return true;}}
function createQuerier(method){return function(selector,context){if(!isNonBlankString(selector)){return document_1[method](null);}
if(isNonBlankString(context)){context=document_1.querySelector(context);}
var ctx=isEl(context)?context:document_1;return ctx[method]&&ctx[method](selector);};}
function createEl(tagName,properties,attributes,content){if(tagName===void 0){tagName='div';}
if(properties===void 0){properties={};}
if(attributes===void 0){attributes={};}
var el=document_1.createElement(tagName);Object.getOwnPropertyNames(properties).forEach(function(propName){var val=properties[propName];if(propName.indexOf('aria-')!==-1||propName==='role'||propName==='type'){log.warn('Setting attributes in the second argument of createEl()\n'+'has been deprecated. Use the third argument instead.\n'+("createEl(type, properties, attributes). Attempting to set "+propName+" to "+val+"."));el.setAttribute(propName,val);}else if(propName==='textContent'){textContent(el,val);}else if(el[propName]!==val||propName==='tabIndex'){el[propName]=val;}});Object.getOwnPropertyNames(attributes).forEach(function(attrName){el.setAttribute(attrName,attributes[attrName]);});if(content){appendContent(el,content);}
return el;}
function textContent(el,text){if(typeof el.textContent==='undefined'){el.innerText=text;}else{el.textContent=text;}
return el;}
function prependTo(child,parent){if(parent.firstChild){parent.insertBefore(child,parent.firstChild);}else{parent.appendChild(child);}}
function hasClass(element,classToCheck){throwIfWhitespace(classToCheck);if(element.classList){return element.classList.contains(classToCheck);}
return classRegExp(classToCheck).test(element.className);}
function addClass(element,classToAdd){if(element.classList){element.classList.add(classToAdd);}else if(!hasClass(element,classToAdd)){element.className=(element.className+' '+classToAdd).trim();}
return element;}
function removeClass(element,classToRemove){if(element.classList){element.classList.remove(classToRemove);}else{throwIfWhitespace(classToRemove);element.className=element.className.split(/\s+/).filter(function(c){return c!==classToRemove;}).join(' ');}
return element;}
function toggleClass(element,classToToggle,predicate){var has=hasClass(element,classToToggle);if(typeof predicate==='function'){predicate=predicate(element,classToToggle);}
if(typeof predicate!=='boolean'){predicate=!has;}
if(predicate===has){return;}
if(predicate){addClass(element,classToToggle);}else{removeClass(element,classToToggle);}
return element;}
function setAttributes(el,attributes){Object.getOwnPropertyNames(attributes).forEach(function(attrName){var attrValue=attributes[attrName];if(attrValue===null||typeof attrValue==='undefined'||attrValue===false){el.removeAttribute(attrName);}else{el.setAttribute(attrName,attrValue===true?'':attrValue);}});}
function getAttributes(tag){var obj={};var knownBooleans=','+'autoplay,controls,playsinline,loop,muted,default,defaultMuted'+',';if(tag&&tag.attributes&&tag.attributes.length>0){var attrs=tag.attributes;for(var i=attrs.length-1;i>=0;i--){var attrName=attrs[i].name;var attrVal=attrs[i].value;if(typeof tag[attrName]==='boolean'||knownBooleans.indexOf(','+attrName+',')!==-1){attrVal=attrVal!==null?true:false;}
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_1.body.focus();document_1.onselectstart=function(){return false;};}
function unblockTextSelection(){document_1.onselectstart=function(){return true;};}
function getBoundingClientRect(el){if(el&&el.getBoundingClientRect&&el.parentNode){var rect=el.getBoundingClientRect();var result={};['bottom','height','left','right','top','width'].forEach(function(k){if(rect[k]!==undefined){result[k]=rect[k];}});if(!result.height){result.height=parseFloat(computedStyle(el,'height'));}
if(!result.width){result.width=parseFloat(computedStyle(el,'width'));}
return result;}}
function findPosition(el){if(!el||el&&!el.offsetParent){return{left:0,top:0,width:0,height:0};}
var width=el.offsetWidth;var height=el.offsetHeight;var left=0;var top=0;do{left+=el.offsetLeft;top+=el.offsetTop;el=el.offsetParent;}while(el);return{left:left,top:top,width:width,height:height};}
function getPointerPosition(el,event){var position={};var boxTarget=findPosition(event.target);var box=findPosition(el);var boxW=box.width;var boxH=box.height;var offsetY=event.offsetY-(box.top-boxTarget.top);var offsetX=event.offsetX-(box.left-boxTarget.left);if(event.changedTouches){offsetX=event.changedTouches[0].pageX-box.left;offsetY=event.changedTouches[0].pageY+box.top;}
position.y=1-Math.max(0,Math.min(1,offsetY/boxH));position.x=Math.max(0,Math.min(1,offsetX/boxW));return position;}
function isTextNode(value){return isObject(value)&&value.nodeType===3;}
function emptyEl(el){while(el.firstChild){el.removeChild(el.firstChild);}
return el;}
function normalizeContent(content){if(typeof content==='function'){content=content();}
return(Array.isArray(content)?content:[content]).map(function(value){if(typeof value==='function'){value=value();}
if(isEl(value)||isTextNode(value)){return value;}
if(typeof value==='string'&&/\S/.test(value)){return document_1.createTextNode(value);}}).filter(function(value){return value;});}
function appendContent(el,content){normalizeContent(content).forEach(function(node){return el.appendChild(node);});return el;}
function insertContent(el,content){return appendContent(emptyEl(el),content);}
function isSingleLeftClick(event){if(event.button===undefined&&event.buttons===undefined){return true;}
if(event.button===0&&event.buttons===undefined){return true;}
if(event.type==='mouseup'&&event.button===0&&event.buttons===0){return true;}
if(event.button!==0||event.buttons!==1){return false;}
return true;}
var $=createQuerier('querySelector');var $$=createQuerier('querySelectorAll');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,emptyEl:emptyEl,normalizeContent:normalizeContent,appendContent:appendContent,insertContent:insertContent,isSingleLeftClick:isSingleLeftClick,$:$,$$:$$});var _windowLoaded=false;var videojs;var autoSetup=function autoSetup(){if(!isReal()||videojs.options.autoSetup===false){return;}
var vids=Array.prototype.slice.call(document_1.getElementsByTagName('video'));var audios=Array.prototype.slice.call(document_1.getElementsByTagName('audio'));var divs=Array.prototype.slice.call(document_1.getElementsByTagName('video-js'));var mediaEls=vids.concat(audios,divs);if(mediaEls&&mediaEls.length>0){for(var i=0,e=mediaEls.length;i<e;i++){var mediaEl=mediaEls[i];if(mediaEl&&mediaEl.getAttribute){if(mediaEl.player===undefined){var options=mediaEl.getAttribute('data-setup');if(options!==null){videojs(mediaEl);}}}else{autoSetupTimeout(1);break;}}}else if(!_windowLoaded){autoSetupTimeout(1);}};function autoSetupTimeout(wait,vjs){if(vjs){videojs=vjs;}
window_1.setTimeout(autoSetup,wait);}
function setWindowLoaded(){_windowLoaded=true;window_1.removeEventListener('load',setWindowLoaded);}
if(isReal()){if(document_1.readyState==='complete'){setWindowLoaded();}else{window_1.addEventListener('load',setWindowLoaded);}}
var createStyleElement=function createStyleElement(className){var style=document_1.createElement('style');style.className=className;return style;};var setTextContent=function setTextContent(el,content){if(el.styleSheet){el.styleSheet.cssText=content;}else{el.textContent=content;}};var _initialGuid=3;var _guid=_initialGuid;function newGUID(){return _guid++;}
var FakeWeakMap;if(!window_1.WeakMap){FakeWeakMap=function(){function FakeWeakMap(){this.vdata='vdata'+Math.floor(window_1.performance&&window_1.performance.now()||Date.now());this.data={};}
var _proto=FakeWeakMap.prototype;_proto.set=function set(key,value){var access=key[this.vdata]||newGUID();if(!key[this.vdata]){key[this.vdata]=access;}
this.data[access]=value;return this;};_proto.get=function get(key){var access=key[this.vdata];if(access){return this.data[access];}
log('We have no data for this element',key);return undefined;};_proto.has=function has(key){var access=key[this.vdata];return access in this.data;};_proto["delete"]=function _delete(key){var access=key[this.vdata];if(access){delete this.data[access];delete key[this.vdata];}};return FakeWeakMap;}();}
var DomData=window_1.WeakMap?new WeakMap():new FakeWeakMap();function _cleanUpEvents(elem,type){if(!DomData.has(elem)){return;}
var data=DomData.get(elem);if(data.handlers[type].length===0){delete data.handlers[type];if(elem.removeEventListener){elem.removeEventListener(type,data.dispatcher,false);}else if(elem.detachEvent){elem.detachEvent('on'+type,data.dispatcher);}}
if(Object.getOwnPropertyNames(data.handlers).length<=0){delete data.handlers;delete data.dispatcher;delete data.disabled;}
if(Object.getOwnPropertyNames(data).length===0){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 true;}
function returnFalse(){return false;}
if(!event||!event.isPropagationStopped){var old=event||window_1.event;event={};for(var key in old){if(key!=='layerX'&&key!=='layerY'&&key!=='keyLocation'&&key!=='webkitMovementX'&&key!=='webkitMovementY'){if(!(key==='returnValue'&&old.preventDefault)){event[key]=old[key];}}}
if(!event.target){event.target=event.srcElement||document_1;}
if(!event.relatedTarget){event.relatedTarget=event.fromElement===event.target?event.toElement:event.fromElement;}
event.preventDefault=function(){if(old.preventDefault){old.preventDefault();}
event.returnValue=false;old.returnValue=false;event.defaultPrevented=true;};event.defaultPrevented=false;event.stopPropagation=function(){if(old.stopPropagation){old.stopPropagation();}
event.cancelBubble=true;old.cancelBubble=true;event.isPropagationStopped=returnTrue;};event.isPropagationStopped=returnFalse;event.stopImmediatePropagation=function(){if(old.stopImmediatePropagation){old.stopImmediatePropagation();}
event.isImmediatePropagationStopped=returnTrue;event.stopPropagation();};event.isImmediatePropagationStopped=returnFalse;if(event.clientX!==null&&event.clientX!==undefined){var doc=document_1.documentElement;var body=document_1.body;event.pageX=event.clientX+(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;if(event.button!==null&&event.button!==undefined){event.button=event.button&1?0:event.button&4?1:event.button&2?2:0;}}
event.fixed_=true;return event;}
var _supportsPassive;var supportsPassive=function supportsPassive(){if(typeof _supportsPassive!=='boolean'){_supportsPassive=false;try{var opts=Object.defineProperty({},'passive',{get:function get(){_supportsPassive=true;}});window_1.addEventListener('test',null,opts);window_1.removeEventListener('test',null,opts);}catch(e){}}
return _supportsPassive;};var passiveEvents=['touchstart','touchmove'];function on(elem,type,fn){if(Array.isArray(type)){return _handleMultipleEvents(on,elem,type,fn);}
if(!DomData.has(elem)){DomData.set(elem,{});}
var data=DomData.get(elem);if(!data.handlers){data.handlers={};}
if(!data.handlers[type]){data.handlers[type]=[];}
if(!fn.guid){fn.guid=newGUID();}
data.handlers[type].push(fn);if(!data.dispatcher){data.disabled=false;data.dispatcher=function(event,hash){if(data.disabled){return;}
event=fixEvent(event);var handlers=data.handlers[event.type];if(handlers){var handlersCopy=handlers.slice(0);for(var m=0,n=handlersCopy.length;m<n;m++){if(event.isImmediatePropagationStopped()){break;}else{try{handlersCopy[m].call(elem,event,hash);}catch(e){log.error(e);}}}}};}
if(data.handlers[type].length===1){if(elem.addEventListener){var options=false;if(supportsPassive()&&passiveEvents.indexOf(type)>-1){options={passive:true};}
elem.addEventListener(type,data.dispatcher,options);}else if(elem.attachEvent){elem.attachEvent('on'+type,data.dispatcher);}}}
function off(elem,type,fn){if(!DomData.has(elem)){return;}
var data=DomData.get(elem);if(!data.handlers){return;}
if(Array.isArray(type)){return _handleMultipleEvents(off,elem,type,fn);}
var removeType=function removeType(el,t){data.handlers[t]=[];_cleanUpEvents(el,t);};if(type===undefined){for(var t in data.handlers){if(Object.prototype.hasOwnProperty.call(data.handlers||{},t)){removeType(elem,t);}}
return;}
var handlers=data.handlers[type];if(!handlers){return;}
if(!fn){removeType(elem,type);return;}
if(fn.guid){for(var n=0;n<handlers.length;n++){if(handlers[n].guid===fn.guid){handlers.splice(n--,1);}}}
_cleanUpEvents(elem,type);}
function trigger(elem,event,hash){var elemData=DomData.has(elem)?DomData.get(elem):{};var parent=elem.parentNode||elem.ownerDocument;if(typeof event==='string'){event={type:event,target:elem};}else if(!event.target){event.target=elem;}
event=fixEvent(event);if(elemData.dispatcher){elemData.dispatcher.call(elem,event,hash);}
if(parent&&!event.isPropagationStopped()&&event.bubbles===true){trigger.call(null,parent,event,hash);}else if(!parent&&!event.defaultPrevented&&event.target&&event.target[event.type]){if(!DomData.has(event.target)){DomData.set(event.target,{});}
var targetData=DomData.get(event.target);if(event.target[event.type]){targetData.disabled=true;if(typeof event.target[event.type]==='function'){event.target[event.type]();}
targetData.disabled=false;}}
return!event.defaultPrevented;}
function one(elem,type,fn){if(Array.isArray(type)){return _handleMultipleEvents(one,elem,type,fn);}
var func=function func(){off(elem,type,func);fn.apply(this,arguments);};func.guid=fn.guid=fn.guid||newGUID();on(elem,type,func);}
function any(elem,type,fn){var func=function func(){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});var UPDATE_REFRESH_INTERVAL=30;var bind=function bind(context,fn,uid){if(!fn.guid){fn.guid=newGUID();}
var bound=fn.bind(context);bound.guid=uid?uid+'_'+fn.guid:fn.guid;return bound;};var throttle=function throttle(fn,wait){var last=window_1.performance.now();var throttled=function throttled(){var now=window_1.performance.now();if(now-last>=wait){fn.apply(void 0,arguments);last=now;}};return throttled;};var debounce=function debounce(func,wait,immediate,context){if(context===void 0){context=window_1;}
var timeout;var cancel=function cancel(){context.clearTimeout(timeout);timeout=null;};var debounced=function debounced(){var self=this;var args=arguments;var _later=function later(){timeout=null;_later=null;if(!immediate){func.apply(self,args);}};if(!timeout&&immediate){func.apply(self,args);}
context.clearTimeout(timeout);timeout=context.setTimeout(_later,wait);};debounced.cancel=cancel;return debounced;};var EventTarget=function EventTarget(){};EventTarget.prototype.allowedEvents_={};EventTarget.prototype.on=function(type,fn){var ael=this.addEventListener;this.addEventListener=function(){};on(this,type,fn);this.addEventListener=ael;};EventTarget.prototype.addEventListener=EventTarget.prototype.on;EventTarget.prototype.off=function(type,fn){off(this,type,fn);};EventTarget.prototype.removeEventListener=EventTarget.prototype.off;EventTarget.prototype.one=function(type,fn){var ael=this.addEventListener;this.addEventListener=function(){};one(this,type,fn);this.addEventListener=ael;};EventTarget.prototype.any=function(type,fn){var ael=this.addEventListener;this.addEventListener=function(){};any(this,type,fn);this.addEventListener=ael;};EventTarget.prototype.trigger=function(event){var type=event.type||event;if(typeof event==='string'){event={type:type};}
event=fixEvent(event);if(this.allowedEvents_[type]&&this['on'+type]){this['on'+type](event);}
trigger(this,event);};EventTarget.prototype.dispatchEvent=EventTarget.prototype.trigger;var EVENT_MAP;EventTarget.prototype.queueTrigger=function(event){var _this=this;if(!EVENT_MAP){EVENT_MAP=new Map();}
var type=event.type||event;var map=EVENT_MAP.get(this);if(!map){map=new Map();EVENT_MAP.set(this,map);}
var oldTimeout=map.get(type);map["delete"](type);window_1.clearTimeout(oldTimeout);var timeout=window_1.setTimeout(function(){if(map.size===0){map=null;EVENT_MAP["delete"](_this);}
_this.trigger(event);},0);map.set(type,timeout);};var objName=function objName(obj){if(typeof obj.name==='function'){return obj.name();}
if(typeof obj.name==='string'){return obj.name;}
if(obj.name_){return obj.name_;}
if(obj.constructor&&obj.constructor.name){return obj.constructor.name;}
return typeof obj;};var isEvented=function isEvented(object){return object instanceof EventTarget||!!object.eventBusEl_&&['on','one','off','trigger'].every(function(k){return typeof object[k]==='function';});};var addEventedCallback=function addEventedCallback(target,callback){if(isEvented(target)){callback();}else{if(!target.eventedCallbacks){target.eventedCallbacks=[];}
target.eventedCallbacks.push(callback);}};var isValidEventType=function isValidEventType(type){return(typeof type==='string'&&/\S/.test(type)||Array.isArray(type)&&!!type.length);};var validateTarget=function validateTarget(target,obj,fnName){if(!target||!target.nodeName&&!isEvented(target)){throw new Error("Invalid target for "+objName(obj)+"#"+fnName+"; must be a DOM node or evented object.");}};var validateEventType=function validateEventType(type,obj,fnName){if(!isValidEventType(type)){throw new Error("Invalid event type for "+objName(obj)+"#"+fnName+"; must be a non-empty string or array.");}};var validateListener=function validateListener(listener,obj,fnName){if(typeof listener!=='function'){throw new Error("Invalid listener for "+objName(obj)+"#"+fnName+"; must be a function.");}};var normalizeListenArgs=function normalizeListenArgs(self,args,fnName){var isTargetingSelf=args.length<3||args[0]===self||args[0]===self.eventBusEl_;var target;var type;var listener;if(isTargetingSelf){target=self.eventBusEl_;if(args.length>=3){args.shift();}
type=args[0];listener=args[1];}else{target=args[0];type=args[1];listener=args[2];}
validateTarget(target,self,fnName);validateEventType(type,self,fnName);validateListener(listener,self,fnName);listener=bind(self,listener);return{isTargetingSelf:isTargetingSelf,target:target,type:type,listener:listener};};var listen=function listen(target,method,type,listener){validateTarget(target,target,method);if(target.nodeName){Events[method](target,type,listener);}else{target[method](type,listener);}};var EventedMixin={on:function on(){var _this=this;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}
var _normalizeListenArgs=normalizeListenArgs(this,args,'on'),isTargetingSelf=_normalizeListenArgs.isTargetingSelf,target=_normalizeListenArgs.target,type=_normalizeListenArgs.type,listener=_normalizeListenArgs.listener;listen(target,'on',type,listener);if(!isTargetingSelf){var removeListenerOnDispose=function removeListenerOnDispose(){return _this.off(target,type,listener);};removeListenerOnDispose.guid=listener.guid;var removeRemoverOnTargetDispose=function removeRemoverOnTargetDispose(){return _this.off('dispose',removeListenerOnDispose);};removeRemoverOnTargetDispose.guid=listener.guid;listen(this,'on','dispose',removeListenerOnDispose);listen(target,'on','dispose',removeRemoverOnTargetDispose);}},one:function one(){var _this2=this;for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2];}
var _normalizeListenArgs2=normalizeListenArgs(this,args,'one'),isTargetingSelf=_normalizeListenArgs2.isTargetingSelf,target=_normalizeListenArgs2.target,type=_normalizeListenArgs2.type,listener=_normalizeListenArgs2.listener;if(isTargetingSelf){listen(target,'one',type,listener);}else{var wrapper=function wrapper(){_this2.off(target,type,wrapper);for(var _len3=arguments.length,largs=new Array(_len3),_key3=0;_key3<_len3;_key3++){largs[_key3]=arguments[_key3];}
listener.apply(null,largs);};wrapper.guid=listener.guid;listen(target,'one',type,wrapper);}},any:function any(){var _this3=this;for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4];}
var _normalizeListenArgs3=normalizeListenArgs(this,args,'any'),isTargetingSelf=_normalizeListenArgs3.isTargetingSelf,target=_normalizeListenArgs3.target,type=_normalizeListenArgs3.type,listener=_normalizeListenArgs3.listener;if(isTargetingSelf){listen(target,'any',type,listener);}else{var wrapper=function wrapper(){_this3.off(target,type,wrapper);for(var _len5=arguments.length,largs=new Array(_len5),_key5=0;_key5<_len5;_key5++){largs[_key5]=arguments[_key5];}
listener.apply(null,largs);};wrapper.guid=listener.guid;listen(target,'any',type,wrapper);}},off:function off$1(targetOrType,typeOrListener,listener){if(!targetOrType||isValidEventType(targetOrType)){off(this.eventBusEl_,targetOrType,typeOrListener);}else{var target=targetOrType;var type=typeOrListener;validateTarget(target,this,'off');validateEventType(type,this,'off');validateListener(listener,this,'off');listener=bind(this,listener);this.off('dispose',listener);if(target.nodeName){off(target,type,listener);off(target,'dispose',listener);}else if(isEvented(target)){target.off(type,listener);target.off('dispose',listener);}}},trigger:function trigger$1(event,hash){validateTarget(this.eventBusEl_,this,'trigger');var type=event&&typeof event!=='string'?event.type:event;if(!isValidEventType(type)){var error="Invalid event type for "+objName(this)+"#trigger; "+'must be a non-empty string or object with a type key that has a non-empty value.';if(event){(this.log||log).error(error);}else{throw new Error(error);}}
return trigger(this.eventBusEl_,event,hash);}};function evented(target,options){if(options===void 0){options={};}
var _options=options,eventBusKey=_options.eventBusKey;if(eventBusKey){if(!target[eventBusKey].nodeName){throw new Error("The eventBusKey \""+eventBusKey+"\" does not refer to an element.");}
target.eventBusEl_=target[eventBusKey];}else{target.eventBusEl_=createEl('span',{className:'vjs-event-bus'});}
assign(target,EventedMixin);if(target.eventedCallbacks){target.eventedCallbacks.forEach(function(callback){callback();});}
target.on('dispose',function(){target.off();window_1.setTimeout(function(){target.eventBusEl_=null;},0);});return target;}
var StatefulMixin={state:{},setState:function setState(stateUpdates){var _this=this;if(typeof stateUpdates==='function'){stateUpdates=stateUpdates();}
var changes;each(stateUpdates,function(value,key){if(_this.state[key]!==value){changes=changes||{};changes[key]={from:_this.state[key],to:value};}
_this.state[key]=value;});if(changes&&isEvented(this)){this.trigger({changes:changes,type:'statechanged'});}
return changes;}};function stateful(target,defaultState){assign(target,StatefulMixin);target.state=assign({},target.state,defaultState);if(typeof target.handleStateChanged==='function'&&isEvented(target)){target.on('statechanged',target.handleStateChanged);}
return target;}
var toLowerCase=function toLowerCase(string){if(typeof string!=='string'){return string;}
return string.replace(/./,function(w){return w.toLowerCase();});};var toTitleCase=function toTitleCase(string){if(typeof string!=='string'){return string;}
return string.replace(/./,function(w){return w.toUpperCase();});};var titleCaseEquals=function titleCaseEquals(str1,str2){return toTitleCase(str1)===toTitleCase(str2);};function mergeOptions(){var result={};for(var _len=arguments.length,sources=new Array(_len),_key=0;_key<_len;_key++){sources[_key]=arguments[_key];}
sources.forEach(function(source){if(!source){return;}
each(source,function(value,key){if(!isPlain(value)){result[key]=value;return;}
if(!isPlain(result[key])){result[key]={};}
result[key]=mergeOptions(result[key],value);});});return result;}
var MapSham=function(){function MapSham(){this.map_={};}
var _proto=MapSham.prototype;_proto.has=function has(key){return key in this.map_;};_proto["delete"]=function _delete(key){var has=this.has(key);delete this.map_[key];return has;};_proto.set=function set(key,value){this.map_[key]=value;return this;};_proto.forEach=function forEach(callback,thisArg){for(var key in this.map_){callback.call(thisArg,this.map_[key],key,this);}};return MapSham;}();var Map$1=window_1.Map?window_1.Map:MapSham;var SetSham=function(){function SetSham(){this.set_={};}
var _proto=SetSham.prototype;_proto.has=function has(key){return key in this.set_;};_proto["delete"]=function _delete(key){var has=this.has(key);delete this.set_[key];return has;};_proto.add=function add(key){this.set_[key]=1;return this;};_proto.forEach=function forEach(callback,thisArg){for(var key in this.set_){callback.call(thisArg,key,key,this);}};return SetSham;}();var Set=window_1.Set?window_1.Set:SetSham;var Component=function(){function Component(player,options,ready){if(!player&&this.play){this.player_=player=this;}else{this.player_=player;}
this.isDisposed_=false;this.parentComponent_=null;this.options_=mergeOptions({},this.options_);options=this.options_=mergeOptions(this.options_,options);this.id_=options.id||options.el&&options.el.id;if(!this.id_){var id=player&&player.id&&player.id()||'no_player';this.id_=id+"_component_"+newGUID();}
this.name_=options.name||null;if(options.el){this.el_=options.el;}else if(options.createEl!==false){this.el_=this.createEl();}
if(options.evented!==false){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$1();this.clearingTimersOnDispose_=false;if(options.initChildren!==false){this.initChildren();}
this.ready(ready);if(options.reportTouchActivity!==false){this.enableTouchActivity();}}
var _proto=Component.prototype;_proto.dispose=function dispose(){if(this.isDisposed_){return;}
if(this.readyQueue_){this.readyQueue_.length=0;}
this.trigger({type:'dispose',bubbles:false});this.isDisposed_=true;if(this.children_){for(var i=this.children_.length-1;i>=0;i--){if(this.children_[i].dispose){this.children_[i].dispose();}}}
this.children_=null;this.childIndex_=null;this.childNameIndex_=null;this.parentComponent_=null;if(this.el_){if(this.el_.parentNode){this.el_.parentNode.removeChild(this.el_);}
if(DomData.has(this.el_)){DomData["delete"](this.el_);}
this.el_=null;}
this.player_=null;};_proto.isDisposed=function isDisposed(){return Boolean(this.isDisposed_);};_proto.player=function player(){return this.player_;};_proto.options=function options(obj){if(!obj){return this.options_;}
this.options_=mergeOptions(this.options_,obj);return this.options_;};_proto.el=function el(){return this.el_;};_proto.createEl=function createEl$1(tagName,properties,attributes){return createEl(tagName,properties,attributes);};_proto.localize=function localize(string,tokens,defaultValue){if(defaultValue===void 0){defaultValue=string;}
var code=this.player_.language&&this.player_.language();var languages=this.player_.languages&&this.player_.languages();var language=languages&&languages[code];var primaryCode=code&&code.split('-')[0];var primaryLang=languages&&languages[primaryCode];var localizedString=defaultValue;if(language&&language[string]){localizedString=language[string];}else if(primaryLang&&primaryLang[string]){localizedString=primaryLang[string];}
if(tokens){localizedString=localizedString.replace(/\{(\d+)\}/g,function(match,index){var value=tokens[index-1];var ret=value;if(typeof value==='undefined'){ret=match;}
return ret;});}
return localizedString;};_proto.handleLanguagechange=function handleLanguagechange(){};_proto.contentEl=function contentEl(){return this.contentEl_||this.el_;};_proto.id=function id(){return this.id_;};_proto.name=function name(){return this.name_;};_proto.children=function children(){return this.children_;};_proto.getChildById=function getChildById(id){return this.childIndex_[id];};_proto.getChild=function getChild(name){if(!name){return;}
return this.childNameIndex_[name];};_proto.getDescendant=function getDescendant(){for(var _len=arguments.length,names=new Array(_len),_key=0;_key<_len;_key++){names[_key]=arguments[_key];}
names=names.reduce(function(acc,n){return acc.concat(n);},[]);var currentChild=this;for(var i=0;i<names.length;i++){currentChild=currentChild.getChild(names[i]);if(!currentChild||!currentChild.getChild){return;}}
return currentChild;};_proto.addChild=function addChild(child,options,index){if(options===void 0){options={};}
if(index===void 0){index=this.children_.length;}
var component;var componentName;if(typeof child==='string'){componentName=toTitleCase(child);var componentClassName=options.componentClass||componentName;options.name=componentName;var ComponentClass=Component.getComponent(componentClassName);if(!ComponentClass){throw new Error("Component "+componentClassName+" does not exist");}
if(typeof ComponentClass!=='function'){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;if(typeof component.id==='function'){this.childIndex_[component.id()]=component;}
componentName=componentName||component.name&&toTitleCase(component.name());if(componentName){this.childNameIndex_[componentName]=component;this.childNameIndex_[toLowerCase(componentName)]=component;}
if(typeof component.el==='function'&&component.el()){var refNode=null;if(this.children_[index+1]){if(this.children_[index+1].el_){refNode=this.children_[index+1].el_;}else if(isEl(this.children_[index+1])){refNode=this.children_[index+1];}}
this.contentEl().insertBefore(component.el(),refNode);}
return component;};_proto.removeChild=function removeChild(component){if(typeof component==='string'){component=this.getChild(component);}
if(!component||!this.children_){return;}
var childFound=false;for(var i=this.children_.length-1;i>=0;i--){if(this.children_[i]===component){childFound=true;this.children_.splice(i,1);break;}}
if(!childFound){return;}
component.parentComponent_=null;this.childIndex_[component.id()]=null;this.childNameIndex_[toTitleCase(component.name())]=null;this.childNameIndex_[toLowerCase(component.name())]=null;var compEl=component.el();if(compEl&&compEl.parentNode===this.contentEl()){this.contentEl().removeChild(component.el());}};_proto.initChildren=function initChildren(){var _this=this;var children=this.options_.children;if(children){var parentOptions=this.options_;var handleAdd=function handleAdd(child){var name=child.name;var opts=child.opts;if(parentOptions[name]!==undefined){opts=parentOptions[name];}
if(opts===false){return;}
if(opts===true){opts={};}
opts.playerOptions=_this.options_.playerOptions;var newChild=_this.addChild(name,opts);if(newChild){_this[name]=newChild;}};var workingChildren;var Tech=Component.getComponent('Tech');if(Array.isArray(children)){workingChildren=children;}else{workingChildren=Object.keys(children);}
workingChildren.concat(Object.keys(this.options_).filter(function(child){return!workingChildren.some(function(wchild){if(typeof wchild==='string'){return child===wchild;}
return child===wchild.name;});})).map(function(child){var name;var opts;if(typeof child==='string'){name=child;opts=children[name]||_this.options_[name]||{};}else{name=child.name;opts=child;}
return{name:name,opts:opts};}).filter(function(child){var c=Component.getComponent(child.opts.componentClass||toTitleCase(child.name));return c&&!Tech.isTech(c);}).forEach(handleAdd);}};_proto.buildCSSClass=function buildCSSClass(){return'';};_proto.ready=function ready(fn,sync){if(sync===void 0){sync=false;}
if(!fn){return;}
if(!this.isReady_){this.readyQueue_=this.readyQueue_||[];this.readyQueue_.push(fn);return;}
if(sync){fn.call(this);}else{this.setTimeout(fn,1);}};_proto.triggerReady=function triggerReady(){this.isReady_=true;this.setTimeout(function(){var readyQueue=this.readyQueue_;this.readyQueue_=[];if(readyQueue&&readyQueue.length>0){readyQueue.forEach(function(fn){fn.call(this);},this);}
this.trigger('ready');},1);};_proto.$=function $$1(selector,context){return $(selector,context||this.contentEl());};_proto.$$=function $$$1(selector,context){return $$(selector,context||this.contentEl());};_proto.hasClass=function hasClass$1(classToCheck){return hasClass(this.el_,classToCheck);};_proto.addClass=function addClass$1(classToAdd){addClass(this.el_,classToAdd);};_proto.removeClass=function removeClass$1(classToRemove){removeClass(this.el_,classToRemove);};_proto.toggleClass=function toggleClass$1(classToToggle,predicate){toggleClass(this.el_,classToToggle,predicate);};_proto.show=function show(){this.removeClass('vjs-hidden');};_proto.hide=function hide(){this.addClass('vjs-hidden');};_proto.lockShowing=function lockShowing(){this.addClass('vjs-lock-showing');};_proto.unlockShowing=function unlockShowing(){this.removeClass('vjs-lock-showing');};_proto.getAttribute=function getAttribute$1(attribute){return getAttribute(this.el_,attribute);};_proto.setAttribute=function setAttribute$1(attribute,value){setAttribute(this.el_,attribute,value);};_proto.removeAttribute=function removeAttribute$1(attribute){removeAttribute(this.el_,attribute);};_proto.width=function width(num,skipListeners){return this.dimension('width',num,skipListeners);};_proto.height=function height(num,skipListeners){return this.dimension('height',num,skipListeners);};_proto.dimensions=function dimensions(width,height){this.width(width,true);this.height(height);};_proto.dimension=function dimension(widthOrHeight,num,skipListeners){if(num!==undefined){if(num===null||num!==num){num=0;}
if((''+num).indexOf('%')!==-1||(''+num).indexOf('px')!==-1){this.el_.style[widthOrHeight]=num;}else if(num==='auto'){this.el_.style[widthOrHeight]='';}else{this.el_.style[widthOrHeight]=num+'px';}
if(!skipListeners){this.trigger('componentresize');}
return;}
if(!this.el_){return 0;}
var val=this.el_.style[widthOrHeight];var pxIndex=val.indexOf('px');if(pxIndex!==-1){return parseInt(val.slice(0,pxIndex),10);}
return parseInt(this.el_['offset'+toTitleCase(widthOrHeight)],10);};_proto.currentDimension=function currentDimension(widthOrHeight){var computedWidthOrHeight=0;if(widthOrHeight!=='width'&&widthOrHeight!=='height'){throw new Error('currentDimension only accepts width or height value');}
computedWidthOrHeight=computedStyle(this.el_,widthOrHeight);computedWidthOrHeight=parseFloat(computedWidthOrHeight);if(computedWidthOrHeight===0||isNaN(computedWidthOrHeight)){var rule="offset"+toTitleCase(widthOrHeight);computedWidthOrHeight=this.el_[rule];}
return computedWidthOrHeight;};_proto.currentDimensions=function currentDimensions(){return{width:this.currentDimension('width'),height:this.currentDimension('height')};};_proto.currentWidth=function currentWidth(){return this.currentDimension('width');};_proto.currentHeight=function currentHeight(){return this.currentDimension('height');};_proto.focus=function focus(){this.el_.focus();};_proto.blur=function blur(){this.el_.blur();};_proto.handleKeyDown=function handleKeyDown(event){if(this.player_){event.stopPropagation();this.player_.handleKeyDown(event);}};_proto.handleKeyPress=function handleKeyPress(event){this.handleKeyDown(event);};_proto.emitTapEvents=function emitTapEvents(){var touchStart=0;var firstTouch=null;var tapMovementThreshold=10;var touchTimeThreshold=200;var couldBeTap;this.on('touchstart',function(event){if(event.touches.length===1){firstTouch={pageX:event.touches[0].pageX,pageY:event.touches[0].pageY};touchStart=window_1.performance.now();couldBeTap=true;}});this.on('touchmove',function(event){if(event.touches.length>1){couldBeTap=false;}else if(firstTouch){var xdiff=event.touches[0].pageX-firstTouch.pageX;var ydiff=event.touches[0].pageY-firstTouch.pageY;var touchDistance=Math.sqrt(xdiff*xdiff+ydiff*ydiff);if(touchDistance>tapMovementThreshold){couldBeTap=false;}}});var noTap=function noTap(){couldBeTap=false;};this.on('touchleave',noTap);this.on('touchcancel',noTap);this.on('touchend',function(event){firstTouch=null;if(couldBeTap===true){var touchTime=window_1.performance.now()-touchStart;if(touchTime<touchTimeThreshold){event.preventDefault();this.trigger('tap');}}});};_proto.enableTouchActivity=function enableTouchActivity(){if(!this.player()||!this.player().reportUserActivity){return;}
var report=bind(this.player(),this.player().reportUserActivity);var touchHolding;this.on('touchstart',function(){report();this.clearInterval(touchHolding);touchHolding=this.setInterval(report,250);});var touchEnd=function touchEnd(event){report();this.clearInterval(touchHolding);};this.on('touchmove',report);this.on('touchend',touchEnd);this.on('touchcancel',touchEnd);};_proto.setTimeout=function setTimeout(fn,timeout){var _this2=this;var timeoutId;fn=bind(this,fn);this.clearTimersOnDispose_();timeoutId=window_1.setTimeout(function(){if(_this2.setTimeoutIds_.has(timeoutId)){_this2.setTimeoutIds_["delete"](timeoutId);}
fn();},timeout);this.setTimeoutIds_.add(timeoutId);return timeoutId;};_proto.clearTimeout=function clearTimeout(timeoutId){if(this.setTimeoutIds_.has(timeoutId)){this.setTimeoutIds_["delete"](timeoutId);window_1.clearTimeout(timeoutId);}
return timeoutId;};_proto.setInterval=function setInterval(fn,interval){fn=bind(this,fn);this.clearTimersOnDispose_();var intervalId=window_1.setInterval(fn,interval);this.setIntervalIds_.add(intervalId);return intervalId;};_proto.clearInterval=function clearInterval(intervalId){if(this.setIntervalIds_.has(intervalId)){this.setIntervalIds_["delete"](intervalId);window_1.clearInterval(intervalId);}
return intervalId;};_proto.requestAnimationFrame=function requestAnimationFrame(fn){var _this3=this;if(!this.supportsRaf_){return this.setTimeout(fn,1000/60);}
this.clearTimersOnDispose_();var id;fn=bind(this,fn);id=window_1.requestAnimationFrame(function(){if(_this3.rafIds_.has(id)){_this3.rafIds_["delete"](id);}
fn();});this.rafIds_.add(id);return id;};_proto.requestNamedAnimationFrame=function requestNamedAnimationFrame(name,fn){var _this4=this;if(this.namedRafs_.has(name)){return;}
this.clearTimersOnDispose_();fn=bind(this,fn);var id=this.requestAnimationFrame(function(){fn();if(_this4.namedRafs_.has(name)){_this4.namedRafs_["delete"](name);}});this.namedRafs_.set(name,id);return name;};_proto.cancelNamedAnimationFrame=function cancelNamedAnimationFrame(name){if(!this.namedRafs_.has(name)){return;}
this.cancelAnimationFrame(this.namedRafs_.get(name));this.namedRafs_["delete"](name);};_proto.cancelAnimationFrame=function cancelAnimationFrame(id){if(!this.supportsRaf_){return this.clearTimeout(id);}
if(this.rafIds_.has(id)){this.rafIds_["delete"](id);window_1.cancelAnimationFrame(id);}
return id;};_proto.clearTimersOnDispose_=function clearTimersOnDispose_(){var _this5=this;if(this.clearingTimersOnDispose_){return;}
this.clearingTimersOnDispose_=true;this.one('dispose',function(){[['namedRafs_','cancelNamedAnimationFrame'],['rafIds_','cancelAnimationFrame'],['setTimeoutIds_','clearTimeout'],['setIntervalIds_','clearInterval']].forEach(function(_ref){var idName=_ref[0],cancelName=_ref[1];_this5[idName].forEach(function(val,key){return _this5[cancelName](key);});});_this5.clearingTimersOnDispose_=false;});};Component.registerComponent=function registerComponent(name,ComponentToRegister){if(typeof name!=='string'||!name){throw new Error("Illegal component name, \""+name+"\"; must be a non-empty string.");}
var Tech=Component.getComponent('Tech');var isTech=Tech&&Tech.isTech(ComponentToRegister);var isComp=Component===ComponentToRegister||Component.prototype.isPrototypeOf(ComponentToRegister.prototype);if(isTech||!isComp){var reason;if(isTech){reason='techs must be registered using Tech.registerTech()';}else{reason='must be a Component subclass';}
throw new Error("Illegal component, \""+name+"\"; "+reason+".");}
name=toTitleCase(name);if(!Component.components_){Component.components_={};}
var Player=Component.getComponent('Player');if(name==='Player'&&Player&&Player.players){var players=Player.players;var playerNames=Object.keys(players);if(players&&playerNames.length>0&&playerNames.map(function(pname){return players[pname];}).every(Boolean)){throw new Error('Can not register Player component after player has been created.');}}
Component.components_[name]=ComponentToRegister;Component.components_[toLowerCase(name)]=ComponentToRegister;return ComponentToRegister;};Component.getComponent=function getComponent(name){if(!name||!Component.components_){return;}
return Component.components_[name];};return Component;}();Component.prototype.supportsRaf_=typeof window_1.requestAnimationFrame==='function'&&typeof window_1.cancelAnimationFrame==='function';Component.registerComponent('Component',Component);function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}
return self;}
var assertThisInitialized=_assertThisInitialized;var _typeof_1=createCommonjsModule(function(module){function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){module.exports=_typeof=function _typeof(obj){return typeof obj;};}else{module.exports=_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}
return _typeof(obj);}
module.exports=_typeof;});var getPrototypeOf=createCommonjsModule(function(module){function _getPrototypeOf(o){module.exports=_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}
module.exports=_getPrototypeOf;});function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype);subClass.prototype.constructor=subClass;subClass.__proto__=superClass;}
var inheritsLoose=_inheritsLoose;var USER_AGENT=window_1.navigator&&window_1.navigator.userAgent||'';var webkitVersionMap=/AppleWebKit\/([\d.]+)/i.exec(USER_AGENT);var appleWebkitVersion=webkitVersionMap?parseFloat(webkitVersionMap.pop()):null;var IS_IPOD=/iPod/i.test(USER_AGENT);var IOS_VERSION=function(){var match=USER_AGENT.match(/OS (\d+)_/i);if(match&&match[1]){return match[1];}
return null;}();var IS_ANDROID=/Android/i.test(USER_AGENT);var ANDROID_VERSION=function(){var match=USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!match){return null;}
var major=match[1]&&parseFloat(match[1]);var minor=match[2]&&parseFloat(match[2]);if(major&&minor){return parseFloat(match[1]+'.'+match[2]);}else if(major){return major;}
return null;}();var IS_NATIVE_ANDROID=IS_ANDROID&&ANDROID_VERSION<5&&appleWebkitVersion<537;var IS_FIREFOX=/Firefox/i.test(USER_AGENT);var IS_EDGE=/Edg/i.test(USER_AGENT);var IS_CHROME=!IS_EDGE&&(/Chrome/i.test(USER_AGENT)||/CriOS/i.test(USER_AGENT));var CHROME_VERSION=function(){var match=USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);if(match&&match[2]){return parseFloat(match[2]);}
return null;}();var IE_VERSION=function(){var result=/MSIE\s(\d+)\.\d/.exec(USER_AGENT);var version=result&&parseFloat(result[1]);if(!version&&/Trident\/7.0/i.test(USER_AGENT)&&/rv:11.0/.test(USER_AGENT)){version=11.0;}
return version;}();var IS_SAFARI=/Safari/i.test(USER_AGENT)&&!IS_CHROME&&!IS_ANDROID&&!IS_EDGE;var IS_WINDOWS=/Windows/i.test(USER_AGENT);var TOUCH_ENABLED=Boolean(isReal()&&('ontouchstart'in window_1||window_1.navigator.maxTouchPoints||window_1.DocumentTouch&&window_1.document instanceof window_1.DocumentTouch));var IS_IPAD=/iPad/i.test(USER_AGENT)||IS_SAFARI&&TOUCH_ENABLED&&!/iPhone/i.test(USER_AGENT);var IS_IPHONE=/iPhone/i.test(USER_AGENT)&&!IS_IPAD;var IS_IOS=IS_IPHONE||IS_IPAD||IS_IPOD;var IS_ANY_SAFARI=(IS_SAFARI||IS_IOS)&&!IS_CHROME;var browser=Object.freeze({__proto__:null,IS_IPOD:IS_IPOD,IOS_VERSION:IOS_VERSION,IS_ANDROID:IS_ANDROID,ANDROID_VERSION:ANDROID_VERSION,IS_NATIVE_ANDROID:IS_NATIVE_ANDROID,IS_FIREFOX:IS_FIREFOX,IS_EDGE:IS_EDGE,IS_CHROME:IS_CHROME,CHROME_VERSION:CHROME_VERSION,IE_VERSION:IE_VERSION,IS_SAFARI:IS_SAFARI,IS_WINDOWS:IS_WINDOWS,TOUCH_ENABLED:TOUCH_ENABLED,IS_IPAD:IS_IPAD,IS_IPHONE:IS_IPHONE,IS_IOS:IS_IOS,IS_ANY_SAFARI:IS_ANY_SAFARI});function rangeCheck(fnName,index,maxIndex){if(typeof index!=='number'||index<0||index>maxIndex){throw new Error("Failed to execute '"+fnName+"' on 'TimeRanges': The index provided ("+index+") is non-numeric or out of bounds (0-"+maxIndex+").");}}
function getRange(fnName,valueIndex,ranges,rangeIndex){rangeCheck(fnName,rangeIndex,ranges.length-1);return ranges[rangeIndex][valueIndex];}
function createTimeRangesObj(ranges){if(ranges===undefined||ranges.length===0){return{length:0,start:function start(){throw new Error('This TimeRanges object is empty');},end:function end(){throw new Error('This TimeRanges object is empty');}};}
return{length:ranges.length,start:getRange.bind(null,'start',0,ranges),end:getRange.bind(null,'end',1,ranges)};}
function createTimeRanges(start,end){if(Array.isArray(start)){return createTimeRangesObj(start);}else if(start===undefined||end===undefined){return createTimeRangesObj();}
return createTimeRangesObj([[start,end]]);}
function bufferedPercent(buffered,duration){var bufferedDuration=0;var start;var end;if(!duration){return 0;}
if(!buffered||!buffered.length){buffered=createTimeRanges(0,0);}
for(var i=0;i<buffered.length;i++){start=buffered.start(i);end=buffered.end(i);if(end>duration){end=duration;}
bufferedDuration+=end-start;}
return bufferedDuration/duration;}
var FullscreenApi={prefixed:true};var apiMap=[['requestFullscreen','exitFullscreen','fullscreenElement','fullscreenEnabled','fullscreenchange','fullscreenerror','fullscreen'],['webkitRequestFullscreen','webkitExitFullscreen','webkitFullscreenElement','webkitFullscreenEnabled','webkitfullscreenchange','webkitfullscreenerror','-webkit-full-screen'],['mozRequestFullScreen','mozCancelFullScreen','mozFullScreenElement','mozFullScreenEnabled','mozfullscreenchange','mozfullscreenerror','-moz-full-screen'],['msRequestFullscreen','msExitFullscreen','msFullscreenElement','msFullscreenEnabled','MSFullscreenChange','MSFullscreenError','-ms-fullscreen']];var specApi=apiMap[0];var browserApi;for(var i=0;i<apiMap.length;i++){if(apiMap[i][1]in document_1){browserApi=apiMap[i];break;}}
if(browserApi){for(var _i=0;_i<browserApi.length;_i++){FullscreenApi[specApi[_i]]=browserApi[_i];}
FullscreenApi.prefixed=browserApi[0]!==specApi[0];}
function MediaError(value){if(value instanceof MediaError){return value;}
if(typeof value==='number'){this.code=value;}else if(typeof value==='string'){this.message=value;}else if(isObject(value)){if(typeof value.code==='number'){this.code=value.code;}
assign(this,value);}
if(!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 playback 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(var errNum=0;errNum<MediaError.errorTypes.length;errNum++){MediaError[MediaError.errorTypes[errNum]]=errNum;MediaError.prototype[MediaError.errorTypes[errNum]]=errNum;}
var tuple=SafeParseTuple;function SafeParseTuple(obj,reviver){var json;var error=null;try{json=JSON.parse(obj,reviver);}catch(err){error=err;}
return[error,json];}
function isPromise(value){return value!==undefined&&value!==null&&typeof value.then==='function';}
function silencePromise(value){if(isPromise(value)){value.then(null,function(e){});}}
var trackToJson_=function trackToJson_(track){var ret=['kind','label','language','id','inBandMetadataTrackDispatchType','mode','src'].reduce(function(acc,prop,i){if(track[prop]){acc[prop]=track[prop];}
return acc;},{cues:track.cues&&Array.prototype.map.call(track.cues,function(cue){return{startTime:cue.startTime,endTime:cue.endTime,text:cue.text,id:cue.id};})});return ret;};var textTracksToJson=function textTracksToJson(tech){var trackEls=tech.$$('track');var trackObjs=Array.prototype.map.call(trackEls,function(t){return t.track;});var tracks=Array.prototype.map.call(trackEls,function(trackEl){var json=trackToJson_(trackEl.track);if(trackEl.src){json.src=trackEl.src;}
return json;});return tracks.concat(Array.prototype.filter.call(tech.textTracks(),function(track){return trackObjs.indexOf(track)===-1;}).map(trackToJson_));};var jsonToTextTracks=function jsonToTextTracks(json,tech){json.forEach(function(track){var addedTrack=tech.addRemoteTextTrack(track).track;if(!track.src&&track.cues){track.cues.forEach(function(cue){return addedTrack.addCue(cue);});}});return tech.textTracks();};var textTrackConverter={textTracksToJson:textTracksToJson,jsonToTextTracks:jsonToTextTracks,trackToJson_:trackToJson_};var keycode=createCommonjsModule(function(module,exports){function keyCode(searchInput){if(searchInput&&'object'===typeof searchInput){var hasKeyCode=searchInput.which||searchInput.keyCode||searchInput.charCode;if(hasKeyCode)searchInput=hasKeyCode;}
if('number'===typeof searchInput)return names[searchInput];var search=String(searchInput);var foundNamedKey=codes[search.toLowerCase()];if(foundNamedKey)return foundNamedKey;var foundNamedKey=aliases[search.toLowerCase()];if(foundNamedKey)return foundNamedKey;if(search.length===1)return search.charCodeAt(0);return undefined;}
keyCode.isEventKey=function isEventKey(event,nameOrCode){if(event&&'object'===typeof event){var keyCode=event.which||event.keyCode||event.charCode;if(keyCode===null||keyCode===undefined){return false;}
if(typeof nameOrCode==='string'){var foundNamedKey=codes[nameOrCode.toLowerCase()];if(foundNamedKey){return foundNamedKey===keyCode;}
var foundNamedKey=aliases[nameOrCode.toLowerCase()];if(foundNamedKey){return foundNamedKey===keyCode;}}else if(typeof nameOrCode==='number'){return nameOrCode===keyCode;}
return false;}};exports=module.exports=keyCode;var codes=exports.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,'numpad .':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};var 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];}});var keycode_1=keycode.code;var keycode_2=keycode.codes;var keycode_3=keycode.aliases;var keycode_4=keycode.names;var keycode_5=keycode.title;var MODAL_CLASS_NAME='vjs-modal-dialog';var ModalDialog=function(_Component){inheritsLoose(ModalDialog,_Component);function ModalDialog(player,options){var _this;_this=_Component.call(this,player,options)||this;_this.opened_=_this.hasBeenOpened_=_this.hasBeenFilled_=false;_this.closeable(!_this.options_.uncloseable);_this.content(_this.options_.content);_this.contentEl_=createEl('div',{className:MODAL_CLASS_NAME+"-content"},{role:'document'});_this.descEl_=createEl('p',{className:MODAL_CLASS_NAME+"-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_);return _this;}
var _proto=ModalDialog.prototype;_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'div',{className:this.buildCSSClass(),tabIndex:-1},{'aria-describedby':this.id()+"_description",'aria-hidden':'true','aria-label':this.label(),'role':'dialog'});};_proto.dispose=function dispose(){this.contentEl_=null;this.descEl_=null;this.previouslyActiveEl_=null;_Component.prototype.dispose.call(this);};_proto.buildCSSClass=function buildCSSClass(){return MODAL_CLASS_NAME+" vjs-hidden "+_Component.prototype.buildCSSClass.call(this);};_proto.label=function label(){return this.localize(this.options_.label||'Modal Window');};_proto.description=function description(){var desc=this.options_.description||this.localize('This is a modal window.');if(this.closeable()){desc+=' '+this.localize('This modal can be closed by pressing the Escape key or activating the close button.');}
return desc;};_proto.open=function open(){if(!this.opened_){var player=this.player();this.trigger('beforemodalopen');this.opened_=true;if(this.options_.fillAlways||!this.hasBeenOpened_&&!this.hasBeenFilled_){this.fill();}
this.wasPlaying_=!player.paused();if(this.options_.pauseOnOpen&&this.wasPlaying_){player.pause();}
this.on('keydown',this.handleKeyDown);this.hadControls_=player.controls();player.controls(false);this.show();this.conditionalFocus_();this.el().setAttribute('aria-hidden','false');this.trigger('modalopen');this.hasBeenOpened_=true;}};_proto.opened=function opened(value){if(typeof value==='boolean'){this[value?'open':'close']();}
return this.opened_;};_proto.close=function close(){if(!this.opened_){return;}
var player=this.player();this.trigger('beforemodalclose');this.opened_=false;if(this.wasPlaying_&&this.options_.pauseOnOpen){player.play();}
this.off('keydown',this.handleKeyDown);if(this.hadControls_){player.controls(true);}
this.hide();this.el().setAttribute('aria-hidden','true');this.trigger('modalclose');this.conditionalBlur_();if(this.options_.temporary){this.dispose();}};_proto.closeable=function closeable(value){if(typeof value==='boolean'){var closeable=this.closeable_=!!value;var close=this.getChild('closeButton');if(closeable&&!close){var temp=this.contentEl_;this.contentEl_=this.el_;close=this.addChild('closeButton',{controlText:'Close Modal Dialog'});this.contentEl_=temp;this.on(close,'close',this.close);}
if(!closeable&&close){this.off(close,'close',this.close);this.removeChild(close);close.dispose();}}
return this.closeable_;};_proto.fill=function fill(){this.fillWith(this.content());};_proto.fillWith=function fillWith(content){var contentEl=this.contentEl();var parentEl=contentEl.parentNode;var nextSiblingEl=contentEl.nextSibling;this.trigger('beforemodalfill');this.hasBeenFilled_=true;parentEl.removeChild(contentEl);this.empty();insertContent(contentEl,content);this.trigger('modalfill');if(nextSiblingEl){parentEl.insertBefore(contentEl,nextSiblingEl);}else{parentEl.appendChild(contentEl);}
var closeButton=this.getChild('closeButton');if(closeButton){parentEl.appendChild(closeButton.el_);}};_proto.empty=function empty(){this.trigger('beforemodalempty');emptyEl(this.contentEl());this.trigger('modalempty');};_proto.content=function content(value){if(typeof value!=='undefined'){this.content_=value;}
return this.content_;};_proto.conditionalFocus_=function conditionalFocus_(){var activeEl=document_1.activeElement;var playerEl=this.player_.el_;this.previouslyActiveEl_=null;if(playerEl.contains(activeEl)||playerEl===activeEl){this.previouslyActiveEl_=activeEl;this.focus();}};_proto.conditionalBlur_=function conditionalBlur_(){if(this.previouslyActiveEl_){this.previouslyActiveEl_.focus();this.previouslyActiveEl_=null;}};_proto.handleKeyDown=function handleKeyDown(event){event.stopPropagation();if(keycode.isEventKey(event,'Escape')&&this.closeable()){event.preventDefault();this.close();return;}
if(!keycode.isEventKey(event,'Tab')){return;}
var focusableEls=this.focusableEls_();var activeEl=this.el_.querySelector(':focus');var focusIndex;for(var i=0;i<focusableEls.length;i++){if(activeEl===focusableEls[i]){focusIndex=i;break;}}
if(document_1.activeElement===this.el_){focusIndex=0;}
if(event.shiftKey&&focusIndex===0){focusableEls[focusableEls.length-1].focus();event.preventDefault();}else if(!event.shiftKey&&focusIndex===focusableEls.length-1){focusableEls[0].focus();event.preventDefault();}};_proto.focusableEls_=function focusableEls_(){var allChildren=this.el_.querySelectorAll('*');return Array.prototype.filter.call(allChildren,function(child){return(child instanceof window_1.HTMLAnchorElement||child instanceof window_1.HTMLAreaElement)&&child.hasAttribute('href')||(child instanceof window_1.HTMLInputElement||child instanceof window_1.HTMLSelectElement||child instanceof window_1.HTMLTextAreaElement||child instanceof window_1.HTMLButtonElement)&&!child.hasAttribute('disabled')||child instanceof window_1.HTMLIFrameElement||child instanceof window_1.HTMLObjectElement||child instanceof window_1.HTMLEmbedElement||child.hasAttribute('tabindex')&&child.getAttribute('tabindex')!==-1||child.hasAttribute('contenteditable');});};return ModalDialog;}(Component);ModalDialog.prototype.options_={pauseOnOpen:true,temporary:true};Component.registerComponent('ModalDialog',ModalDialog);var TrackList=function(_EventTarget){inheritsLoose(TrackList,_EventTarget);function TrackList(tracks){var _this;if(tracks===void 0){tracks=[];}
_this=_EventTarget.call(this)||this;_this.tracks_=[];Object.defineProperty(assertThisInitialized(_this),'length',{get:function get(){return this.tracks_.length;}});for(var i=0;i<tracks.length;i++){_this.addTrack(tracks[i]);}
return _this;}
var _proto=TrackList.prototype;_proto.addTrack=function addTrack(track){var _this2=this;var index=this.tracks_.length;if(!(''+index in this)){Object.defineProperty(this,index,{get:function get(){return this.tracks_[index];}});}
if(this.tracks_.indexOf(track)===-1){this.tracks_.push(track);this.trigger({track:track,type:'addtrack',target:this});}
track.labelchange_=function(){_this2.trigger({track:track,type:'labelchange',target:_this2});};if(isEvented(track)){track.addEventListener('labelchange',track.labelchange_);}};_proto.removeTrack=function removeTrack(rtrack){var track;for(var i=0,l=this.length;i<l;i++){if(this[i]===rtrack){track=this[i];if(track.off){track.off();}
this.tracks_.splice(i,1);break;}}
if(!track){return;}
this.trigger({track:track,type:'removetrack',target:this});};_proto.getTrackById=function getTrackById(id){var result=null;for(var i=0,l=this.length;i<l;i++){var track=this[i];if(track.id===id){result=track;break;}}
return result;};return TrackList;}(EventTarget);TrackList.prototype.allowedEvents_={change:'change',addtrack:'addtrack',removetrack:'removetrack',labelchange:'labelchange'};for(var event in TrackList.prototype.allowedEvents_){TrackList.prototype['on'+event]=null;}
var disableOthers=function disableOthers(list,track){for(var i=0;i<list.length;i++){if(!Object.keys(list[i]).length||track.id===list[i].id){continue;}
list[i].enabled=false;}};var AudioTrackList=function(_TrackList){inheritsLoose(AudioTrackList,_TrackList);function AudioTrackList(tracks){var _this;if(tracks===void 0){tracks=[];}
for(var i=tracks.length-1;i>=0;i--){if(tracks[i].enabled){disableOthers(tracks,tracks[i]);break;}}
_this=_TrackList.call(this,tracks)||this;_this.changing_=false;return _this;}
var _proto=AudioTrackList.prototype;_proto.addTrack=function addTrack(track){var _this2=this;if(track.enabled){disableOthers(this,track);}
_TrackList.prototype.addTrack.call(this,track);if(!track.addEventListener){return;}
track.enabledChange_=function(){if(_this2.changing_){return;}
_this2.changing_=true;disableOthers(_this2,track);_this2.changing_=false;_this2.trigger('change');};track.addEventListener('enabledchange',track.enabledChange_);};_proto.removeTrack=function removeTrack(rtrack){_TrackList.prototype.removeTrack.call(this,rtrack);if(rtrack.removeEventListener&&rtrack.enabledChange_){rtrack.removeEventListener('enabledchange',rtrack.enabledChange_);rtrack.enabledChange_=null;}};return AudioTrackList;}(TrackList);var disableOthers$1=function disableOthers(list,track){for(var i=0;i<list.length;i++){if(!Object.keys(list[i]).length||track.id===list[i].id){continue;}
list[i].selected=false;}};var VideoTrackList=function(_TrackList){inheritsLoose(VideoTrackList,_TrackList);function VideoTrackList(tracks){var _this;if(tracks===void 0){tracks=[];}
for(var i=tracks.length-1;i>=0;i--){if(tracks[i].selected){disableOthers$1(tracks,tracks[i]);break;}}
_this=_TrackList.call(this,tracks)||this;_this.changing_=false;Object.defineProperty(assertThisInitialized(_this),'selectedIndex',{get:function get(){for(var _i=0;_i<this.length;_i++){if(this[_i].selected){return _i;}}
return-1;},set:function set(){}});return _this;}
var _proto=VideoTrackList.prototype;_proto.addTrack=function addTrack(track){var _this2=this;if(track.selected){disableOthers$1(this,track);}
_TrackList.prototype.addTrack.call(this,track);if(!track.addEventListener){return;}
track.selectedChange_=function(){if(_this2.changing_){return;}
_this2.changing_=true;disableOthers$1(_this2,track);_this2.changing_=false;_this2.trigger('change');};track.addEventListener('selectedchange',track.selectedChange_);};_proto.removeTrack=function removeTrack(rtrack){_TrackList.prototype.removeTrack.call(this,rtrack);if(rtrack.removeEventListener&&rtrack.selectedChange_){rtrack.removeEventListener('selectedchange',rtrack.selectedChange_);rtrack.selectedChange_=null;}};return VideoTrackList;}(TrackList);var TextTrackList=function(_TrackList){inheritsLoose(TextTrackList,_TrackList);function TextTrackList(){return _TrackList.apply(this,arguments)||this;}
var _proto=TextTrackList.prototype;_proto.addTrack=function addTrack(track){var _this=this;_TrackList.prototype.addTrack.call(this,track);if(!this.queueChange_){this.queueChange_=function(){return _this.queueTrigger('change');};}
if(!this.triggerSelectedlanguagechange){this.triggerSelectedlanguagechange_=function(){return _this.trigger('selectedlanguagechange');};}
track.addEventListener('modechange',this.queueChange_);var nonLanguageTextTrackKind=['metadata','chapters'];if(nonLanguageTextTrackKind.indexOf(track.kind)===-1){track.addEventListener('modechange',this.triggerSelectedlanguagechange_);}};_proto.removeTrack=function removeTrack(rtrack){_TrackList.prototype.removeTrack.call(this,rtrack);if(rtrack.removeEventListener){if(this.queueChange_){rtrack.removeEventListener('modechange',this.queueChange_);}
if(this.selectedlanguagechange_){rtrack.removeEventListener('modechange',this.triggerSelectedlanguagechange_);}}};return TextTrackList;}(TrackList);var HtmlTrackElementList=function(){function HtmlTrackElementList(trackElements){if(trackElements===void 0){trackElements=[];}
this.trackElements_=[];Object.defineProperty(this,'length',{get:function get(){return this.trackElements_.length;}});for(var i=0,length=trackElements.length;i<length;i++){this.addTrackElement_(trackElements[i]);}}
var _proto=HtmlTrackElementList.prototype;_proto.addTrackElement_=function addTrackElement_(trackElement){var index=this.trackElements_.length;if(!(''+index in this)){Object.defineProperty(this,index,{get:function get(){return this.trackElements_[index];}});}
if(this.trackElements_.indexOf(trackElement)===-1){this.trackElements_.push(trackElement);}};_proto.getTrackElementByTrack_=function getTrackElementByTrack_(track){var trackElement_;for(var i=0,length=this.trackElements_.length;i<length;i++){if(track===this.trackElements_[i].track){trackElement_=this.trackElements_[i];break;}}
return trackElement_;};_proto.removeTrackElement_=function removeTrackElement_(trackElement){for(var i=0,length=this.trackElements_.length;i<length;i++){if(trackElement===this.trackElements_[i]){if(this.trackElements_[i].track&&typeof this.trackElements_[i].track.off==='function'){this.trackElements_[i].track.off();}
if(typeof this.trackElements_[i].off==='function'){this.trackElements_[i].off();}
this.trackElements_.splice(i,1);break;}}};return HtmlTrackElementList;}();var TextTrackCueList=function(){function TextTrackCueList(cues){TextTrackCueList.prototype.setCues_.call(this,cues);Object.defineProperty(this,'length',{get:function get(){return this.length_;}});}
var _proto=TextTrackCueList.prototype;_proto.setCues_=function setCues_(cues){var oldLength=this.length||0;var i=0;var l=cues.length;this.cues_=cues;this.length_=cues.length;var defineProp=function defineProp(index){if(!(''+index in this)){Object.defineProperty(this,''+index,{get:function get(){return this.cues_[index];}});}};if(oldLength<l){i=oldLength;for(;i<l;i++){defineProp.call(this,i);}}};_proto.getCueById=function getCueById(id){var result=null;for(var i=0,l=this.length;i<l;i++){var cue=this[i];if(cue.id===id){result=cue;break;}}
return result;};return TextTrackCueList;}();var VideoTrackKind={alternative:'alternative',captions:'captions',main:'main',sign:'sign',subtitles:'subtitles',commentary:'commentary'};var AudioTrackKind={'alternative':'alternative','descriptions':'descriptions','main':'main','main-desc':'main-desc','translation':'translation','commentary':'commentary'};var TextTrackKind={subtitles:'subtitles',captions:'captions',descriptions:'descriptions',chapters:'chapters',metadata:'metadata'};var TextTrackMode={disabled:'disabled',hidden:'hidden',showing:'showing'};var Track=function(_EventTarget){inheritsLoose(Track,_EventTarget);function Track(options){var _this;if(options===void 0){options={};}
_this=_EventTarget.call(this)||this;var trackProps={id:options.id||'vjs_track_'+newGUID(),kind:options.kind||'',language:options.language||''};var label=options.label||'';var _loop=function _loop(key){Object.defineProperty(assertThisInitialized(_this),key,{get:function get(){return trackProps[key];},set:function set(){}});};for(var key in trackProps){_loop(key);}
Object.defineProperty(assertThisInitialized(_this),'label',{get:function get(){return label;},set:function set(newLabel){if(newLabel!==label){label=newLabel;this.trigger('labelchange');}}});return _this;}
return Track;}(EventTarget);var parseUrl=function parseUrl(url){var props=['protocol','hostname','port','pathname','search','hash','host'];var a=document_1.createElement('a');a.href=url;var addToBody=a.host===''&&a.protocol!=='file:';var div;if(addToBody){div=document_1.createElement('div');div.innerHTML="<a href=\""+url+"\"></a>";a=div.firstChild;div.setAttribute('style','display:none; position:absolute;');document_1.body.appendChild(div);}
var details={};for(var i=0;i<props.length;i++){details[props[i]]=a[props[i]];}
if(details.protocol==='http:'){details.host=details.host.replace(/:80$/,'');}
if(details.protocol==='https:'){details.host=details.host.replace(/:443$/,'');}
if(!details.protocol){details.protocol=window_1.location.protocol;}
if(addToBody){document_1.body.removeChild(div);}
return details;};var getAbsoluteURL=function getAbsoluteURL(url){if(!url.match(/^https?:\/\//)){var div=document_1.createElement('div');div.innerHTML="<a href=\""+url+"\">x</a>";url=div.firstChild.href;}
return url;};var getFileExtension=function getFileExtension(path){if(typeof path==='string'){var splitPathRe=/^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;var pathParts=splitPathRe.exec(path);if(pathParts){return pathParts.pop().toLowerCase();}}
return'';};var isCrossOrigin=function isCrossOrigin(url,winLoc){if(winLoc===void 0){winLoc=window_1.location;}
var urlInfo=parseUrl(url);var srcProtocol=urlInfo.protocol===':'?winLoc.protocol:urlInfo.protocol;var crossOrigin=srcProtocol+urlInfo.host!==winLoc.protocol+winLoc.host;return crossOrigin;};var Url=Object.freeze({__proto__:null,parseUrl:parseUrl,getAbsoluteURL:getAbsoluteURL,getFileExtension:getFileExtension,isCrossOrigin:isCrossOrigin});var win$1;if(typeof window!=="undefined"){win$1=window;}else if(typeof commonjsGlobal!=="undefined"){win$1=commonjsGlobal;}else if(typeof self!=="undefined"){win$1=self;}else{win$1={};}
var window_1$1=win$1;var isFunction_1=isFunction;var toString$1=Object.prototype.toString;function isFunction(fn){var string=toString$1.call(fn);return string==='[object Function]'||typeof fn==='function'&&string!=='[object RegExp]'||typeof window!=='undefined'&&(fn===window.setTimeout||fn===window.alert||fn===window.confirm||fn===window.prompt);}
var parseHeaders=function parseHeaders(headers){var result={};if(!headers){return result;}
headers.trim().split('\n').forEach(function(row){var index=row.indexOf(':');var key=row.slice(0,index).trim().toLowerCase();var value=row.slice(index+1).trim();if(typeof result[key]==='undefined'){result[key]=value;}else if(Array.isArray(result[key])){result[key].push(value);}else{result[key]=[result[key],value];}});return result;};var xhr=createXHR;var default_1=createXHR;createXHR.XMLHttpRequest=window_1$1.XMLHttpRequest||noop;createXHR.XDomainRequest="withCredentials"in new createXHR.XMLHttpRequest()?createXHR.XMLHttpRequest:window_1$1.XDomainRequest;forEachArray(["get","put","post","patch","head","delete"],function(method){createXHR[method==="delete"?"del":method]=function(uri,options,callback){options=initParams(uri,options,callback);options.method=method.toUpperCase();return _createXHR(options);};});function forEachArray(array,iterator){for(var i=0;i<array.length;i++){iterator(array[i]);}}
function isEmpty(obj){for(var i in obj){if(obj.hasOwnProperty(i))return false;}
return true;}
function initParams(uri,options,callback){var params=uri;if(isFunction_1(options)){callback=options;if(typeof uri==="string"){params={uri:uri};}}else{params=_extends_1({},options,{uri:uri});}
params.callback=callback;return params;}
function createXHR(uri,options,callback){options=initParams(uri,options,callback);return _createXHR(options);}
function _createXHR(options){if(typeof options.callback==="undefined"){throw new Error("callback argument missing");}
var called=false;var callback=function cbOnce(err,response,body){if(!called){called=true;options.callback(err,response,body);}};function readystatechange(){if(xhr.readyState===4){setTimeout(loadFunc,0);}}
function getBody(){var body=undefined;if(xhr.response){body=xhr.response;}else{body=xhr.responseText||getXml(xhr);}
if(isJson){try{body=JSON.parse(body);}catch(e){}}
return body;}
function errorFunc(evt){clearTimeout(timeoutTimer);if(!(evt instanceof Error)){evt=new Error(""+(evt||"Unknown XMLHttpRequest Error"));}
evt.statusCode=0;return callback(evt,failureResponse);}
function loadFunc(){if(aborted)return;var status;clearTimeout(timeoutTimer);if(options.useXDR&&xhr.status===undefined){status=200;}else{status=xhr.status===1223?204:xhr.status;}
var response=failureResponse;var err=null;if(status!==0){response={body:getBody(),statusCode:status,method:method,headers:{},url:uri,rawRequest:xhr};if(xhr.getAllResponseHeaders){response.headers=parseHeaders(xhr.getAllResponseHeaders());}}else{err=new Error("Internal XMLHttpRequest Error");}
return callback(err,response,response.body);}
var xhr=options.xhr||null;if(!xhr){if(options.cors||options.useXDR){xhr=new createXHR.XDomainRequest();}else{xhr=new createXHR.XMLHttpRequest();}}
var key;var aborted;var uri=xhr.url=options.uri||options.url;var method=xhr.method=options.method||"GET";var body=options.body||options.data;var headers=xhr.headers=options.headers||{};var sync=!!options.sync;var isJson=false;var timeoutTimer;var failureResponse={body:undefined,headers:{},statusCode:0,method:method,url:uri,rawRequest:xhr};if("json"in options&&options.json!==false){isJson=true;headers["accept"]||headers["Accept"]||(headers["Accept"]="application/json");if(method!=="GET"&&method!=="HEAD"){headers["content-type"]||headers["Content-Type"]||(headers["Content-Type"]="application/json");body=JSON.stringify(options.json===true?body:options.json);}}
xhr.onreadystatechange=readystatechange;xhr.onload=loadFunc;xhr.onerror=errorFunc;xhr.onprogress=function(){};xhr.onabort=function(){aborted=true;};xhr.ontimeout=errorFunc;xhr.open(method,uri,!sync,options.username,options.password);if(!sync){xhr.withCredentials=!!options.withCredentials;}
if(!sync&&options.timeout>0){timeoutTimer=setTimeout(function(){if(aborted)return;aborted=true;xhr.abort("timeout");var e=new Error("XMLHttpRequest timeout");e.code="ETIMEDOUT";errorFunc(e);},options.timeout);}
if(xhr.setRequestHeader){for(key in headers){if(headers.hasOwnProperty(key)){xhr.setRequestHeader(key,headers[key]);}}}else if(options.headers&&!isEmpty(options.headers)){throw new Error("Headers cannot be set on an XDomainRequest object");}
if("responseType"in options){xhr.responseType=options.responseType;}
if("beforeSend"in options&&typeof options.beforeSend==="function"){options.beforeSend(xhr);}
xhr.send(body||null);return xhr;}
function getXml(xhr){try{if(xhr.responseType==="document"){return xhr.responseXML;}
var firefoxBugTakenEffect=xhr.responseXML&&xhr.responseXML.documentElement.nodeName==="parsererror";if(xhr.responseType===""&&!firefoxBugTakenEffect){return xhr.responseXML;}}catch(e){}
return null;}
function noop(){}
xhr["default"]=default_1;var parseCues=function parseCues(srcContent,track){var parser=new window_1.WebVTT.Parser(window_1,window_1.vttjs,window_1.WebVTT.StringDecoder());var 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);if(errors.length>0){if(window_1.console&&window_1.console.groupCollapsed){window_1.console.groupCollapsed("Text Track parsing errors for "+track.src);}
errors.forEach(function(error){return log.error(error);});if(window_1.console&&window_1.console.groupEnd){window_1.console.groupEnd();}}
parser.flush();};var loadTrack=function loadTrack(src,track){var opts={uri:src};var crossOrigin=isCrossOrigin(src);if(crossOrigin){opts.cors=crossOrigin;}
var withCredentials=track.tech_.crossOrigin()==='use-credentials';if(withCredentials){opts.withCredentials=withCredentials;}
xhr(opts,bind(this,function(err,response,responseBody){if(err){return log.error(err,response);}
track.loaded_=true;if(typeof window_1.WebVTT!=='function'){if(track.tech_){track.tech_.any(['vttjsloaded','vttjserror'],function(event){if(event.type==='vttjserror'){log.error("vttjs failed to load, stopping trying to process "+track.src);return;}
return parseCues(responseBody,track);});}}else{parseCues(responseBody,track);}}));};var TextTrack=function(_Track){inheritsLoose(TextTrack,_Track);function TextTrack(options){var _this;if(options===void 0){options={};}
if(!options.tech){throw new Error('A tech was not provided.');}
var settings=mergeOptions(options,{kind:TextTrackKind[options.kind]||'subtitles',language:options.language||options.srclang||''});var mode=TextTrackMode[settings.mode]||'disabled';var default_=settings["default"];if(settings.kind==='metadata'||settings.kind==='chapters'){mode='hidden';}
_this=_Track.call(this,settings)||this;_this.tech_=settings.tech;_this.cues_=[];_this.activeCues_=[];_this.preload_=_this.tech_.preloadTextTracks!==false;var cues=new TextTrackCueList(_this.cues_);var activeCues=new TextTrackCueList(_this.activeCues_);var changed=false;var timeupdateHandler=bind(assertThisInitialized(_this),function(){if(!this.tech_.isReady_||this.tech_.isDisposed()){return;}
this.activeCues=this.activeCues;if(changed){this.trigger('cuechange');changed=false;}});var disposeHandler=function disposeHandler(){_this.tech_.off('timeupdate',timeupdateHandler);};_this.tech_.one('dispose',disposeHandler);if(mode!=='disabled'){_this.tech_.on('timeupdate',timeupdateHandler);}
Object.defineProperties(assertThisInitialized(_this),{"default":{get:function get(){return default_;},set:function set(){}},mode:{get:function get(){return mode;},set:function set(newMode){if(!TextTrackMode[newMode]){return;}
if(mode===newMode){return;}
mode=newMode;if(!this.preload_&&mode!=='disabled'&&this.cues.length===0){loadTrack(this.src,this);}
this.tech_.off('timeupdate',timeupdateHandler);if(mode!=='disabled'){this.tech_.on('timeupdate',timeupdateHandler);}
this.trigger('modechange');}},cues:{get:function get(){if(!this.loaded_){return null;}
return cues;},set:function set(){}},activeCues:{get:function get(){if(!this.loaded_){return null;}
if(this.cues.length===0){return activeCues;}
var ct=this.tech_.currentTime();var active=[];for(var i=0,l=this.cues.length;i<l;i++){var cue=this.cues[i];if(cue.startTime<=ct&&cue.endTime>=ct){active.push(cue);}else if(cue.startTime===cue.endTime&&cue.startTime<=ct&&cue.startTime+0.5>=ct){active.push(cue);}}
changed=false;if(active.length!==this.activeCues_.length){changed=true;}else{for(var _i=0;_i<active.length;_i++){if(this.activeCues_.indexOf(active[_i])===-1){changed=true;}}}
this.activeCues_=active;activeCues.setCues_(this.activeCues_);return activeCues;},set:function set(){}}});if(settings.src){_this.src=settings.src;if(!_this.preload_){_this.loaded_=true;}
if(_this.preload_||default_||settings.kind!=='subtitles'&&settings.kind!=='captions'){loadTrack(_this.src,assertThisInitialized(_this));}}else{_this.loaded_=true;}
return _this;}
var _proto=TextTrack.prototype;_proto.addCue=function addCue(originalCue){var cue=originalCue;if(window_1.vttjs&&!(originalCue instanceof window_1.vttjs.VTTCue)){cue=new window_1.vttjs.VTTCue(originalCue.startTime,originalCue.endTime,originalCue.text);for(var prop in originalCue){if(!(prop in cue)){cue[prop]=originalCue[prop];}}
cue.id=originalCue.id;cue.originalCue_=originalCue;}
var tracks=this.tech_.textTracks();for(var i=0;i<tracks.length;i++){if(tracks[i]!==this){tracks[i].removeCue(cue);}}
this.cues_.push(cue);this.cues.setCues_(this.cues_);};_proto.removeCue=function removeCue(_removeCue){var i=this.cues_.length;while(i--){var cue=this.cues_[i];if(cue===_removeCue||cue.originalCue_&&cue.originalCue_===_removeCue){this.cues_.splice(i,1);this.cues.setCues_(this.cues_);break;}}};return TextTrack;}(Track);TextTrack.prototype.allowedEvents_={cuechange:'cuechange'};var AudioTrack=function(_Track){inheritsLoose(AudioTrack,_Track);function AudioTrack(options){var _this;if(options===void 0){options={};}
var settings=mergeOptions(options,{kind:AudioTrackKind[options.kind]||''});_this=_Track.call(this,settings)||this;var enabled=false;Object.defineProperty(assertThisInitialized(_this),'enabled',{get:function get(){return enabled;},set:function set(newEnabled){if(typeof newEnabled!=='boolean'||newEnabled===enabled){return;}
enabled=newEnabled;this.trigger('enabledchange');}});if(settings.enabled){_this.enabled=settings.enabled;}
_this.loaded_=true;return _this;}
return AudioTrack;}(Track);var VideoTrack=function(_Track){inheritsLoose(VideoTrack,_Track);function VideoTrack(options){var _this;if(options===void 0){options={};}
var settings=mergeOptions(options,{kind:VideoTrackKind[options.kind]||''});_this=_Track.call(this,settings)||this;var selected=false;Object.defineProperty(assertThisInitialized(_this),'selected',{get:function get(){return selected;},set:function set(newSelected){if(typeof newSelected!=='boolean'||newSelected===selected){return;}
selected=newSelected;this.trigger('selectedchange');}});if(settings.selected){_this.selected=settings.selected;}
return _this;}
return VideoTrack;}(Track);var NONE=0;var LOADING=1;var LOADED=2;var ERROR=3;var HTMLTrackElement=function(_EventTarget){inheritsLoose(HTMLTrackElement,_EventTarget);function HTMLTrackElement(options){var _this;if(options===void 0){options={};}
_this=_EventTarget.call(this)||this;var readyState;var 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(assertThisInitialized(_this),{readyState:{get:function get(){return readyState;}},track:{get:function get(){return track;}}});readyState=NONE;track.addEventListener('loadeddata',function(){readyState=LOADED;_this.trigger({type:'load',target:assertThisInitialized(_this)});});return _this;}
return HTMLTrackElement;}(EventTarget);HTMLTrackElement.prototype.allowedEvents_={load:'load'};HTMLTrackElement.NONE=NONE;HTMLTrackElement.LOADING=LOADING;HTMLTrackElement.LOADED=LOADED;HTMLTrackElement.ERROR=ERROR;var NORMAL={audio:{ListClass:AudioTrackList,TrackClass:AudioTrack,capitalName:'Audio'},video:{ListClass:VideoTrackList,TrackClass:VideoTrack,capitalName:'Video'},text:{ListClass:TextTrackList,TrackClass:TextTrack,capitalName:'Text'}};Object.keys(NORMAL).forEach(function(type){NORMAL[type].getterName=type+"Tracks";NORMAL[type].privateName=type+"Tracks_";});var REMOTE={remoteText:{ListClass:TextTrackList,TrackClass:TextTrack,capitalName:'RemoteText',getterName:'remoteTextTracks',privateName:'remoteTextTracks_'},remoteTextEl:{ListClass:HtmlTrackElementList,TrackClass:HTMLTrackElement,capitalName:'RemoteTextTrackEls',getterName:'remoteTextTrackEls',privateName:'remoteTextTrackEls_'}};var ALL=_extends_1({},NORMAL,REMOTE);REMOTE.names=Object.keys(REMOTE);NORMAL.names=Object.keys(NORMAL);ALL.names=[].concat(REMOTE.names).concat(NORMAL.names);var _objCreate=Object.create||function(){function F(){}
return function(o){if(arguments.length!==1){throw new Error('Object.create shim only accepts one parameter.');}
F.prototype=o;return new F();};}();function ParsingError(errorData,message){this.name="ParsingError";this.code=errorData.code;this.message=message||errorData.message;}
ParsingError.prototype=_objCreate(Error.prototype);ParsingError.prototype.constructor=ParsingError;ParsingError.Errors={BadSignature:{code:0,message:"Malformed WebVTT signature."},BadTimeStamp:{code:1,message:"Malformed time stamp."}};function parseTimeStamp(input){function computeSeconds(h,m,s,f){return(h|0)*3600+(m|0)*60+(s|0)+(f|0)/1000;}
var m=input.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);if(!m){return null;}
if(m[3]){return computeSeconds(m[1],m[2],m[3].replace(":",""),m[4]);}else if(m[1]>59){return computeSeconds(m[1],m[2],0,m[4]);}else{return computeSeconds(0,m[1],m[2],m[4]);}}
function Settings(){this.values=_objCreate(null);}
Settings.prototype={set:function set(k,v){if(!this.get(k)&&v!==""){this.values[k]=v;}},get:function get(k,dflt,defaultKey){if(defaultKey){return this.has(k)?this.values[k]:dflt[defaultKey];}
return this.has(k)?this.values[k]:dflt;},has:function has(k){return k in this.values;},alt:function alt(k,v,a){for(var n=0;n<a.length;++n){if(v===a[n]){this.set(k,v);break;}}},integer:function integer(k,v){if(/^-?\d+$/.test(v)){this.set(k,parseInt(v,10));}},percent:function percent(k,v){var m;if(m=v.match(/^([\d]{1,3})(\.[\d]*)?%$/)){v=parseFloat(v);if(v>=0&&v<=100){this.set(k,v);return true;}}
return false;}};function parseOptions(input,callback,keyValueDelim,groupDelim){var groups=groupDelim?input.split(groupDelim):[input];for(var i in groups){if(typeof groups[i]!=="string"){continue;}
var kv=groups[i].split(keyValueDelim);if(kv.length!==2){continue;}
var k=kv[0];var v=kv[1];callback(k,v);}}
function parseCue(input,cue,regionList){var oInput=input;function consumeTimeStamp(){var ts=parseTimeStamp(input);if(ts===null){throw new ParsingError(ParsingError.Errors.BadTimeStamp,"Malformed timestamp: "+oInput);}
input=input.replace(/^[^\sa-zA-Z-]+/,"");return ts;}
function consumeCueSettings(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",false):null;settings.alt(k,vals0,["auto"]);if(vals.length===2){settings.alt("lineAlign",vals[1],["start","center","end"]);}
break;case"position":vals=v.split(",");settings.percent(k,vals[0]);if(vals.length===2){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"]);break;}},/:/,/\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",true);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);}
function skipWhitespace(){input=input.replace(/^\s+/,"");}
skipWhitespace();cue.startTime=consumeTimeStamp();skipWhitespace();if(input.substr(0,3)!=="-->"){throw new ParsingError(ParsingError.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '-->'): "+oInput);}
input=input.substr(3);skipWhitespace();cue.endTime=consumeTimeStamp();skipWhitespace();consumeCueSettings(input,cue);}
var TEXTAREA_ELEMENT=document_1.createElement("textarea");var TAG_NAME={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span"};var 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)'};var TAG_ANNOTATION={v:"title",lang:"lang"};var NEEDS_PARENT={rt:"ruby"};function parseContent(window,input){function nextToken(){if(!input){return null;}
function consume(result){input=input.substr(result.length);return result;}
var m=input.match(/^([^<]*)(<[^>]*>?)?/);return consume(m[1]?m[1]:m[2]);}
function unescape(s){TEXTAREA_ELEMENT.innerHTML=s;s=TEXTAREA_ELEMENT.textContent;TEXTAREA_ELEMENT.textContent="";return s;}
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);var name=TAG_ANNOTATION[type];if(name&&annotation){element[name]=annotation.trim();}
return element;}
var rootDiv=window.document.createElement("div"),current=rootDiv,t,tagStack=[];while((t=nextToken())!==null){if(t[0]==='<'){if(t[1]==="/"){if(tagStack.length&&tagStack[tagStack.length-1]===t.substr(2).replace(">","")){tagStack.pop();current=current.parentNode;}
continue;}
var ts=parseTimeStamp(t.substr(1,t.length-2));var node;if(ts){node=window.document.createProcessingInstruction("timestamp",ts);current.appendChild(node);continue;}
var m=t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!m){continue;}
node=createElement(m[1],m[3]);if(!node){continue;}
if(!shouldAdd(current,node)){continue;}
if(m[2]){var classes=m[2].split('.');classes.forEach(function(cl){var bgColor=/^bg_/.test(cl);var colorName=bgColor?cl.slice(3):cl;if(DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)){var propName=bgColor?'background-color':'color';var propValue=DEFAULT_COLOR_CLASS[colorName];node.style[propName]=propValue;}});node.className=classes.join(' ');}
tagStack.push(m[1]);current.appendChild(node);current=node;continue;}
current.appendChild(window.document.createTextNode(unescape(t)));}
return rootDiv;}
var strongRTLRanges=[[0x5be,0x5be],[0x5c0,0x5c0],[0x5c3,0x5c3],[0x5c6,0x5c6],[0x5d0,0x5ea],[0x5f0,0x5f4],[0x608,0x608],[0x60b,0x60b],[0x60d,0x60d],[0x61b,0x61b],[0x61e,0x64a],[0x66d,0x66f],[0x671,0x6d5],[0x6e5,0x6e6],[0x6ee,0x6ef],[0x6fa,0x70d],[0x70f,0x710],[0x712,0x72f],[0x74d,0x7a5],[0x7b1,0x7b1],[0x7c0,0x7ea],[0x7f4,0x7f5],[0x7fa,0x7fa],[0x800,0x815],[0x81a,0x81a],[0x824,0x824],[0x828,0x828],[0x830,0x83e],[0x840,0x858],[0x85e,0x85e],[0x8a0,0x8a0],[0x8a2,0x8ac],[0x200f,0x200f],[0xfb1d,0xfb1d],[0xfb1f,0xfb28],[0xfb2a,0xfb36],[0xfb38,0xfb3c],[0xfb3e,0xfb3e],[0xfb40,0xfb41],[0xfb43,0xfb44],[0xfb46,0xfbc1],[0xfbd3,0xfd3d],[0xfd50,0xfd8f],[0xfd92,0xfdc7],[0xfdf0,0xfdfc],[0xfe70,0xfe74],[0xfe76,0xfefc],[0x10800,0x10805],[0x10808,0x10808],[0x1080a,0x10835],[0x10837,0x10838],[0x1083c,0x1083c],[0x1083f,0x10855],[0x10857,0x1085f],[0x10900,0x1091b],[0x10920,0x10939],[0x1093f,0x1093f],[0x10980,0x109b7],[0x109be,0x109bf],[0x10a00,0x10a00],[0x10a10,0x10a13],[0x10a15,0x10a17],[0x10a19,0x10a33],[0x10a40,0x10a47],[0x10a50,0x10a58],[0x10a60,0x10a7f],[0x10b00,0x10b35],[0x10b40,0x10b55],[0x10b58,0x10b72],[0x10b78,0x10b7f],[0x10c00,0x10c48],[0x1ee00,0x1ee03],[0x1ee05,0x1ee1f],[0x1ee21,0x1ee22],[0x1ee24,0x1ee24],[0x1ee27,0x1ee27],[0x1ee29,0x1ee32],[0x1ee34,0x1ee37],[0x1ee39,0x1ee39],[0x1ee3b,0x1ee3b],[0x1ee42,0x1ee42],[0x1ee47,0x1ee47],[0x1ee49,0x1ee49],[0x1ee4b,0x1ee4b],[0x1ee4d,0x1ee4f],[0x1ee51,0x1ee52],[0x1ee54,0x1ee54],[0x1ee57,0x1ee57],[0x1ee59,0x1ee59],[0x1ee5b,0x1ee5b],[0x1ee5d,0x1ee5d],[0x1ee5f,0x1ee5f],[0x1ee61,0x1ee62],[0x1ee64,0x1ee64],[0x1ee67,0x1ee6a],[0x1ee6c,0x1ee72],[0x1ee74,0x1ee77],[0x1ee79,0x1ee7c],[0x1ee7e,0x1ee7e],[0x1ee80,0x1ee89],[0x1ee8b,0x1ee9b],[0x1eea1,0x1eea3],[0x1eea5,0x1eea9],[0x1eeab,0x1eebb],[0x10fffd,0x10fffd]];function isStrongRTLChar(charCode){for(var i=0;i<strongRTLRanges.length;i++){var currentRange=strongRTLRanges[i];if(charCode>=currentRange[0]&&charCode<=currentRange[1]){return true;}}
return false;}
function determineBidi(cueDiv){var nodeStack=[],text="",charCode;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)/);if(m){nodeStack.length=0;return m[0];}
return text;}
if(node.tagName==="ruby"){return nextTextNode(nodeStack);}
if(node.childNodes){pushNodes(nodeStack,node);return nextTextNode(nodeStack);}}
pushNodes(nodeStack,cueDiv);while(text=nextTextNode(nodeStack)){for(var i=0;i<text.length;i++){charCode=text.charCodeAt(i);if(isStrongRTLChar(charCode)){return"rtl";}}}
return"ltr";}
function computeLinePos(cue){if(typeof cue.line==="number"&&(cue.snapToLines||cue.line>=0&&cue.line<=100)){return cue.line;}
if(!cue.track||!cue.track.textTrackList||!cue.track.textTrackList.mediaElement){return-1;}
var track=cue.track,trackList=track.textTrackList,count=0;for(var i=0;i<trackList.length&&trackList[i]!==track;i++){if(trackList[i].mode==="showing"){count++;}}
return++count*-1;}
function StyleBox(){}
StyleBox.prototype.applyStyles=function(styles,div){div=div||this.div;for(var prop in styles){if(styles.hasOwnProperty(prop)){div.style[prop]=styles[prop];}}};StyleBox.prototype.formatStyle=function(val,unit){return val===0?0:val+unit;};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":cue.vertical==="lr"?"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":cue.vertical==="lr"?"vertical-lr":"vertical-rl",unicodeBidi:"plaintext",textAlign:cue.align==="middle"?"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":textPos=cue.position;break;case"center":textPos=cue.position-cue.size/2;break;case"end":textPos=cue.position-cue.size;break;}
if(cue.vertical===""){this.applyStyles({left:this.formatStyle(textPos,"%"),width:this.formatStyle(cue.size,"%")});}else{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")});};}
CueStyleBox.prototype=_objCreate(StyleBox.prototype);CueStyleBox.prototype.constructor=CueStyleBox;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.width||width;this.lineHeight=lh!==undefined?lh:obj.lineHeight;}
BoxPosition.prototype.move=function(axis,toMove){toMove=toMove!==undefined?toMove:this.lineHeight;switch(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;break;}};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 true;}}
return false;};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){var x=Math.max(0,Math.min(this.right,b2.right)-Math.max(this.left,b2.left)),y=Math.max(0,Math.min(this.bottom,b2.bottom)-Math.max(this.top,b2.top)),intersectArea=x*y;return intersectArea/(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;var width=obj.div?obj.div.offsetWidth:obj.tagName?obj.offsetWidth:0;var top=obj.div?obj.div.offsetTop:obj.tagName?obj.offsetTop:0;obj=obj.div?obj.div.getBoundingClientRect():obj.tagName?obj.getBoundingClientRect():obj;var ret={left:obj.left,right:obj.right,top:obj.top||top,height:obj.height||height,bottom:obj.bottom||top+(obj.height||height),width:obj.width||width};return ret;};function moveBoxToLinePosition(window,styleBox,containerBox,boxPositions){function findBestPosition(b,axis){var bestPosition,specifiedPosition=new BoxPosition(b),percentage=1;for(var i=0;i<axis.length;i++){while(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);if(percentage>p){bestPosition=new BoxPosition(b);percentage=p;}
b=new BoxPosition(specifiedPosition);}
return bestPosition||specifiedPosition;}
var boxPosition=new BoxPosition(styleBox),cue=styleBox.cue,linePos=computeLinePos(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";break;}
var step=boxPosition.lineHeight,position=step*Math.round(linePos),maxPosition=containerBox[size]+step,initialAxis=axis[0];if(Math.abs(position)>maxPosition){position=position<0?-1:1;position*=Math.ceil(maxPosition/step)*step;}
if(linePos<0){position+=cue.vertical===""?containerBox.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;break;}
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,"%")});break;}
axis=["+y","-x","+x","-y"];boxPosition=new BoxPosition(styleBox);}
var bestPosition=findBestPosition(boxPosition,axis);styleBox.move(bestPosition.toCSSCompatValues(containerBox));}
function WebVTT$1(){}
WebVTT$1.StringDecoder=function(){return{decode:function decode(data){if(!data){return"";}
if(typeof data!=="string"){throw new Error("Error - expected string data.");}
return decodeURIComponent(encodeURIComponent(data));}};};WebVTT$1.convertCueToDOMTree=function(window,cuetext){if(!window||!cuetext){return null;}
return parseContent(window,cuetext);};var FONT_SIZE_PERCENT=0.05;var FONT_STYLE="sans-serif";var CUE_BACKGROUND_PADDING="1.5%";WebVTT$1.processCues=function(window,cues,overlay){if(!window||!cues||!overlay){return null;}
while(overlay.firstChild){overlay.removeChild(overlay.firstChild);}
var paddedOverlay=window.document.createElement("div");paddedOverlay.style.position="absolute";paddedOverlay.style.left="0";paddedOverlay.style.right="0";paddedOverlay.style.top="0";paddedOverlay.style.bottom="0";paddedOverlay.style.margin=CUE_BACKGROUND_PADDING;overlay.appendChild(paddedOverlay);function shouldCompute(cues){for(var i=0;i<cues.length;i++){if(cues[i].hasBeenReset||!cues[i].displayState){return true;}}
return false;}
if(!shouldCompute(cues)){for(var i=0;i<cues.length;i++){paddedOverlay.appendChild(cues[i].displayState);}
return;}
var boxPositions=[],containerBox=BoxPosition.getSimpleBoxPosition(paddedOverlay),fontSize=Math.round(containerBox.height*FONT_SIZE_PERCENT*100)/100;var styleOptions={font:fontSize+"px "+FONT_STYLE};(function(){var styleBox,cue;for(var i=0;i<cues.length;i++){cue=cues[i];styleBox=new CueStyleBox(window,cue,styleOptions);paddedOverlay.appendChild(styleBox.div);moveBoxToLinePosition(window,styleBox,containerBox,boxPositions);cue.displayState=styleBox.div;boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));}})();};WebVTT$1.Parser=function(window,vttjs,decoder){if(!decoder){decoder=vttjs;vttjs={};}
if(!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={reportOrThrowError:function reportOrThrowError(e){if(e instanceof ParsingError){this.onparsingerror&&this.onparsingerror(e);}else{throw e;}},parse:function parse(data){var self=this;if(data){self.buffer+=self.decoder.decode(data,{stream:true});}
function collectNextLine(){var buffer=self.buffer;var pos=0;while(pos<buffer.length&&buffer[pos]!=='\r'&&buffer[pos]!=='\n'){++pos;}
var line=buffer.substr(0,pos);if(buffer[pos]==='\r'){++pos;}
if(buffer[pos]==='\n'){++pos;}
self.buffer=buffer.substr(pos);return line;}
function parseRegion(input){var settings=new Settings();parseOptions(input,function(k,v){switch(k){case"id":settings.set(k,v);break;case"width":settings.percent(k,v);break;case"lines":settings.integer(k,v);break;case"regionanchor":case"viewportanchor":var xy=v.split(',');if(xy.length!==2){break;}
var anchor=new Settings();anchor.percent("x",xy[0]);anchor.percent("y",xy[1]);if(!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"]);break;}},/=/,/\s/);if(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});}}
function parseTimestampMap(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));break;}},/[^\d]:/,/,/);self.ontimestampmap&&self.ontimestampmap({"MPEGTS":settings.get("MPEGTS"),"LOCAL":settings.get("LOCAL")});}
function parseHeader(input){if(input.match(/X-TIMESTAMP-MAP/)){parseOptions(input,function(k,v){switch(k){case"X-TIMESTAMP-MAP":parseTimestampMap(v);break;}},/=/);}else{parseOptions(input,function(k,v){switch(k){case"Region":parseRegion(v);break;}},/:/);}}
try{var line;if(self.state==="INITIAL"){if(!/\r\n|\n/.test(self.buffer)){return this;}
line=collectNextLine();var m=line.match(/^WEBVTT([ \t].*)?$/);if(!m||!m[0]){throw new ParsingError(ParsingError.Errors.BadSignature);}
self.state="HEADER";}
var alreadyCollectedLine=false;while(self.buffer){if(!/\r\n|\n/.test(self.buffer)){return this;}
if(!alreadyCollectedLine){line=collectNextLine();}else{alreadyCollectedLine=false;}
switch(self.state){case"HEADER":if(/:/.test(line)){parseHeader(line);}else if(!line){self.state="ID";}
continue;case"NOTE":if(!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";}
self.state="CUE";if(line.indexOf("-->")===-1){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=line.indexOf("-->")!==-1;if(!line||hasSubstring&&(alreadyCollectedLine=true)){self.oncue&&self.oncue(self.cue);self.cue=null;self.state="ID";continue;}
if(self.cue.text){self.cue.text+="\n";}
self.cue.text+=line.replace(/\u2028/g,'\n').replace(/u2029/g,'\n');continue;case"BADCUE":if(!line){self.state="ID";}
continue;}}}catch(e){self.reportOrThrowError(e);if(self.state==="CUETEXT"&&self.cue&&self.oncue){self.oncue(self.cue);}
self.cue=null;self.state=self.state==="INITIAL"?"BADWEBVTT":"BADCUE";}
return this;},flush:function flush(){var self=this;try{self.buffer+=self.decoder.decode();if(self.cue||self.state==="HEADER"){self.buffer+="\n\n";self.parse();}
if(self.state==="INITIAL"){throw new ParsingError(ParsingError.Errors.BadSignature);}}catch(e){self.reportOrThrowError(e);}
self.onflush&&self.onflush();return this;}};var vtt=WebVTT$1;var autoKeyword="auto";var directionSetting={"":1,"lr":1,"rl":1};var alignSetting={"start":1,"center":1,"end":1,"left":1,"right":1,"auto":1,"line-left":1,"line-right":1};function findDirectionSetting(value){if(typeof value!=="string"){return false;}
var dir=directionSetting[value.toLowerCase()];return dir?value.toLowerCase():false;}
function findAlignSetting(value){if(typeof value!=="string"){return false;}
var align=alignSetting[value.toLowerCase()];return align?value.toLowerCase():false;}
function VTTCue(startTime,endTime,text){this.hasBeenReset=false;var _id="";var _pauseOnExit=false;var _startTime=startTime;var _endTime=endTime;var _text=text;var _region=null;var _vertical="";var _snapToLines=true;var _line="auto";var _lineAlign="start";var _position="auto";var _positionAlign="auto";var _size=100;var _align="center";Object.defineProperties(this,{"id":{enumerable:true,get:function get(){return _id;},set:function set(value){_id=""+value;}},"pauseOnExit":{enumerable:true,get:function get(){return _pauseOnExit;},set:function set(value){_pauseOnExit=!!value;}},"startTime":{enumerable:true,get:function get(){return _startTime;},set:function set(value){if(typeof value!=="number"){throw new TypeError("Start time must be set to a number.");}
_startTime=value;this.hasBeenReset=true;}},"endTime":{enumerable:true,get:function get(){return _endTime;},set:function set(value){if(typeof value!=="number"){throw new TypeError("End time must be set to a number.");}
_endTime=value;this.hasBeenReset=true;}},"text":{enumerable:true,get:function get(){return _text;},set:function set(value){_text=""+value;this.hasBeenReset=true;}},"region":{enumerable:true,get:function get(){return _region;},set:function set(value){_region=value;this.hasBeenReset=true;}},"vertical":{enumerable:true,get:function get(){return _vertical;},set:function set(value){var setting=findDirectionSetting(value);if(setting===false){throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");}
_vertical=setting;this.hasBeenReset=true;}},"snapToLines":{enumerable:true,get:function get(){return _snapToLines;},set:function set(value){_snapToLines=!!value;this.hasBeenReset=true;}},"line":{enumerable:true,get:function get(){return _line;},set:function set(value){if(typeof value!=="number"&&value!==autoKeyword){throw new SyntaxError("Line: an invalid number or illegal string was specified.");}
_line=value;this.hasBeenReset=true;}},"lineAlign":{enumerable:true,get:function get(){return _lineAlign;},set:function set(value){var setting=findAlignSetting(value);if(!setting){console.warn("lineAlign: an invalid or illegal string was specified.");}else{_lineAlign=setting;this.hasBeenReset=true;}}},"position":{enumerable:true,get:function get(){return _position;},set:function set(value){if(value<0||value>100){throw new Error("Position must be between 0 and 100.");}
_position=value;this.hasBeenReset=true;}},"positionAlign":{enumerable:true,get:function get(){return _positionAlign;},set:function set(value){var setting=findAlignSetting(value);if(!setting){console.warn("positionAlign: an invalid or illegal string was specified.");}else{_positionAlign=setting;this.hasBeenReset=true;}}},"size":{enumerable:true,get:function get(){return _size;},set:function set(value){if(value<0||value>100){throw new Error("Size must be between 0 and 100.");}
_size=value;this.hasBeenReset=true;}},"align":{enumerable:true,get:function get(){return _align;},set:function set(value){var setting=findAlignSetting(value);if(!setting){throw new SyntaxError("align: an invalid or illegal alignment string was specified.");}
_align=setting;this.hasBeenReset=true;}}});this.displayState=undefined;}
VTTCue.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text);};var vttcue=VTTCue;var scrollSetting={"":true,"up":true};function findScrollSetting(value){if(typeof value!=="string"){return false;}
var scroll=scrollSetting[value.toLowerCase()];return scroll?value.toLowerCase():false;}
function isValidPercentValue(value){return typeof value==="number"&&value>=0&&value<=100;}
function VTTRegion(){var _width=100;var _lines=3;var _regionAnchorX=0;var _regionAnchorY=100;var _viewportAnchorX=0;var _viewportAnchorY=100;var _scroll="";Object.defineProperties(this,{"width":{enumerable:true,get:function get(){return _width;},set:function set(value){if(!isValidPercentValue(value)){throw new Error("Width must be between 0 and 100.");}
_width=value;}},"lines":{enumerable:true,get:function get(){return _lines;},set:function set(value){if(typeof value!=="number"){throw new TypeError("Lines must be set to a number.");}
_lines=value;}},"regionAnchorY":{enumerable:true,get:function get(){return _regionAnchorY;},set:function set(value){if(!isValidPercentValue(value)){throw new Error("RegionAnchorX must be between 0 and 100.");}
_regionAnchorY=value;}},"regionAnchorX":{enumerable:true,get:function get(){return _regionAnchorX;},set:function set(value){if(!isValidPercentValue(value)){throw new Error("RegionAnchorY must be between 0 and 100.");}
_regionAnchorX=value;}},"viewportAnchorY":{enumerable:true,get:function get(){return _viewportAnchorY;},set:function set(value){if(!isValidPercentValue(value)){throw new Error("ViewportAnchorY must be between 0 and 100.");}
_viewportAnchorY=value;}},"viewportAnchorX":{enumerable:true,get:function get(){return _viewportAnchorX;},set:function set(value){if(!isValidPercentValue(value)){throw new Error("ViewportAnchorX must be between 0 and 100.");}
_viewportAnchorX=value;}},"scroll":{enumerable:true,get:function get(){return _scroll;},set:function set(value){var setting=findScrollSetting(value);if(setting===false){console.warn("Scroll: an invalid or illegal string was specified.");}else{_scroll=setting;}}}});}
var vttregion=VTTRegion;var 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;var regionShim=vttjs.VTTRegion;var nativeVTTCue=window_1.VTTCue;var nativeVTTRegion=window_1.VTTRegion;vttjs.shim=function(){window_1.VTTCue=cueShim;window_1.VTTRegion=regionShim;};vttjs.restore=function(){window_1.VTTCue=nativeVTTCue;window_1.VTTRegion=nativeVTTRegion;};if(!window_1.VTTCue){vttjs.shim();}});var browserIndex_1=browserIndex.WebVTT;var browserIndex_2=browserIndex.VTTCue;var browserIndex_3=browserIndex.VTTRegion;function createTrackHelper(self,kind,label,language,options){if(options===void 0){options={};}
var tracks=self.textTracks();options.kind=kind;if(label){options.label=label;}
if(language){options.language=language;}
options.tech=self;var track=new ALL.text.TrackClass(options);tracks.addTrack(track);return track;}
var Tech=function(_Component){inheritsLoose(Tech,_Component);function Tech(options,ready){var _this;if(options===void 0){options={};}
if(ready===void 0){ready=function ready(){};}
options.reportTouchActivity=false;_this=_Component.call(this,null,options,ready)||this;_this.hasStarted_=false;_this.on('playing',function(){this.hasStarted_=true;});_this.on('loadstart',function(){this.hasStarted_=false;});ALL.names.forEach(function(name){var props=ALL[name];if(options&&options[props.getterName]){_this[props.privateName]=options[props.getterName];}});if(!_this.featuresProgressEvents){_this.manualProgressOn();}
if(!_this.featuresTimeupdateEvents){_this.manualTimeUpdatesOn();}
['Text','Audio','Video'].forEach(function(track){if(options["native"+track+"Tracks"]===false){_this["featuresNative"+track+"Tracks"]=false;}});if(options.nativeCaptions===false||options.nativeTextTracks===false){_this.featuresNativeTextTracks=false;}else if(options.nativeCaptions===true||options.nativeTextTracks===true){_this.featuresNativeTextTracks=true;}
if(!_this.featuresNativeTextTracks){_this.emulateTextTracks();}
_this.preloadTextTracks=options.preloadTextTracks!==false;_this.autoRemoteTextTracks_=new ALL.text.ListClass();_this.initTrackListeners();if(!options.nativeControlsForTouch){_this.emitTapEvents();}
if(_this.constructor){_this.name_=_this.constructor.name||'Unknown Tech';}
return _this;}
var _proto=Tech.prototype;_proto.triggerSourceset=function triggerSourceset(src){var _this2=this;if(!this.isReady_){this.one('ready',function(){return _this2.setTimeout(function(){return _this2.triggerSourceset(src);},1);});}
this.trigger({src:src,type:'sourceset'});};_proto.manualProgressOn=function manualProgressOn(){this.on('durationchange',this.onDurationChange);this.manualProgress=true;this.one('ready',this.trackProgress);};_proto.manualProgressOff=function manualProgressOff(){this.manualProgress=false;this.stopTrackingProgress();this.off('durationchange',this.onDurationChange);};_proto.trackProgress=function trackProgress(event){this.stopTrackingProgress();this.progressInterval=this.setInterval(bind(this,function(){var numBufferedPercent=this.bufferedPercent();if(this.bufferedPercent_!==numBufferedPercent){this.trigger('progress');}
this.bufferedPercent_=numBufferedPercent;if(numBufferedPercent===1){this.stopTrackingProgress();}}),500);};_proto.onDurationChange=function onDurationChange(event){this.duration_=this.duration();};_proto.buffered=function buffered(){return createTimeRanges(0,0);};_proto.bufferedPercent=function bufferedPercent$1(){return bufferedPercent(this.buffered(),this.duration_);};_proto.stopTrackingProgress=function stopTrackingProgress(){this.clearInterval(this.progressInterval);};_proto.manualTimeUpdatesOn=function manualTimeUpdatesOn(){this.manualTimeUpdates=true;this.on('play',this.trackCurrentTime);this.on('pause',this.stopTrackingCurrentTime);};_proto.manualTimeUpdatesOff=function manualTimeUpdatesOff(){this.manualTimeUpdates=false;this.stopTrackingCurrentTime();this.off('play',this.trackCurrentTime);this.off('pause',this.stopTrackingCurrentTime);};_proto.trackCurrentTime=function trackCurrentTime(){if(this.currentTimeInterval){this.stopTrackingCurrentTime();}
this.currentTimeInterval=this.setInterval(function(){this.trigger({type:'timeupdate',target:this,manuallyTriggered:true});},250);};_proto.stopTrackingCurrentTime=function stopTrackingCurrentTime(){this.clearInterval(this.currentTimeInterval);this.trigger({type:'timeupdate',target:this,manuallyTriggered:true});};_proto.dispose=function dispose(){this.clearTracks(NORMAL.names);if(this.manualProgress){this.manualProgressOff();}
if(this.manualTimeUpdates){this.manualTimeUpdatesOff();}
_Component.prototype.dispose.call(this);};_proto.clearTracks=function clearTracks(types){var _this3=this;types=[].concat(types);types.forEach(function(type){var list=_this3[type+"Tracks"]()||[];var i=list.length;while(i--){var track=list[i];if(type==='text'){_this3.removeRemoteTextTrack(track);}
list.removeTrack(track);}});};_proto.cleanupAutoTextTracks=function cleanupAutoTextTracks(){var list=this.autoRemoteTextTracks_||[];var i=list.length;while(i--){var track=list[i];this.removeRemoteTextTrack(track);}};_proto.reset=function reset(){};_proto.crossOrigin=function crossOrigin(){};_proto.setCrossOrigin=function setCrossOrigin(){};_proto.error=function error(err){if(err!==undefined){this.error_=new MediaError(err);this.trigger('error');}
return this.error_;};_proto.played=function played(){if(this.hasStarted_){return createTimeRanges(0,0);}
return createTimeRanges();};_proto.play=function play(){};_proto.setScrubbing=function setScrubbing(){};_proto.scrubbing=function scrubbing(){};_proto.setCurrentTime=function setCurrentTime(){if(this.manualTimeUpdates){this.trigger({type:'timeupdate',target:this,manuallyTriggered:true});}};_proto.initTrackListeners=function initTrackListeners(){var _this4=this;NORMAL.names.forEach(function(name){var props=NORMAL[name];var trackListChanges=function trackListChanges(){_this4.trigger(name+"trackchange");};var tracks=_this4[props.getterName]();tracks.addEventListener('removetrack',trackListChanges);tracks.addEventListener('addtrack',trackListChanges);_this4.on('dispose',function(){tracks.removeEventListener('removetrack',trackListChanges);tracks.removeEventListener('addtrack',trackListChanges);});});};_proto.addWebVttScript_=function addWebVttScript_(){var _this5=this;if(window_1.WebVTT){return;}
if(document_1.body.contains(this.el())){if(!this.options_['vtt.js']&&isPlain(browserIndex)&&Object.keys(browserIndex).length>0){this.trigger('vttjsloaded');return;}
var script=document_1.createElement('script');script.src=this.options_['vtt.js']||'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';script.onload=function(){_this5.trigger('vttjsloaded');};script.onerror=function(){_this5.trigger('vttjserror');};this.on('dispose',function(){script.onload=null;script.onerror=null;});window_1.WebVTT=true;this.el().parentNode.appendChild(script);}else{this.ready(this.addWebVttScript_);}};_proto.emulateTextTracks=function emulateTextTracks(){var _this6=this;var tracks=this.textTracks();var remoteTracks=this.remoteTextTracks();var handleAddTrack=function handleAddTrack(e){return tracks.addTrack(e.track);};var handleRemoveTrack=function handleRemoveTrack(e){return tracks.removeTrack(e.track);};remoteTracks.on('addtrack',handleAddTrack);remoteTracks.on('removetrack',handleRemoveTrack);this.addWebVttScript_();var updateDisplay=function updateDisplay(){return _this6.trigger('texttrackchange');};var textTracksChanges=function textTracksChanges(){updateDisplay();for(var i=0;i<tracks.length;i++){var track=tracks[i];track.removeEventListener('cuechange',updateDisplay);if(track.mode==='showing'){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(var i=0;i<tracks.length;i++){var track=tracks[i];track.removeEventListener('cuechange',updateDisplay);}});};_proto.addTextTrack=function addTextTrack(kind,label,language){if(!kind){throw new Error('TextTrack kind is required but was not provided');}
return createTrackHelper(this,kind,label,language);};_proto.createRemoteTextTrack=function createRemoteTextTrack(options){var track=mergeOptions(options,{tech:this});return new REMOTE.remoteTextEl.TrackClass(track);};_proto.addRemoteTextTrack=function addRemoteTextTrack(options,manualCleanup){var _this7=this;if(options===void 0){options={};}
var htmlTrackElement=this.createRemoteTextTrack(options);if(manualCleanup!==true&&manualCleanup!==false){log.warn('Calling addRemoteTextTrack without explicitly setting the "manualCleanup" parameter to `true` is deprecated and default to `false` in future version of video.js');manualCleanup=true;}
this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);this.remoteTextTracks().addTrack(htmlTrackElement.track);if(manualCleanup!==true){this.ready(function(){return _this7.autoRemoteTextTracks_.addTrack(htmlTrackElement.track);});}
return htmlTrackElement;};_proto.removeRemoteTextTrack=function removeRemoteTextTrack(track){var trackElement=this.remoteTextTrackEls().getTrackElementByTrack_(track);this.remoteTextTrackEls().removeTrackElement_(trackElement);this.remoteTextTracks().removeTrack(track);this.autoRemoteTextTracks_.removeTrack(track);};_proto.getVideoPlaybackQuality=function getVideoPlaybackQuality(){return{};};_proto.requestPictureInPicture=function requestPictureInPicture(){var PromiseClass=this.options_.Promise||window_1.Promise;if(PromiseClass){return PromiseClass.reject();}};_proto.disablePictureInPicture=function disablePictureInPicture(){return true;};_proto.setDisablePictureInPicture=function setDisablePictureInPicture(){};_proto.setPoster=function setPoster(){};_proto.playsinline=function playsinline(){};_proto.setPlaysinline=function setPlaysinline(){};_proto.overrideNativeAudioTracks=function overrideNativeAudioTracks(){};_proto.overrideNativeVideoTracks=function overrideNativeVideoTracks(){};_proto.canPlayType=function canPlayType(){return'';};Tech.canPlayType=function canPlayType(){return'';};Tech.canPlaySource=function canPlaySource(srcObj,options){return Tech.canPlayType(srcObj.type);};Tech.isTech=function isTech(component){return component.prototype instanceof Tech||component instanceof Tech||component===Tech;};Tech.registerTech=function registerTech(name,tech){if(!Tech.techs_){Tech.techs_={};}
if(!Tech.isTech(tech)){throw new Error("Tech "+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');}
name=toTitleCase(name);Tech.techs_[name]=tech;Tech.techs_[toLowerCase(name)]=tech;if(name!=='Tech'){Tech.defaultTechOrder_.push(name);}
return tech;};Tech.getTech=function getTech(name){if(!name){return;}
if(Tech.techs_&&Tech.techs_[name]){return Tech.techs_[name];}
name=toTitleCase(name);if(window_1&&window_1.videojs&&window_1.videojs[name]){log.warn("The "+name+" tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)");return window_1.videojs[name];}};return Tech;}(Component);ALL.names.forEach(function(name){var props=ALL[name];Tech.prototype[props.getterName]=function(){this[props.privateName]=this[props.privateName]||new props.ListClass();return this[props.privateName];};});Tech.prototype.featuresVolumeControl=true;Tech.prototype.featuresMuteControl=true;Tech.prototype.featuresFullscreenResize=false;Tech.prototype.featuresPlaybackRate=false;Tech.prototype.featuresProgressEvents=false;Tech.prototype.featuresSourceset=false;Tech.prototype.featuresTimeupdateEvents=false;Tech.prototype.featuresNativeTextTracks=false;Tech.withSourceHandlers=function(_Tech){_Tech.registerSourceHandler=function(handler,index){var handlers=_Tech.sourceHandlers;if(!handlers){handlers=_Tech.sourceHandlers=[];}
if(index===undefined){index=handlers.length;}
handlers.splice(index,0,handler);};_Tech.canPlayType=function(type){var handlers=_Tech.sourceHandlers||[];var can;for(var i=0;i<handlers.length;i++){can=handlers[i].canPlayType(type);if(can){return can;}}
return'';};_Tech.selectSourceHandler=function(source,options){var handlers=_Tech.sourceHandlers||[];var can;for(var i=0;i<handlers.length;i++){can=handlers[i].canHandleSource(source,options);if(can){return handlers[i];}}
return null;};_Tech.canPlaySource=function(srcObj,options){var sh=_Tech.selectSourceHandler(srcObj,options);if(sh){return sh.canHandleSource(srcObj,options);}
return'';};var deferrable=['seekable','seeking','duration'];deferrable.forEach(function(fnName){var originalFn=this[fnName];if(typeof originalFn!=='function'){return;}
this[fnName]=function(){if(this.sourceHandler_&&this.sourceHandler_[fnName]){return this.sourceHandler_[fnName].apply(this.sourceHandler_,arguments);}
return originalFn.apply(this,arguments);};},_Tech.prototype);_Tech.prototype.setSource=function(source){var sh=_Tech.selectSourceHandler(source,this.options_);if(!sh){if(_Tech.nativeSourceHandler){sh=_Tech.nativeSourceHandler;}else{log.error('No source handler found for the current source.');}}
this.disposeSourceHandler();this.off('dispose',this.disposeSourceHandler);if(sh!==_Tech.nativeSourceHandler){this.currentSource_=source;}
this.sourceHandler_=sh.handleSource(source,this,this.options_);this.one('dispose',this.disposeSourceHandler);};_Tech.prototype.disposeSourceHandler=function(){if(this.currentSource_){this.clearTracks(['audio','video']);this.currentSource_=null;}
this.cleanupAutoTextTracks();if(this.sourceHandler_){if(this.sourceHandler_.dispose){this.sourceHandler_.dispose();}
this.sourceHandler_=null;}};};Component.registerComponent('Tech',Tech);Tech.registerTech('Tech',Tech);Tech.defaultTechOrder_=[];var middlewares={};var middlewareInstances={};var TERMINATOR={};function use(type,middleware){middlewares[type]=middlewares[type]||[];middlewares[type].push(middleware);}
function setSource(player,src,next){player.setTimeout(function(){return setSourceHelper(src,middlewares[src.type],next,player);},1);}
function setTech(middleware,tech){middleware.forEach(function(mw){return mw.setTech&&mw.setTech(tech);});}
function get(middleware,tech,method){return middleware.reduceRight(middlewareIterator(method),tech[method]());}
function set(middleware,tech,method,arg){return tech[method](middleware.reduce(middlewareIterator(method),arg));}
function mediate(middleware,tech,method,arg){if(arg===void 0){arg=null;}
var callMethod='call'+toTitleCase(method);var middlewareValue=middleware.reduce(middlewareIterator(callMethod),arg);var terminated=middlewareValue===TERMINATOR;var returnValue=terminated?null:tech[method](middlewareValue);executeRight(middleware,method,returnValue,terminated);return returnValue;}
var allowedGetters={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1};var allowedSetters={setCurrentTime:1,setMuted:1,setVolume:1};var allowedMediators={play:1,pause:1};function middlewareIterator(method){return function(value,mw){if(value===TERMINATOR){return TERMINATOR;}
if(mw[method]){return mw[method](value);}
return value;};}
function executeRight(mws,method,value,terminated){for(var i=mws.length-1;i>=0;i--){var mw=mws[i];if(mw[method]){mw[method](terminated,value);}}}
function clearCacheForPlayer(player){middlewareInstances[player.id()]=null;}
function getOrCreateFactory(player,mwFactory){var mws=middlewareInstances[player.id()];var mw=null;if(mws===undefined||mws===null){mw=mwFactory(player);middlewareInstances[player.id()]=[[mwFactory,mw]];return mw;}
for(var i=0;i<mws.length;i++){var _mws$i=mws[i],mwf=_mws$i[0],mwi=_mws$i[1];if(mwf!==mwFactory){continue;}
mw=mwi;}
if(mw===null){mw=mwFactory(player);mws.push([mwFactory,mw]);}
return mw;}
function setSourceHelper(src,middleware,next,player,acc,lastRun){if(src===void 0){src={};}
if(middleware===void 0){middleware=[];}
if(acc===void 0){acc=[];}
if(lastRun===void 0){lastRun=false;}
var _middleware=middleware,mwFactory=_middleware[0],mwrest=_middleware.slice(1);if(typeof mwFactory==='string'){setSourceHelper(src,middlewares[mwFactory],next,player,acc,lastRun);}else if(mwFactory){var mw=getOrCreateFactory(player,mwFactory);if(!mw.setSource){acc.push(mw);return setSourceHelper(src,mwrest,next,player,acc,lastRun);}
mw.setSource(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 if(mwrest.length){setSourceHelper(src,mwrest,next,player,acc,lastRun);}else if(lastRun){next(src,acc);}else{setSourceHelper(src,middlewares['*'],next,player,acc,true);}}
var 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',jpg:'image/jpeg',jpeg:'image/jpeg',gif:'image/gif',png:'image/png',svg:'image/svg+xml',webp:'image/webp'};var getMimetype=function getMimetype(src){if(src===void 0){src='';}
var ext=getFileExtension(src);var mimetype=MimetypesKind[ext.toLowerCase()];return mimetype||'';};var findMimetype=function findMimetype(player,src){if(!src){return'';}
if(player.cache_.source.src===src&&player.cache_.source.type){return player.cache_.source.type;}
var matchingSources=player.cache_.sources.filter(function(s){return s.src===src;});if(matchingSources.length){return matchingSources[0].type;}
var sources=player.$$('source');for(var i=0;i<sources.length;i++){var s=sources[i];if(s.type&&s.src&&s.src===src){return s.type;}}
return getMimetype(src);};var filterSource=function filterSource(src){if(Array.isArray(src)){var newsrc=[];src.forEach(function(srcobj){srcobj=filterSource(srcobj);if(Array.isArray(srcobj)){newsrc=newsrc.concat(srcobj);}else if(isObject(srcobj)){newsrc.push(srcobj);}});src=newsrc;}else if(typeof src==='string'&&src.trim()){src=[fixSource({src:src})];}else if(isObject(src)&&typeof src.src==='string'&&src.src&&src.src.trim()){src=[fixSource(src)];}else{src=[];}
return src;};function fixSource(src){if(!src.type){var mimetype=getMimetype(src.src);if(mimetype){src.type=mimetype;}}
return src;}
var MediaLoader=function(_Component){inheritsLoose(MediaLoader,_Component);function MediaLoader(player,options,ready){var _this;var options_=mergeOptions({createEl:false},options);_this=_Component.call(this,player,options_,ready)||this;if(!options.playerOptions.sources||options.playerOptions.sources.length===0){for(var i=0,j=options.playerOptions.techOrder;i<j.length;i++){var techName=toTitleCase(j[i]);var tech=Tech.getTech(techName);if(!techName){tech=Component.getComponent(techName);}
if(tech&&tech.isSupported()){player.loadTech_(techName);break;}}}else{player.src(options.playerOptions.sources);}
return _this;}
return MediaLoader;}(Component);Component.registerComponent('MediaLoader',MediaLoader);var ClickableComponent=function(_Component){inheritsLoose(ClickableComponent,_Component);function ClickableComponent(player,options){var _this;_this=_Component.call(this,player,options)||this;_this.emitTapEvents();_this.enable();return _this;}
var _proto=ClickableComponent.prototype;_proto.createEl=function createEl(tag,props,attributes){if(tag===void 0){tag='div';}
if(props===void 0){props={};}
if(attributes===void 0){attributes={};}
props=assign({innerHTML:'<span aria-hidden="true" class="vjs-icon-placeholder"></span>',className:this.buildCSSClass(),tabIndex:0},props);if(tag==='button'){log.error("Creating a ClickableComponent with an HTML element of "+tag+" is not supported; use a Button instead.");}
attributes=assign({role:'button'},attributes);this.tabIndex_=props.tabIndex;var el=_Component.prototype.createEl.call(this,tag,props,attributes);this.createControlTextEl(el);return el;};_proto.dispose=function dispose(){this.controlTextEl_=null;_Component.prototype.dispose.call(this);};_proto.createControlTextEl=function createControlTextEl(el){this.controlTextEl_=createEl('span',{className:'vjs-control-text'},{'aria-live':'polite'});if(el){el.appendChild(this.controlTextEl_);}
this.controlText(this.controlText_,el);return this.controlTextEl_;};_proto.controlText=function controlText(text,el){if(el===void 0){el=this.el();}
if(text===undefined){return this.controlText_||'Need Text';}
var localizedText=this.localize(text);this.controlText_=text;textContent(this.controlTextEl_,localizedText);if(!this.nonIconControl){el.setAttribute('title',localizedText);}};_proto.buildCSSClass=function buildCSSClass(){return"vjs-control vjs-button "+_Component.prototype.buildCSSClass.call(this);};_proto.enable=function enable(){if(!this.enabled_){this.enabled_=true;this.removeClass('vjs-disabled');this.el_.setAttribute('aria-disabled','false');if(typeof this.tabIndex_!=='undefined'){this.el_.setAttribute('tabIndex',this.tabIndex_);}
this.on(['tap','click'],this.handleClick);this.on('keydown',this.handleKeyDown);}};_proto.disable=function disable(){this.enabled_=false;this.addClass('vjs-disabled');this.el_.setAttribute('aria-disabled','true');if(typeof this.tabIndex_!=='undefined'){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);};_proto.handleLanguagechange=function handleLanguagechange(){this.controlText(this.controlText_);};_proto.handleClick=function handleClick(event){if(this.options_.clickHandler){this.options_.clickHandler.call(this,arguments);}};_proto.handleKeyDown=function handleKeyDown(event){if(keycode.isEventKey(event,'Space')||keycode.isEventKey(event,'Enter')){event.preventDefault();event.stopPropagation();this.trigger('click');}else{_Component.prototype.handleKeyDown.call(this,event);}};return ClickableComponent;}(Component);Component.registerComponent('ClickableComponent',ClickableComponent);var PosterImage=function(_ClickableComponent){inheritsLoose(PosterImage,_ClickableComponent);function PosterImage(player,options){var _this;_this=_ClickableComponent.call(this,player,options)||this;_this.update();player.on('posterchange',bind(assertThisInitialized(_this),_this.update));return _this;}
var _proto=PosterImage.prototype;_proto.dispose=function dispose(){this.player().off('posterchange',this.update);_ClickableComponent.prototype.dispose.call(this);};_proto.createEl=function createEl$1(){var el=createEl('div',{className:'vjs-poster',tabIndex:-1});return el;};_proto.update=function update(event){var url=this.player().poster();this.setSrc(url);if(url){this.show();}else{this.hide();}};_proto.setSrc=function setSrc(url){var backgroundImage='';if(url){backgroundImage="url(\""+url+"\")";}
this.el_.style.backgroundImage=backgroundImage;};_proto.handleClick=function handleClick(event){if(!this.player_.controls()){return;}
var sourceIsEncrypted=this.player_.usingPlugin('eme')&&this.player_.eme.sessions&&this.player_.eme.sessions.length>0;if(this.player_.tech(true)&&!((IE_VERSION||IS_EDGE)&&sourceIsEncrypted)){this.player_.tech(true).focus();}
if(this.player_.paused()){silencePromise(this.player_.play());}else{this.player_.pause();}};return PosterImage;}(ClickableComponent);Component.registerComponent('PosterImage',PosterImage);var darkGray='#222';var lightGray='#ccc';var fontMap={monospace:'monospace',sansSerif:'sans-serif',serif:'serif',monospaceSansSerif:'"Andale Mono", "Lucida Console", monospace',monospaceSerif:'"Courier New", monospace',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){var hex;if(color.length===4){hex=color[1]+color[1]+color[2]+color[2]+color[3]+color[3];}else if(color.length===7){hex=color.slice(1);}else{throw new Error('Invalid color code provided, '+color+'; must be formatted as e.g. #f0e or #f604e2.');}
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;}}
var TextTrackDisplay=function(_Component){inheritsLoose(TextTrackDisplay,_Component);function TextTrackDisplay(player,options,ready){var _this;_this=_Component.call(this,player,options,ready)||this;var updateDisplayHandler=bind(assertThisInitialized(_this),_this.updateDisplay);player.on('loadstart',bind(assertThisInitialized(_this),_this.toggleDisplay));player.on('texttrackchange',updateDisplayHandler);player.on('loadedmetadata',bind(assertThisInitialized(_this),_this.preselectTrack));player.ready(bind(assertThisInitialized(_this),function(){if(player.tech_&&player.tech_.featuresNativeTextTracks){this.hide();return;}
player.on('fullscreenchange',updateDisplayHandler);player.on('playerresize',updateDisplayHandler);window_1.addEventListener('orientationchange',updateDisplayHandler);player.on('dispose',function(){return window_1.removeEventListener('orientationchange',updateDisplayHandler);});var tracks=this.options_.playerOptions.tracks||[];for(var i=0;i<tracks.length;i++){this.player_.addRemoteTextTrack(tracks[i],true);}
this.preselectTrack();}));return _this;}
var _proto=TextTrackDisplay.prototype;_proto.preselectTrack=function preselectTrack(){var modes={captions:1,subtitles:1};var trackList=this.player_.textTracks();var userPref=this.player_.cache_.selectedLanguage;var firstDesc;var firstCaptions;var preferredTrack;for(var i=0;i<trackList.length;i++){var track=trackList[i];if(userPref&&userPref.enabled&&userPref.language&&userPref.language===track.language&&track.kind in modes){if(track.kind===userPref.kind){preferredTrack=track;}else if(!preferredTrack){preferredTrack=track;}}else if(userPref&&!userPref.enabled){preferredTrack=null;firstDesc=null;firstCaptions=null;}else if(track["default"]){if(track.kind==='descriptions'&&!firstDesc){firstDesc=track;}else if(track.kind in modes&&!firstCaptions){firstCaptions=track;}}}
if(preferredTrack){preferredTrack.mode='showing';}else if(firstCaptions){firstCaptions.mode='showing';}else if(firstDesc){firstDesc.mode='showing';}};_proto.toggleDisplay=function toggleDisplay(){if(this.player_.tech_&&this.player_.tech_.featuresNativeTextTracks){this.hide();}else{this.show();}};_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'div',{className:'vjs-text-track-display'},{'aria-live':'off','aria-atomic':'true'});};_proto.clearDisplay=function clearDisplay(){if(typeof window_1.WebVTT==='function'){window_1.WebVTT.processCues(window_1,[],this.el_);}};_proto.updateDisplay=function updateDisplay(){var tracks=this.player_.textTracks();var allowMultipleShowingTracks=this.options_.allowMultipleShowingTracks;this.clearDisplay();if(allowMultipleShowingTracks){var showingTracks=[];for(var _i=0;_i<tracks.length;++_i){var track=tracks[_i];if(track.mode!=='showing'){continue;}
showingTracks.push(track);}
this.updateForTrack(showingTracks);return;}
var descriptionsTrack=null;var captionsSubtitlesTrack=null;var i=tracks.length;while(i--){var _track=tracks[i];if(_track.mode==='showing'){if(_track.kind==='descriptions'){descriptionsTrack=_track;}else{captionsSubtitlesTrack=_track;}}}
if(captionsSubtitlesTrack){if(this.getAttribute('aria-live')!=='off'){this.setAttribute('aria-live','off');}
this.updateForTrack(captionsSubtitlesTrack);}else if(descriptionsTrack){if(this.getAttribute('aria-live')!=='assertive'){this.setAttribute('aria-live','assertive');}
this.updateForTrack(descriptionsTrack);}};_proto.updateDisplayState=function updateDisplayState(track){var overrides=this.player_.textTrackSettings.getValues();var cues=track.activeCues;var i=cues.length;while(i--){var cue=cues[i];if(!cue){continue;}
var cueDiv=cue.displayState;if(overrides.color){cueDiv.firstChild.style.color=overrides.color;}
if(overrides.textOpacity){tryUpdateStyle(cueDiv.firstChild,'color',constructColor(overrides.color||'#fff',overrides.textOpacity));}
if(overrides.backgroundColor){cueDiv.firstChild.style.backgroundColor=overrides.backgroundColor;}
if(overrides.backgroundOpacity){tryUpdateStyle(cueDiv.firstChild,'backgroundColor',constructColor(overrides.backgroundColor||'#000',overrides.backgroundOpacity));}
if(overrides.windowColor){if(overrides.windowOpacity){tryUpdateStyle(cueDiv,'backgroundColor',constructColor(overrides.windowColor,overrides.windowOpacity));}else{cueDiv.style.backgroundColor=overrides.windowColor;}}
if(overrides.edgeStyle){if(overrides.edgeStyle==='dropshadow'){cueDiv.firstChild.style.textShadow="2px 2px 3px "+darkGray+", 2px 2px 4px "+darkGray+", 2px 2px 5px "+darkGray;}else if(overrides.edgeStyle==='raised'){cueDiv.firstChild.style.textShadow="1px 1px "+darkGray+", 2px 2px "+darkGray+", 3px 3px "+darkGray;}else if(overrides.edgeStyle==='depressed'){cueDiv.firstChild.style.textShadow="1px 1px "+lightGray+", 0 1px "+lightGray+", -1px -1px "+darkGray+", 0 -1px "+darkGray;}else if(overrides.edgeStyle==='uniform'){cueDiv.firstChild.style.textShadow="0 0 4px "+darkGray+", 0 0 4px "+darkGray+", 0 0 4px "+darkGray+", 0 0 4px "+darkGray;}}
if(overrides.fontPercent&&overrides.fontPercent!==1){var fontSize=window_1.parseFloat(cueDiv.style.fontSize);cueDiv.style.fontSize=fontSize*overrides.fontPercent+'px';cueDiv.style.height='auto';cueDiv.style.top='auto';}
if(overrides.fontFamily&&overrides.fontFamily!=='default'){if(overrides.fontFamily==='small-caps'){cueDiv.firstChild.style.fontVariant='small-caps';}else{cueDiv.firstChild.style.fontFamily=fontMap[overrides.fontFamily];}}}};_proto.updateForTrack=function updateForTrack(tracks){if(!Array.isArray(tracks)){tracks=[tracks];}
if(typeof window_1.WebVTT!=='function'||tracks.every(function(track){return!track.activeCues;})){return;}
var cues=[];for(var i=0;i<tracks.length;++i){var track=tracks[i];for(var j=0;j<track.activeCues.length;++j){cues.push(track.activeCues[j]);}}
window_1.WebVTT.processCues(window_1,cues,this.el_);for(var _i2=0;_i2<tracks.length;++_i2){var _track2=tracks[_i2];for(var _j=0;_j<_track2.activeCues.length;++_j){var cueEl=_track2.activeCues[_j].displayState;addClass(cueEl,'vjs-text-track-cue');addClass(cueEl,'vjs-text-track-cue-'+(_track2.language?_track2.language:_i2));}
if(this.player_.textTrackSettings){this.updateDisplayState(_track2);}}};return TextTrackDisplay;}(Component);Component.registerComponent('TextTrackDisplay',TextTrackDisplay);var LoadingSpinner=function(_Component){inheritsLoose(LoadingSpinner,_Component);function LoadingSpinner(){return _Component.apply(this,arguments)||this;}
var _proto=LoadingSpinner.prototype;_proto.createEl=function createEl$1(){var isAudio=this.player_.isAudio();var playerType=this.localize(isAudio?'Audio Player':'Video Player');var controlText=createEl('span',{className:'vjs-control-text',innerHTML:this.localize('{1} is loading.',[playerType])});var el=_Component.prototype.createEl.call(this,'div',{className:'vjs-loading-spinner',dir:'ltr'});el.appendChild(controlText);return el;};return LoadingSpinner;}(Component);Component.registerComponent('LoadingSpinner',LoadingSpinner);var Button=function(_ClickableComponent){inheritsLoose(Button,_ClickableComponent);function Button(){return _ClickableComponent.apply(this,arguments)||this;}
var _proto=Button.prototype;_proto.createEl=function createEl(tag,props,attributes){if(props===void 0){props={};}
if(attributes===void 0){attributes={};}
tag='button';props=assign({innerHTML:'<span aria-hidden="true" class="vjs-icon-placeholder"></span>',className:this.buildCSSClass()},props);attributes=assign({type:'button'},attributes);var el=Component.prototype.createEl.call(this,tag,props,attributes);this.createControlTextEl(el);return el;};_proto.addChild=function addChild(child,options){if(options===void 0){options={};}
var className=this.constructor.name;log.warn("Adding an actionable (user controllable) child to a Button ("+className+") is not supported; use a ClickableComponent instead.");return Component.prototype.addChild.call(this,child,options);};_proto.enable=function enable(){_ClickableComponent.prototype.enable.call(this);this.el_.removeAttribute('disabled');};_proto.disable=function disable(){_ClickableComponent.prototype.disable.call(this);this.el_.setAttribute('disabled','disabled');};_proto.handleKeyDown=function handleKeyDown(event){if(keycode.isEventKey(event,'Space')||keycode.isEventKey(event,'Enter')){event.stopPropagation();return;}
_ClickableComponent.prototype.handleKeyDown.call(this,event);};return Button;}(ClickableComponent);Component.registerComponent('Button',Button);var BigPlayButton=function(_Button){inheritsLoose(BigPlayButton,_Button);function BigPlayButton(player,options){var _this;_this=_Button.call(this,player,options)||this;_this.mouseused_=false;_this.on('mousedown',_this.handleMouseDown);return _this;}
var _proto=BigPlayButton.prototype;_proto.buildCSSClass=function buildCSSClass(){return'vjs-big-play-button';};_proto.handleClick=function handleClick(event){var playPromise=this.player_.play();if(this.mouseused_&&event.clientX&&event.clientY){var sourceIsEncrypted=this.player_.usingPlugin('eme')&&this.player_.eme.sessions&&this.player_.eme.sessions.length>0;silencePromise(playPromise);if(this.player_.tech(true)&&!((IE_VERSION||IS_EDGE)&&sourceIsEncrypted)){this.player_.tech(true).focus();}
return;}
var cb=this.player_.getChild('controlBar');var playToggle=cb&&cb.getChild('playToggle');if(!playToggle){this.player_.tech(true).focus();return;}
var playFocus=function playFocus(){return playToggle.focus();};if(isPromise(playPromise)){playPromise.then(playFocus,function(){});}else{this.setTimeout(playFocus,1);}};_proto.handleKeyDown=function handleKeyDown(event){this.mouseused_=false;_Button.prototype.handleKeyDown.call(this,event);};_proto.handleMouseDown=function handleMouseDown(event){this.mouseused_=true;};return BigPlayButton;}(Button);BigPlayButton.prototype.controlText_='Play Video';Component.registerComponent('BigPlayButton',BigPlayButton);var CloseButton=function(_Button){inheritsLoose(CloseButton,_Button);function CloseButton(player,options){var _this;_this=_Button.call(this,player,options)||this;_this.controlText(options&&options.controlText||_this.localize('Close'));return _this;}
var _proto=CloseButton.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-close-button "+_Button.prototype.buildCSSClass.call(this);};_proto.handleClick=function handleClick(event){this.trigger({type:'close',bubbles:false});};_proto.handleKeyDown=function handleKeyDown(event){if(keycode.isEventKey(event,'Esc')){event.preventDefault();event.stopPropagation();this.trigger('click');}else{_Button.prototype.handleKeyDown.call(this,event);}};return CloseButton;}(Button);Component.registerComponent('CloseButton',CloseButton);var PlayToggle=function(_Button){inheritsLoose(PlayToggle,_Button);function PlayToggle(player,options){var _this;if(options===void 0){options={};}
_this=_Button.call(this,player,options)||this;options.replay=options.replay===undefined||options.replay;_this.on(player,'play',_this.handlePlay);_this.on(player,'pause',_this.handlePause);if(options.replay){_this.on(player,'ended',_this.handleEnded);}
return _this;}
var _proto=PlayToggle.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-play-control "+_Button.prototype.buildCSSClass.call(this);};_proto.handleClick=function handleClick(event){if(this.player_.paused()){this.player_.play();}else{this.player_.pause();}};_proto.handleSeeked=function handleSeeked(event){this.removeClass('vjs-ended');if(this.player_.paused()){this.handlePause(event);}else{this.handlePlay(event);}};_proto.handlePlay=function handlePlay(event){this.removeClass('vjs-ended');this.removeClass('vjs-paused');this.addClass('vjs-playing');this.controlText('Pause');};_proto.handlePause=function handlePause(event){this.removeClass('vjs-playing');this.addClass('vjs-paused');this.controlText('Play');};_proto.handleEnded=function handleEnded(event){this.removeClass('vjs-playing');this.addClass('vjs-ended');this.controlText('Replay');this.one(this.player_,'seeked',this.handleSeeked);};return PlayToggle;}(Button);PlayToggle.prototype.controlText_='Play';Component.registerComponent('PlayToggle',PlayToggle);var defaultImplementation=function defaultImplementation(seconds,guide){seconds=seconds<0?0:seconds;var s=Math.floor(seconds%60);var m=Math.floor(seconds/60%60);var h=Math.floor(seconds/3600);var gm=Math.floor(guide/60%60);var gh=Math.floor(guide/3600);if(isNaN(seconds)||seconds===Infinity){h=m=s='-';}
h=h>0||gh>0?h+':':'';m=((h||gm>=10)&&m<10?'0'+m:m)+':';s=s<10?'0'+s:s;return h+m+s;};var implementation=defaultImplementation;function setFormatTime(customImplementation){implementation=customImplementation;}
function resetFormatTime(){implementation=defaultImplementation;}
function formatTime(seconds,guide){if(guide===void 0){guide=seconds;}
return implementation(seconds,guide);}
var TimeDisplay=function(_Component){inheritsLoose(TimeDisplay,_Component);function TimeDisplay(player,options){var _this;_this=_Component.call(this,player,options)||this;_this.on(player,['timeupdate','ended'],_this.updateContent);_this.updateTextNode_();return _this;}
var _proto=TimeDisplay.prototype;_proto.createEl=function createEl$1(){var className=this.buildCSSClass();var el=_Component.prototype.createEl.call(this,'div',{className:className+" vjs-time-control vjs-control",innerHTML:"<span class=\"vjs-control-text\" role=\"presentation\">"+this.localize(this.labelText_)+"\xA0</span>"});this.contentEl_=createEl('span',{className:className+"-display"},{'aria-live':'off','role':'presentation'});el.appendChild(this.contentEl_);return el;};_proto.dispose=function dispose(){this.contentEl_=null;this.textNode_=null;_Component.prototype.dispose.call(this);};_proto.updateTextNode_=function updateTextNode_(time){var _this2=this;if(time===void 0){time=0;}
time=formatTime(time);if(this.formattedTime_===time){return;}
this.formattedTime_=time;this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_',function(){if(!_this2.contentEl_){return;}
var oldNode=_this2.textNode_;if(oldNode&&_this2.contentEl_.firstChild!==oldNode){oldNode=null;log.warn('TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.');}
_this2.textNode_=document_1.createTextNode(_this2.formattedTime_);if(!_this2.textNode_){return;}
if(oldNode){_this2.contentEl_.replaceChild(_this2.textNode_,oldNode);}else{_this2.contentEl_.appendChild(_this2.textNode_);}});};_proto.updateContent=function updateContent(event){};return TimeDisplay;}(Component);TimeDisplay.prototype.labelText_='Time';TimeDisplay.prototype.controlText_='Time';Component.registerComponent('TimeDisplay',TimeDisplay);var CurrentTimeDisplay=function(_TimeDisplay){inheritsLoose(CurrentTimeDisplay,_TimeDisplay);function CurrentTimeDisplay(){return _TimeDisplay.apply(this,arguments)||this;}
var _proto=CurrentTimeDisplay.prototype;_proto.buildCSSClass=function buildCSSClass(){return'vjs-current-time';};_proto.updateContent=function updateContent(event){var time;if(this.player_.ended()){time=this.player_.duration();}else{time=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();}
this.updateTextNode_(time);};return CurrentTimeDisplay;}(TimeDisplay);CurrentTimeDisplay.prototype.labelText_='Current Time';CurrentTimeDisplay.prototype.controlText_='Current Time';Component.registerComponent('CurrentTimeDisplay',CurrentTimeDisplay);var DurationDisplay=function(_TimeDisplay){inheritsLoose(DurationDisplay,_TimeDisplay);function DurationDisplay(player,options){var _this;_this=_TimeDisplay.call(this,player,options)||this;_this.on(player,'durationchange',_this.updateContent);_this.on(player,'loadstart',_this.updateContent);_this.on(player,'loadedmetadata',_this.updateContent);return _this;}
var _proto=DurationDisplay.prototype;_proto.buildCSSClass=function buildCSSClass(){return'vjs-duration';};_proto.updateContent=function updateContent(event){var duration=this.player_.duration();this.updateTextNode_(duration);};return DurationDisplay;}(TimeDisplay);DurationDisplay.prototype.labelText_='Duration';DurationDisplay.prototype.controlText_='Duration';Component.registerComponent('DurationDisplay',DurationDisplay);var TimeDivider=function(_Component){inheritsLoose(TimeDivider,_Component);function TimeDivider(){return _Component.apply(this,arguments)||this;}
var _proto=TimeDivider.prototype;_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'div',{className:'vjs-time-control vjs-time-divider',innerHTML:'<div><span>/</span></div>'},{'aria-hidden':true});};return TimeDivider;}(Component);Component.registerComponent('TimeDivider',TimeDivider);var RemainingTimeDisplay=function(_TimeDisplay){inheritsLoose(RemainingTimeDisplay,_TimeDisplay);function RemainingTimeDisplay(player,options){var _this;_this=_TimeDisplay.call(this,player,options)||this;_this.on(player,'durationchange',_this.updateContent);return _this;}
var _proto=RemainingTimeDisplay.prototype;_proto.buildCSSClass=function buildCSSClass(){return'vjs-remaining-time';};_proto.createEl=function createEl$1(){var el=_TimeDisplay.prototype.createEl.call(this);el.insertBefore(createEl('span',{},{'aria-hidden':true},'-'),this.contentEl_);return el;};_proto.updateContent=function updateContent(event){if(typeof this.player_.duration()!=='number'){return;}
var time;if(this.player_.ended()){time=0;}else if(this.player_.remainingTimeDisplay){time=this.player_.remainingTimeDisplay();}else{time=this.player_.remainingTime();}
this.updateTextNode_(time);};return RemainingTimeDisplay;}(TimeDisplay);RemainingTimeDisplay.prototype.labelText_='Remaining Time';RemainingTimeDisplay.prototype.controlText_='Remaining Time';Component.registerComponent('RemainingTimeDisplay',RemainingTimeDisplay);var LiveDisplay=function(_Component){inheritsLoose(LiveDisplay,_Component);function LiveDisplay(player,options){var _this;_this=_Component.call(this,player,options)||this;_this.updateShowing();_this.on(_this.player(),'durationchange',_this.updateShowing);return _this;}
var _proto=LiveDisplay.prototype;_proto.createEl=function createEl$1(){var el=_Component.prototype.createEl.call(this,'div',{className:'vjs-live-control vjs-control'});this.contentEl_=createEl('div',{className:'vjs-live-display',innerHTML:"<span class=\"vjs-control-text\">"+this.localize('Stream Type')+"\xA0</span>"+this.localize('LIVE')},{'aria-live':'off'});el.appendChild(this.contentEl_);return el;};_proto.dispose=function dispose(){this.contentEl_=null;_Component.prototype.dispose.call(this);};_proto.updateShowing=function updateShowing(event){if(this.player().duration()===Infinity){this.show();}else{this.hide();}};return LiveDisplay;}(Component);Component.registerComponent('LiveDisplay',LiveDisplay);var SeekToLive=function(_Button){inheritsLoose(SeekToLive,_Button);function SeekToLive(player,options){var _this;_this=_Button.call(this,player,options)||this;_this.updateLiveEdgeStatus();if(_this.player_.liveTracker){_this.on(_this.player_.liveTracker,'liveedgechange',_this.updateLiveEdgeStatus);}
return _this;}
var _proto=SeekToLive.prototype;_proto.createEl=function createEl$1(){var el=_Button.prototype.createEl.call(this,'button',{className:'vjs-seek-to-live-control vjs-control'});this.textEl_=createEl('span',{className:'vjs-seek-to-live-text',innerHTML:this.localize('LIVE')},{'aria-hidden':'true'});el.appendChild(this.textEl_);return el;};_proto.updateLiveEdgeStatus=function updateLiveEdgeStatus(){if(!this.player_.liveTracker||this.player_.liveTracker.atLiveEdge()){this.setAttribute('aria-disabled',true);this.addClass('vjs-at-live-edge');this.controlText('Seek to live, currently playing live');}else{this.setAttribute('aria-disabled',false);this.removeClass('vjs-at-live-edge');this.controlText('Seek to live, currently behind live');}};_proto.handleClick=function handleClick(){this.player_.liveTracker.seekToLiveEdge();};_proto.dispose=function dispose(){if(this.player_.liveTracker){this.off(this.player_.liveTracker,'liveedgechange',this.updateLiveEdgeStatus);}
this.textEl_=null;_Button.prototype.dispose.call(this);};return SeekToLive;}(Button);SeekToLive.prototype.controlText_='Seek to live, currently playing live';Component.registerComponent('SeekToLive',SeekToLive);var clamp=function clamp(number,min,max){number=Number(number);return Math.min(max,Math.max(min,isNaN(number)?min:number));};var Slider=function(_Component){inheritsLoose(Slider,_Component);function Slider(player,options){var _this;_this=_Component.call(this,player,options)||this;_this.bar=_this.getChild(_this.options_.barName);_this.vertical(!!_this.options_.vertical);_this.enable();return _this;}
var _proto=Slider.prototype;_proto.enabled=function enabled(){return this.enabled_;};_proto.enable=function enable(){if(this.enabled()){return;}
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);if(this.playerEvent){this.on(this.player_,this.playerEvent,this.update);}
this.removeClass('disabled');this.setAttribute('tabindex',0);this.enabled_=true;};_proto.disable=function disable(){if(!this.enabled()){return;}
var 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');if(this.playerEvent){this.off(this.player_,this.playerEvent,this.update);}
this.enabled_=false;};_proto.createEl=function createEl(type,props,attributes){if(props===void 0){props={};}
if(attributes===void 0){attributes={};}
props.className=props.className+' vjs-slider';props=assign({tabIndex:0},props);attributes=assign({'role':'slider','aria-valuenow':0,'aria-valuemin':0,'aria-valuemax':100,'tabIndex':0},attributes);return _Component.prototype.createEl.call(this,type,props,attributes);};_proto.handleMouseDown=function handleMouseDown(event){var doc=this.bar.el_.ownerDocument;if(event.type==='mousedown'){event.preventDefault();}
if(event.type==='touchstart'&&!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);};_proto.handleMouseMove=function handleMouseMove(event){};_proto.handleMouseUp=function handleMouseUp(){var 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();};_proto.update=function update(){var _this2=this;if(!this.el_||!this.bar){return;}
var progress=this.getProgress();if(progress===this.progress_){return progress;}
this.progress_=progress;this.requestNamedAnimationFrame('Slider#update',function(){var sizeKey=_this2.vertical()?'height':'width';_this2.bar.el().style[sizeKey]=(progress*100).toFixed(2)+'%';});return progress;};_proto.getProgress=function getProgress(){return Number(clamp(this.getPercent(),0,1).toFixed(4));};_proto.calculateDistance=function calculateDistance(event){var position=getPointerPosition(this.el_,event);if(this.vertical()){return position.y;}
return position.x;};_proto.handleKeyDown=function handleKeyDown(event){if(keycode.isEventKey(event,'Left')||keycode.isEventKey(event,'Down')){event.preventDefault();event.stopPropagation();this.stepBack();}else if(keycode.isEventKey(event,'Right')||keycode.isEventKey(event,'Up')){event.preventDefault();event.stopPropagation();this.stepForward();}else{_Component.prototype.handleKeyDown.call(this,event);}};_proto.handleClick=function handleClick(event){event.stopPropagation();event.preventDefault();};_proto.vertical=function vertical(bool){if(bool===undefined){return this.vertical_||false;}
this.vertical_=!!bool;if(this.vertical_){this.addClass('vjs-slider-vertical');}else{this.addClass('vjs-slider-horizontal');}};return Slider;}(Component);Component.registerComponent('Slider',Slider);var percentify=function percentify(time,end){return clamp(time/end*100,0,100).toFixed(2)+'%';};var LoadProgressBar=function(_Component){inheritsLoose(LoadProgressBar,_Component);function LoadProgressBar(player,options){var _this;_this=_Component.call(this,player,options)||this;_this.partEls_=[];_this.on(player,'progress',_this.update);return _this;}
var _proto=LoadProgressBar.prototype;_proto.createEl=function createEl$1(){var el=_Component.prototype.createEl.call(this,'div',{className:'vjs-load-progress'});var wrapper=createEl('span',{className:'vjs-control-text'});var loadedText=createEl('span',{textContent:this.localize('Loaded')});var separator=document_1.createTextNode(': ');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_);return el;};_proto.dispose=function dispose(){this.partEls_=null;this.percentageEl_=null;_Component.prototype.dispose.call(this);};_proto.update=function update(event){var _this2=this;this.requestNamedAnimationFrame('LoadProgressBar#update',function(){var liveTracker=_this2.player_.liveTracker;var buffered=_this2.player_.buffered();var duration=liveTracker&&liveTracker.isLive()?liveTracker.seekableEnd():_this2.player_.duration();var bufferedEnd=_this2.player_.bufferedEnd();var children=_this2.partEls_;var percent=percentify(bufferedEnd,duration);if(_this2.percent_!==percent){_this2.el_.style.width=percent;textContent(_this2.percentageEl_,percent);_this2.percent_=percent;}
for(var i=0;i<buffered.length;i++){var start=buffered.start(i);var end=buffered.end(i);var part=children[i];if(!part){part=_this2.el_.appendChild(createEl());children[i]=part;}
if(part.dataset.start===start&&part.dataset.end===end){continue;}
part.dataset.start=start;part.dataset.end=end;part.style.left=percentify(start,bufferedEnd);part.style.width=percentify(end-start,bufferedEnd);}
for(var _i=children.length;_i>buffered.length;_i--){_this2.el_.removeChild(children[_i-1]);}
children.length=buffered.length;});};return LoadProgressBar;}(Component);Component.registerComponent('LoadProgressBar',LoadProgressBar);var TimeTooltip=function(_Component){inheritsLoose(TimeTooltip,_Component);function TimeTooltip(player,options){var _this;_this=_Component.call(this,player,options)||this;_this.update=throttle(bind(assertThisInitialized(_this),_this.update),UPDATE_REFRESH_INTERVAL);return _this;}
var _proto=TimeTooltip.prototype;_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'div',{className:'vjs-time-tooltip'},{'aria-hidden':'true'});};_proto.update=function update(seekBarRect,seekBarPoint,content){var tooltipRect=findPosition(this.el_);var playerRect=getBoundingClientRect(this.player_.el());var seekBarPointPx=seekBarRect.width*seekBarPoint;if(!playerRect||!tooltipRect){return;}
var spaceLeftOfPoint=seekBarRect.left-playerRect.left+seekBarPointPx;var spaceRightOfPoint=seekBarRect.width-seekBarPointPx+(playerRect.right-seekBarRect.right);var pullTooltipBy=tooltipRect.width/2;if(spaceLeftOfPoint<pullTooltipBy){pullTooltipBy+=pullTooltipBy-spaceLeftOfPoint;}else if(spaceRightOfPoint<pullTooltipBy){pullTooltipBy=spaceRightOfPoint;}
if(pullTooltipBy<0){pullTooltipBy=0;}else if(pullTooltipBy>tooltipRect.width){pullTooltipBy=tooltipRect.width;}
pullTooltipBy=Math.round(pullTooltipBy);this.el_.style.right="-"+pullTooltipBy+"px";this.write(content);};_proto.write=function write(content){textContent(this.el_,content);};_proto.updateTime=function updateTime(seekBarRect,seekBarPoint,time,cb){var _this2=this;this.requestNamedAnimationFrame('TimeTooltip#updateTime',function(){var content;var duration=_this2.player_.duration();if(_this2.player_.liveTracker&&_this2.player_.liveTracker.isLive()){var liveWindow=_this2.player_.liveTracker.liveWindow();var secondsBehind=liveWindow-seekBarPoint*liveWindow;content=(secondsBehind<1?'':'-')+formatTime(secondsBehind,liveWindow);}else{content=formatTime(time,duration);}
_this2.update(seekBarRect,seekBarPoint,content);if(cb){cb();}});};return TimeTooltip;}(Component);Component.registerComponent('TimeTooltip',TimeTooltip);var PlayProgressBar=function(_Component){inheritsLoose(PlayProgressBar,_Component);function PlayProgressBar(player,options){var _this;_this=_Component.call(this,player,options)||this;_this.update=throttle(bind(assertThisInitialized(_this),_this.update),UPDATE_REFRESH_INTERVAL);return _this;}
var _proto=PlayProgressBar.prototype;_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'div',{className:'vjs-play-progress vjs-slider-bar'},{'aria-hidden':'true'});};_proto.update=function update(seekBarRect,seekBarPoint){var timeTooltip=this.getChild('timeTooltip');if(!timeTooltip){return;}
var time=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();timeTooltip.updateTime(seekBarRect,seekBarPoint,time);};return PlayProgressBar;}(Component);PlayProgressBar.prototype.options_={children:[]};if(!IS_IOS&&!IS_ANDROID){PlayProgressBar.prototype.options_.children.push('timeTooltip');}
Component.registerComponent('PlayProgressBar',PlayProgressBar);var MouseTimeDisplay=function(_Component){inheritsLoose(MouseTimeDisplay,_Component);function MouseTimeDisplay(player,options){var _this;_this=_Component.call(this,player,options)||this;_this.update=throttle(bind(assertThisInitialized(_this),_this.update),UPDATE_REFRESH_INTERVAL);return _this;}
var _proto=MouseTimeDisplay.prototype;_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'div',{className:'vjs-mouse-display'});};_proto.update=function update(seekBarRect,seekBarPoint){var _this2=this;var time=seekBarPoint*this.player_.duration();this.getChild('timeTooltip').updateTime(seekBarRect,seekBarPoint,time,function(){_this2.el_.style.left=seekBarRect.width*seekBarPoint+"px";});};return MouseTimeDisplay;}(Component);MouseTimeDisplay.prototype.options_={children:['timeTooltip']};Component.registerComponent('MouseTimeDisplay',MouseTimeDisplay);var STEP_SECONDS=5;var PAGE_KEY_MULTIPLIER=12;var SeekBar=function(_Slider){inheritsLoose(SeekBar,_Slider);function SeekBar(player,options){var _this;_this=_Slider.call(this,player,options)||this;_this.setEventHandlers_();return _this;}
var _proto=SeekBar.prototype;_proto.setEventHandlers_=function setEventHandlers_(){this.update_=bind(this,this.update);this.update=throttle(this.update_,UPDATE_REFRESH_INTERVAL);this.on(this.player_,['ended','durationchange','timeupdate'],this.update);if(this.player_.liveTracker){this.on(this.player_.liveTracker,'liveedgechange',this.update);}
this.updateInterval=null;this.on(this.player_,['playing'],this.enableInterval_);this.on(this.player_,['ended','pause','waiting'],this.disableInterval_);if('hidden'in document_1&&'visibilityState'in document_1){this.on(document_1,'visibilitychange',this.toggleVisibility_);}};_proto.toggleVisibility_=function toggleVisibility_(e){if(document_1.hidden){this.disableInterval_(e);}else{this.enableInterval_();this.update();}};_proto.enableInterval_=function enableInterval_(){if(this.updateInterval){return;}
this.updateInterval=this.setInterval(this.update,UPDATE_REFRESH_INTERVAL);};_proto.disableInterval_=function disableInterval_(e){if(this.player_.liveTracker&&this.player_.liveTracker.isLive()&&e&&e.type!=='ended'){return;}
if(!this.updateInterval){return;}
this.clearInterval(this.updateInterval);this.updateInterval=null;};_proto.createEl=function createEl(){return _Slider.prototype.createEl.call(this,'div',{className:'vjs-progress-holder'},{'aria-label':this.localize('Progress Bar')});};_proto.update=function update(event){var _this2=this;var percent=_Slider.prototype.update.call(this);this.requestNamedAnimationFrame('SeekBar#update',function(){var currentTime=_this2.player_.ended()?_this2.player_.duration():_this2.getCurrentTime_();var liveTracker=_this2.player_.liveTracker;var duration=_this2.player_.duration();if(liveTracker&&liveTracker.isLive()){duration=_this2.player_.liveTracker.liveCurrentTime();}
if(_this2.percent_!==percent){_this2.el_.setAttribute('aria-valuenow',(percent*100).toFixed(2));_this2.percent_=percent;}
if(_this2.currentTime_!==currentTime||_this2.duration_!==duration){_this2.el_.setAttribute('aria-valuetext',_this2.localize('progress bar timing: currentTime={1} duration={2}',[formatTime(currentTime,duration),formatTime(duration,duration)],'{1} of {2}'));_this2.currentTime_=currentTime;_this2.duration_=duration;}
if(_this2.bar){_this2.bar.update(getBoundingClientRect(_this2.el()),_this2.getProgress());}});return percent;};_proto.getCurrentTime_=function getCurrentTime_(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();};_proto.getPercent=function getPercent(){var currentTime=this.getCurrentTime_();var percent;var liveTracker=this.player_.liveTracker;if(liveTracker&&liveTracker.isLive()){percent=(currentTime-liveTracker.seekableStart())/liveTracker.liveWindow();if(liveTracker.atLiveEdge()){percent=1;}}else{percent=currentTime/this.player_.duration();}
return percent;};_proto.handleMouseDown=function handleMouseDown(event){if(!isSingleLeftClick(event)){return;}
event.stopPropagation();this.player_.scrubbing(true);this.videoWasPlaying=!this.player_.paused();this.player_.pause();_Slider.prototype.handleMouseDown.call(this,event);};_proto.handleMouseMove=function handleMouseMove(event){if(!isSingleLeftClick(event)){return;}
var newTime;var distance=this.calculateDistance(event);var liveTracker=this.player_.liveTracker;if(!liveTracker||!liveTracker.isLive()){newTime=distance*this.player_.duration();if(newTime===this.player_.duration()){newTime=newTime-0.1;}}else{if(distance>=0.99){liveTracker.seekToLiveEdge();return;}
var seekableStart=liveTracker.seekableStart();var seekableEnd=liveTracker.liveCurrentTime();newTime=seekableStart+distance*liveTracker.liveWindow();if(newTime>=seekableEnd){newTime=seekableEnd;}
if(newTime<=seekableStart){newTime=seekableStart+0.1;}
if(newTime===Infinity){return;}}
this.player_.currentTime(newTime);};_proto.enable=function enable(){_Slider.prototype.enable.call(this);var mouseTimeDisplay=this.getChild('mouseTimeDisplay');if(!mouseTimeDisplay){return;}
mouseTimeDisplay.show();};_proto.disable=function disable(){_Slider.prototype.disable.call(this);var mouseTimeDisplay=this.getChild('mouseTimeDisplay');if(!mouseTimeDisplay){return;}
mouseTimeDisplay.hide();};_proto.handleMouseUp=function handleMouseUp(event){_Slider.prototype.handleMouseUp.call(this,event);if(event){event.stopPropagation();}
this.player_.scrubbing(false);this.player_.trigger({type:'timeupdate',target:this,manuallyTriggered:true});if(this.videoWasPlaying){silencePromise(this.player_.play());}else{this.update_();}};_proto.stepForward=function stepForward(){this.player_.currentTime(this.player_.currentTime()+STEP_SECONDS);};_proto.stepBack=function stepBack(){this.player_.currentTime(this.player_.currentTime()-STEP_SECONDS);};_proto.handleAction=function handleAction(event){if(this.player_.paused()){this.player_.play();}else{this.player_.pause();}};_proto.handleKeyDown=function handleKeyDown(event){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.player_.currentTime(0);}else if(keycode.isEventKey(event,'End')){event.preventDefault();event.stopPropagation();this.player_.currentTime(this.player_.duration());}else if(/^[0-9]$/.test(keycode(event))){event.preventDefault();event.stopPropagation();var gotoFraction=(keycode.codes[keycode(event)]-keycode.codes['0'])*10.0/100.0;this.player_.currentTime(this.player_.duration()*gotoFraction);}else if(keycode.isEventKey(event,'PgDn')){event.preventDefault();event.stopPropagation();this.player_.currentTime(this.player_.currentTime()-STEP_SECONDS*PAGE_KEY_MULTIPLIER);}else if(keycode.isEventKey(event,'PgUp')){event.preventDefault();event.stopPropagation();this.player_.currentTime(this.player_.currentTime()+STEP_SECONDS*PAGE_KEY_MULTIPLIER);}else{_Slider.prototype.handleKeyDown.call(this,event);}};_proto.dispose=function dispose(){this.disableInterval_();this.off(this.player_,['ended','durationchange','timeupdate'],this.update);if(this.player_.liveTracker){this.on(this.player_.liveTracker,'liveedgechange',this.update);}
this.off(this.player_,['playing'],this.enableInterval_);this.off(this.player_,['ended','pause','waiting'],this.disableInterval_);if('hidden'in document_1&&'visibilityState'in document_1){this.off(document_1,'visibilitychange',this.toggleVisibility_);}
_Slider.prototype.dispose.call(this);};return SeekBar;}(Slider);SeekBar.prototype.options_={children:['loadProgressBar','playProgressBar'],barName:'playProgressBar'};if(!IS_IOS&&!IS_ANDROID){SeekBar.prototype.options_.children.splice(1,0,'mouseTimeDisplay');}
Component.registerComponent('SeekBar',SeekBar);var ProgressControl=function(_Component){inheritsLoose(ProgressControl,_Component);function ProgressControl(player,options){var _this;_this=_Component.call(this,player,options)||this;_this.handleMouseMove=throttle(bind(assertThisInitialized(_this),_this.handleMouseMove),UPDATE_REFRESH_INTERVAL);_this.throttledHandleMouseSeek=throttle(bind(assertThisInitialized(_this),_this.handleMouseSeek),UPDATE_REFRESH_INTERVAL);_this.enable();return _this;}
var _proto=ProgressControl.prototype;_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'div',{className:'vjs-progress-control vjs-control'});};_proto.handleMouseMove=function handleMouseMove(event){var seekBar=this.getChild('seekBar');if(!seekBar){return;}
var playProgressBar=seekBar.getChild('playProgressBar');var mouseTimeDisplay=seekBar.getChild('mouseTimeDisplay');if(!playProgressBar&&!mouseTimeDisplay){return;}
var seekBarEl=seekBar.el();var seekBarRect=findPosition(seekBarEl);var seekBarPoint=getPointerPosition(seekBarEl,event).x;seekBarPoint=clamp(seekBarPoint,0,1);if(mouseTimeDisplay){mouseTimeDisplay.update(seekBarRect,seekBarPoint);}
if(playProgressBar){playProgressBar.update(seekBarRect,seekBar.getProgress());}};_proto.handleMouseSeek=function handleMouseSeek(event){var seekBar=this.getChild('seekBar');if(seekBar){seekBar.handleMouseMove(event);}};_proto.enabled=function enabled(){return this.enabled_;};_proto.disable=function disable(){this.children().forEach(function(child){return child.disable&&child.disable();});if(!this.enabled()){return;}
this.off(['mousedown','touchstart'],this.handleMouseDown);this.off(this.el_,'mousemove',this.handleMouseMove);this.handleMouseUp();this.addClass('disabled');this.enabled_=false;};_proto.enable=function enable(){this.children().forEach(function(child){return child.enable&&child.enable();});if(this.enabled()){return;}
this.on(['mousedown','touchstart'],this.handleMouseDown);this.on(this.el_,'mousemove',this.handleMouseMove);this.removeClass('disabled');this.enabled_=true;};_proto.handleMouseDown=function handleMouseDown(event){var doc=this.el_.ownerDocument;var seekBar=this.getChild('seekBar');if(seekBar){seekBar.handleMouseDown(event);}
this.on(doc,'mousemove',this.throttledHandleMouseSeek);this.on(doc,'touchmove',this.throttledHandleMouseSeek);this.on(doc,'mouseup',this.handleMouseUp);this.on(doc,'touchend',this.handleMouseUp);};_proto.handleMouseUp=function handleMouseUp(event){var doc=this.el_.ownerDocument;var seekBar=this.getChild('seekBar');if(seekBar){seekBar.handleMouseUp(event);}
this.off(doc,'mousemove',this.throttledHandleMouseSeek);this.off(doc,'touchmove',this.throttledHandleMouseSeek);this.off(doc,'mouseup',this.handleMouseUp);this.off(doc,'touchend',this.handleMouseUp);};return ProgressControl;}(Component);ProgressControl.prototype.options_={children:['seekBar']};Component.registerComponent('ProgressControl',ProgressControl);var PictureInPictureToggle=function(_Button){inheritsLoose(PictureInPictureToggle,_Button);function PictureInPictureToggle(player,options){var _this;_this=_Button.call(this,player,options)||this;_this.on(player,['enterpictureinpicture','leavepictureinpicture'],_this.handlePictureInPictureChange);_this.on(player,['disablepictureinpicturechanged','loadedmetadata'],_this.handlePictureInPictureEnabledChange);_this.disable();return _this;}
var _proto=PictureInPictureToggle.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-picture-in-picture-control "+_Button.prototype.buildCSSClass.call(this);};_proto.handlePictureInPictureEnabledChange=function handlePictureInPictureEnabledChange(){if(document_1.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===false){this.enable();}else{this.disable();}};_proto.handlePictureInPictureChange=function handlePictureInPictureChange(event){if(this.player_.isInPictureInPicture()){this.controlText('Exit Picture-in-Picture');}else{this.controlText('Picture-in-Picture');}
this.handlePictureInPictureEnabledChange();};_proto.handleClick=function handleClick(event){if(!this.player_.isInPictureInPicture()){this.player_.requestPictureInPicture();}else{this.player_.exitPictureInPicture();}};return PictureInPictureToggle;}(Button);PictureInPictureToggle.prototype.controlText_='Picture-in-Picture';Component.registerComponent('PictureInPictureToggle',PictureInPictureToggle);var FullscreenToggle=function(_Button){inheritsLoose(FullscreenToggle,_Button);function FullscreenToggle(player,options){var _this;_this=_Button.call(this,player,options)||this;_this.on(player,'fullscreenchange',_this.handleFullscreenChange);if(document_1[player.fsApi_.fullscreenEnabled]===false){_this.disable();}
return _this;}
var _proto=FullscreenToggle.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-fullscreen-control "+_Button.prototype.buildCSSClass.call(this);};_proto.handleFullscreenChange=function handleFullscreenChange(event){if(this.player_.isFullscreen()){this.controlText('Non-Fullscreen');}else{this.controlText('Fullscreen');}};_proto.handleClick=function handleClick(event){if(!this.player_.isFullscreen()){this.player_.requestFullscreen();}else{this.player_.exitFullscreen();}};return FullscreenToggle;}(Button);FullscreenToggle.prototype.controlText_='Fullscreen';Component.registerComponent('FullscreenToggle',FullscreenToggle);var checkVolumeSupport=function checkVolumeSupport(self,player){if(player.tech_&&!player.tech_.featuresVolumeControl){self.addClass('vjs-hidden');}
self.on(player,'loadstart',function(){if(!player.tech_.featuresVolumeControl){self.addClass('vjs-hidden');}else{self.removeClass('vjs-hidden');}});};var VolumeLevel=function(_Component){inheritsLoose(VolumeLevel,_Component);function VolumeLevel(){return _Component.apply(this,arguments)||this;}
var _proto=VolumeLevel.prototype;_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'div',{className:'vjs-volume-level',innerHTML:'<span class="vjs-control-text"></span>'});};return VolumeLevel;}(Component);Component.registerComponent('VolumeLevel',VolumeLevel);var VolumeBar=function(_Slider){inheritsLoose(VolumeBar,_Slider);function VolumeBar(player,options){var _this;_this=_Slider.call(this,player,options)||this;_this.on('slideractive',_this.updateLastVolume_);_this.on(player,'volumechange',_this.updateARIAAttributes);player.ready(function(){return _this.updateARIAAttributes();});return _this;}
var _proto=VolumeBar.prototype;_proto.createEl=function createEl(){return _Slider.prototype.createEl.call(this,'div',{className:'vjs-volume-bar vjs-slider-bar'},{'aria-label':this.localize('Volume Level'),'aria-live':'polite'});};_proto.handleMouseDown=function handleMouseDown(event){if(!isSingleLeftClick(event)){return;}
_Slider.prototype.handleMouseDown.call(this,event);};_proto.handleMouseMove=function handleMouseMove(event){if(!isSingleLeftClick(event)){return;}
this.checkMuted();this.player_.volume(this.calculateDistance(event));};_proto.checkMuted=function checkMuted(){if(this.player_.muted()){this.player_.muted(false);}};_proto.getPercent=function getPercent(){if(this.player_.muted()){return 0;}
return this.player_.volume();};_proto.stepForward=function stepForward(){this.checkMuted();this.player_.volume(this.player_.volume()+0.1);};_proto.stepBack=function stepBack(){this.checkMuted();this.player_.volume(this.player_.volume()-0.1);};_proto.updateARIAAttributes=function updateARIAAttributes(event){var ariaValue=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute('aria-valuenow',ariaValue);this.el_.setAttribute('aria-valuetext',ariaValue+'%');};_proto.volumeAsPercentage_=function volumeAsPercentage_(){return Math.round(this.player_.volume()*100);};_proto.updateLastVolume_=function updateLastVolume_(){var _this2=this;var volumeBeforeDrag=this.player_.volume();this.one('sliderinactive',function(){if(_this2.player_.volume()===0){_this2.player_.lastVolume_(volumeBeforeDrag);}});};return VolumeBar;}(Slider);VolumeBar.prototype.options_={children:['volumeLevel'],barName:'volumeLevel'};VolumeBar.prototype.playerEvent='volumechange';Component.registerComponent('VolumeBar',VolumeBar);var VolumeControl=function(_Component){inheritsLoose(VolumeControl,_Component);function VolumeControl(player,options){var _this;if(options===void 0){options={};}
options.vertical=options.vertical||false;if(typeof options.volumeBar==='undefined'||isPlain(options.volumeBar)){options.volumeBar=options.volumeBar||{};options.volumeBar.vertical=options.vertical;}
_this=_Component.call(this,player,options)||this;checkVolumeSupport(assertThisInitialized(_this),player);_this.throttledHandleMouseMove=throttle(bind(assertThisInitialized(_this),_this.handleMouseMove),UPDATE_REFRESH_INTERVAL);_this.on('mousedown',_this.handleMouseDown);_this.on('touchstart',_this.handleMouseDown);_this.on(_this.volumeBar,['focus','slideractive'],function(){_this.volumeBar.addClass('vjs-slider-active');_this.addClass('vjs-slider-active');_this.trigger('slideractive');});_this.on(_this.volumeBar,['blur','sliderinactive'],function(){_this.volumeBar.removeClass('vjs-slider-active');_this.removeClass('vjs-slider-active');_this.trigger('sliderinactive');});return _this;}
var _proto=VolumeControl.prototype;_proto.createEl=function createEl(){var orientationClass='vjs-volume-horizontal';if(this.options_.vertical){orientationClass='vjs-volume-vertical';}
return _Component.prototype.createEl.call(this,'div',{className:"vjs-volume-control vjs-control "+orientationClass});};_proto.handleMouseDown=function handleMouseDown(event){var doc=this.el_.ownerDocument;this.on(doc,'mousemove',this.throttledHandleMouseMove);this.on(doc,'touchmove',this.throttledHandleMouseMove);this.on(doc,'mouseup',this.handleMouseUp);this.on(doc,'touchend',this.handleMouseUp);};_proto.handleMouseUp=function handleMouseUp(event){var doc=this.el_.ownerDocument;this.off(doc,'mousemove',this.throttledHandleMouseMove);this.off(doc,'touchmove',this.throttledHandleMouseMove);this.off(doc,'mouseup',this.handleMouseUp);this.off(doc,'touchend',this.handleMouseUp);};_proto.handleMouseMove=function handleMouseMove(event){this.volumeBar.handleMouseMove(event);};return VolumeControl;}(Component);VolumeControl.prototype.options_={children:['volumeBar']};Component.registerComponent('VolumeControl',VolumeControl);var checkMuteSupport=function checkMuteSupport(self,player){if(player.tech_&&!player.tech_.featuresMuteControl){self.addClass('vjs-hidden');}
self.on(player,'loadstart',function(){if(!player.tech_.featuresMuteControl){self.addClass('vjs-hidden');}else{self.removeClass('vjs-hidden');}});};var MuteToggle=function(_Button){inheritsLoose(MuteToggle,_Button);function MuteToggle(player,options){var _this;_this=_Button.call(this,player,options)||this;checkMuteSupport(assertThisInitialized(_this),player);_this.on(player,['loadstart','volumechange'],_this.update);return _this;}
var _proto=MuteToggle.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-mute-control "+_Button.prototype.buildCSSClass.call(this);};_proto.handleClick=function handleClick(event){var vol=this.player_.volume();var lastVolume=this.player_.lastVolume_();if(vol===0){var volumeToSet=lastVolume<0.1?0.1:lastVolume;this.player_.volume(volumeToSet);this.player_.muted(false);}else{this.player_.muted(this.player_.muted()?false:true);}};_proto.update=function update(event){this.updateIcon_();this.updateControlText_();};_proto.updateIcon_=function updateIcon_(){var vol=this.player_.volume();var level=3;if(IS_IOS&&this.player_.tech_&&this.player_.tech_.el_){this.player_.muted(this.player_.tech_.el_.muted);}
if(vol===0||this.player_.muted()){level=0;}else if(vol<0.33){level=1;}else if(vol<0.67){level=2;}
for(var i=0;i<4;i++){removeClass(this.el_,"vjs-vol-"+i);}
addClass(this.el_,"vjs-vol-"+level);};_proto.updateControlText_=function updateControlText_(){var soundOff=this.player_.muted()||this.player_.volume()===0;var text=soundOff?'Unmute':'Mute';if(this.controlText()!==text){this.controlText(text);}};return MuteToggle;}(Button);MuteToggle.prototype.controlText_='Mute';Component.registerComponent('MuteToggle',MuteToggle);var VolumePanel=function(_Component){inheritsLoose(VolumePanel,_Component);function VolumePanel(player,options){var _this;if(options===void 0){options={};}
if(typeof options.inline!=='undefined'){options.inline=options.inline;}else{options.inline=true;}
if(typeof options.volumeControl==='undefined'||isPlain(options.volumeControl)){options.volumeControl=options.volumeControl||{};options.volumeControl.vertical=!options.inline;}
_this=_Component.call(this,player,options)||this;_this.on(player,['loadstart'],_this.volumePanelState_);_this.on(_this.muteToggle,'keyup',_this.handleKeyPress);_this.on(_this.volumeControl,'keyup',_this.handleVolumeControlKeyUp);_this.on('keydown',_this.handleKeyPress);_this.on('mouseover',_this.handleMouseOver);_this.on('mouseout',_this.handleMouseOut);_this.on(_this.volumeControl,['slideractive'],_this.sliderActive_);_this.on(_this.volumeControl,['sliderinactive'],_this.sliderInactive_);return _this;}
var _proto=VolumePanel.prototype;_proto.sliderActive_=function sliderActive_(){this.addClass('vjs-slider-active');};_proto.sliderInactive_=function sliderInactive_(){this.removeClass('vjs-slider-active');};_proto.volumePanelState_=function volumePanelState_(){if(this.volumeControl.hasClass('vjs-hidden')&&this.muteToggle.hasClass('vjs-hidden')){this.addClass('vjs-hidden');}
if(this.volumeControl.hasClass('vjs-hidden')&&!this.muteToggle.hasClass('vjs-hidden')){this.addClass('vjs-mute-toggle-only');}};_proto.createEl=function createEl(){var orientationClass='vjs-volume-panel-horizontal';if(!this.options_.inline){orientationClass='vjs-volume-panel-vertical';}
return _Component.prototype.createEl.call(this,'div',{className:"vjs-volume-panel vjs-control "+orientationClass});};_proto.dispose=function dispose(){this.handleMouseOut();_Component.prototype.dispose.call(this);};_proto.handleVolumeControlKeyUp=function handleVolumeControlKeyUp(event){if(keycode.isEventKey(event,'Esc')){this.muteToggle.focus();}};_proto.handleMouseOver=function handleMouseOver(event){this.addClass('vjs-hover');on(document_1,'keyup',bind(this,this.handleKeyPress));};_proto.handleMouseOut=function handleMouseOut(event){this.removeClass('vjs-hover');off(document_1,'keyup',bind(this,this.handleKeyPress));};_proto.handleKeyPress=function handleKeyPress(event){if(keycode.isEventKey(event,'Esc')){this.handleMouseOut();}};return VolumePanel;}(Component);VolumePanel.prototype.options_={children:['muteToggle','volumeControl']};Component.registerComponent('VolumePanel',VolumePanel);var Menu=function(_Component){inheritsLoose(Menu,_Component);function Menu(player,options){var _this;_this=_Component.call(this,player,options)||this;if(options){_this.menuButton_=options.menuButton;}
_this.focusedChild_=-1;_this.on('keydown',_this.handleKeyDown);_this.boundHandleBlur_=bind(assertThisInitialized(_this),_this.handleBlur);_this.boundHandleTapClick_=bind(assertThisInitialized(_this),_this.handleTapClick);return _this;}
var _proto=Menu.prototype;_proto.addEventListenerForItem=function addEventListenerForItem(component){if(!(component instanceof Component)){return;}
this.on(component,'blur',this.boundHandleBlur_);this.on(component,['tap','click'],this.boundHandleTapClick_);};_proto.removeEventListenerForItem=function removeEventListenerForItem(component){if(!(component instanceof Component)){return;}
this.off(component,'blur',this.boundHandleBlur_);this.off(component,['tap','click'],this.boundHandleTapClick_);};_proto.removeChild=function removeChild(component){if(typeof component==='string'){component=this.getChild(component);}
this.removeEventListenerForItem(component);_Component.prototype.removeChild.call(this,component);};_proto.addItem=function addItem(component){var childComponent=this.addChild(component);if(childComponent){this.addEventListenerForItem(childComponent);}};_proto.createEl=function createEl$1(){var contentElType=this.options_.contentElType||'ul';this.contentEl_=createEl(contentElType,{className:'vjs-menu-content'});this.contentEl_.setAttribute('role','menu');var el=_Component.prototype.createEl.call(this,'div',{append:this.contentEl_,className:'vjs-menu'});el.appendChild(this.contentEl_);on(el,'click',function(event){event.preventDefault();event.stopImmediatePropagation();});return el;};_proto.dispose=function dispose(){this.contentEl_=null;this.boundHandleBlur_=null;this.boundHandleTapClick_=null;_Component.prototype.dispose.call(this);};_proto.handleBlur=function handleBlur(event){var relatedTarget=event.relatedTarget||document_1.activeElement;if(!this.children().some(function(element){return element.el()===relatedTarget;})){var btn=this.menuButton_;if(btn&&btn.buttonPressed_&&relatedTarget!==btn.el().firstChild){btn.unpressButton();}}};_proto.handleTapClick=function handleTapClick(event){if(this.menuButton_){this.menuButton_.unpressButton();var childComponents=this.children();if(!Array.isArray(childComponents)){return;}
var foundComponent=childComponents.filter(function(component){return component.el()===event.target;})[0];if(!foundComponent){return;}
if(foundComponent.name()!=='CaptionSettingsMenuItem'){this.menuButton_.focus();}}};_proto.handleKeyDown=function handleKeyDown(event){if(keycode.isEventKey(event,'Left')||keycode.isEventKey(event,'Down')){event.preventDefault();event.stopPropagation();this.stepForward();}else if(keycode.isEventKey(event,'Right')||keycode.isEventKey(event,'Up')){event.preventDefault();event.stopPropagation();this.stepBack();}};_proto.stepForward=function stepForward(){var stepChild=0;if(this.focusedChild_!==undefined){stepChild=this.focusedChild_+1;}
this.focus(stepChild);};_proto.stepBack=function stepBack(){var stepChild=0;if(this.focusedChild_!==undefined){stepChild=this.focusedChild_-1;}
this.focus(stepChild);};_proto.focus=function focus(item){if(item===void 0){item=0;}
var children=this.children().slice();var haveTitle=children.length&&children[0].hasClass('vjs-menu-title');if(haveTitle){children.shift();}
if(children.length>0){if(item<0){item=0;}else if(item>=children.length){item=children.length-1;}
this.focusedChild_=item;children[item].el_.focus();}};return Menu;}(Component);Component.registerComponent('Menu',Menu);var MenuButton=function(_Component){inheritsLoose(MenuButton,_Component);function MenuButton(player,options){var _this;if(options===void 0){options={};}
_this=_Component.call(this,player,options)||this;_this.menuButton_=new Button(player,options);_this.menuButton_.controlText(_this.controlText_);_this.menuButton_.el_.setAttribute('aria-haspopup','true');var buttonClass=Button.prototype.buildCSSClass();_this.menuButton_.el_.className=_this.buildCSSClass()+' '+buttonClass;_this.menuButton_.removeClass('vjs-control');_this.addChild(_this.menuButton_);_this.update();_this.enabled_=true;_this.on(_this.menuButton_,'tap',_this.handleClick);_this.on(_this.menuButton_,'click',_this.handleClick);_this.on(_this.menuButton_,'keydown',_this.handleKeyDown);_this.on(_this.menuButton_,'mouseenter',function(){_this.addClass('vjs-hover');_this.menu.show();on(document_1,'keyup',bind(assertThisInitialized(_this),_this.handleMenuKeyUp));});_this.on('mouseleave',_this.handleMouseLeave);_this.on('keydown',_this.handleSubmenuKeyDown);return _this;}
var _proto=MenuButton.prototype;_proto.update=function update(){var menu=this.createMenu();if(this.menu){this.menu.dispose();this.removeChild(this.menu);}
this.menu=menu;this.addChild(menu);this.buttonPressed_=false;this.menuButton_.el_.setAttribute('aria-expanded','false');if(this.items&&this.items.length<=this.hideThreshold_){this.hide();}else{this.show();}};_proto.createMenu=function createMenu(){var menu=new Menu(this.player_,{menuButton:this});this.hideThreshold_=0;if(this.options_.title){var titleEl=createEl('li',{className:'vjs-menu-title',innerHTML:toTitleCase(this.options_.title),tabIndex:-1});this.hideThreshold_+=1;var titleComponent=new Component(this.player_,{el:titleEl});menu.addItem(titleComponent);}
this.items=this.createItems();if(this.items){for(var i=0;i<this.items.length;i++){menu.addItem(this.items[i]);}}
return menu;};_proto.createItems=function createItems(){};_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'div',{className:this.buildWrapperCSSClass()},{});};_proto.buildWrapperCSSClass=function buildWrapperCSSClass(){var menuButtonClass='vjs-menu-button';if(this.options_.inline===true){menuButtonClass+='-inline';}else{menuButtonClass+='-popup';}
var buttonClass=Button.prototype.buildCSSClass();return"vjs-menu-button "+menuButtonClass+" "+buttonClass+" "+_Component.prototype.buildCSSClass.call(this);};_proto.buildCSSClass=function buildCSSClass(){var menuButtonClass='vjs-menu-button';if(this.options_.inline===true){menuButtonClass+='-inline';}else{menuButtonClass+='-popup';}
return"vjs-menu-button "+menuButtonClass+" "+_Component.prototype.buildCSSClass.call(this);};_proto.controlText=function controlText(text,el){if(el===void 0){el=this.menuButton_.el();}
return this.menuButton_.controlText(text,el);};_proto.dispose=function dispose(){this.handleMouseLeave();_Component.prototype.dispose.call(this);};_proto.handleClick=function handleClick(event){if(this.buttonPressed_){this.unpressButton();}else{this.pressButton();}};_proto.handleMouseLeave=function handleMouseLeave(event){this.removeClass('vjs-hover');off(document_1,'keyup',bind(this,this.handleMenuKeyUp));};_proto.focus=function focus(){this.menuButton_.focus();};_proto.blur=function blur(){this.menuButton_.blur();};_proto.handleKeyDown=function handleKeyDown(event){if(keycode.isEventKey(event,'Esc')||keycode.isEventKey(event,'Tab')){if(this.buttonPressed_){this.unpressButton();}
if(!keycode.isEventKey(event,'Tab')){event.preventDefault();this.menuButton_.focus();}}else if(keycode.isEventKey(event,'Up')||keycode.isEventKey(event,'Down')){if(!this.buttonPressed_){event.preventDefault();this.pressButton();}}};_proto.handleMenuKeyUp=function handleMenuKeyUp(event){if(keycode.isEventKey(event,'Esc')||keycode.isEventKey(event,'Tab')){this.removeClass('vjs-hover');}};_proto.handleSubmenuKeyPress=function handleSubmenuKeyPress(event){this.handleSubmenuKeyDown(event);};_proto.handleSubmenuKeyDown=function handleSubmenuKeyDown(event){if(keycode.isEventKey(event,'Esc')||keycode.isEventKey(event,'Tab')){if(this.buttonPressed_){this.unpressButton();}
if(!keycode.isEventKey(event,'Tab')){event.preventDefault();this.menuButton_.focus();}}};_proto.pressButton=function pressButton(){if(this.enabled_){this.buttonPressed_=true;this.menu.show();this.menu.lockShowing();this.menuButton_.el_.setAttribute('aria-expanded','true');if(IS_IOS&&isInFrame()){return;}
this.menu.focus();}};_proto.unpressButton=function unpressButton(){if(this.enabled_){this.buttonPressed_=false;this.menu.unlockShowing();this.menu.hide();this.menuButton_.el_.setAttribute('aria-expanded','false');}};_proto.disable=function disable(){this.unpressButton();this.enabled_=false;this.addClass('vjs-disabled');this.menuButton_.disable();};_proto.enable=function enable(){this.enabled_=true;this.removeClass('vjs-disabled');this.menuButton_.enable();};return MenuButton;}(Component);Component.registerComponent('MenuButton',MenuButton);var TrackButton=function(_MenuButton){inheritsLoose(TrackButton,_MenuButton);function TrackButton(player,options){var _this;var tracks=options.tracks;_this=_MenuButton.call(this,player,options)||this;if(_this.items.length<=1){_this.hide();}
if(!tracks){return assertThisInitialized(_this);}
var updateHandler=bind(assertThisInitialized(_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);});return _this;}
return TrackButton;}(MenuButton);Component.registerComponent('TrackButton',TrackButton);var MenuKeys=['Tab','Esc','Up','Down','Right','Left'];var MenuItem=function(_ClickableComponent){inheritsLoose(MenuItem,_ClickableComponent);function MenuItem(player,options){var _this;_this=_ClickableComponent.call(this,player,options)||this;_this.selectable=options.selectable;_this.isSelected_=options.selected||false;_this.multiSelectable=options.multiSelectable;_this.selected(_this.isSelected_);if(_this.selectable){if(_this.multiSelectable){_this.el_.setAttribute('role','menuitemcheckbox');}else{_this.el_.setAttribute('role','menuitemradio');}}else{_this.el_.setAttribute('role','menuitem');}
return _this;}
var _proto=MenuItem.prototype;_proto.createEl=function createEl(type,props,attrs){this.nonIconControl=true;return _ClickableComponent.prototype.createEl.call(this,'li',assign({className:'vjs-menu-item',innerHTML:"<span class=\"vjs-menu-item-text\">"+this.localize(this.options_.label)+"</span>",tabIndex:-1},props),attrs);};_proto.handleKeyDown=function handleKeyDown(event){if(!MenuKeys.some(function(key){return keycode.isEventKey(event,key);})){_ClickableComponent.prototype.handleKeyDown.call(this,event);}};_proto.handleClick=function handleClick(event){this.selected(true);};_proto.selected=function selected(_selected){if(this.selectable){if(_selected){this.addClass('vjs-selected');this.el_.setAttribute('aria-checked','true');this.controlText(', selected');this.isSelected_=true;}else{this.removeClass('vjs-selected');this.el_.setAttribute('aria-checked','false');this.controlText('');this.isSelected_=false;}}};return MenuItem;}(ClickableComponent);Component.registerComponent('MenuItem',MenuItem);var TextTrackMenuItem=function(_MenuItem){inheritsLoose(TextTrackMenuItem,_MenuItem);function TextTrackMenuItem(player,options){var _this;var track=options.track;var tracks=player.textTracks();options.label=track.label||track.language||'Unknown';options.selected=track.mode==='showing';_this=_MenuItem.call(this,player,options)||this;_this.track=track;_this.kinds=(options.kinds||[options.kind||_this.track.kind]).filter(Boolean);var changeHandler=function changeHandler(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}
_this.handleTracksChange.apply(assertThisInitialized(_this),args);};var selectedLanguageChangeHandler=function selectedLanguageChangeHandler(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2];}
_this.handleSelectedLanguageChange.apply(assertThisInitialized(_this),args);};player.on(['loadstart','texttrackchange'],changeHandler);tracks.addEventListener('change',changeHandler);tracks.addEventListener('selectedlanguagechange',selectedLanguageChangeHandler);_this.on('dispose',function(){player.off(['loadstart','texttrackchange'],changeHandler);tracks.removeEventListener('change',changeHandler);tracks.removeEventListener('selectedlanguagechange',selectedLanguageChangeHandler);});if(tracks.onchange===undefined){var event;_this.on(['tap','click'],function(){if(typeof window_1.Event!=='object'){try{event=new window_1.Event('change');}catch(err){}}
if(!event){event=document_1.createEvent('Event');event.initEvent('change',true,true);}
tracks.dispatchEvent(event);});}
_this.handleTracksChange();return _this;}
var _proto=TextTrackMenuItem.prototype;_proto.handleClick=function handleClick(event){var referenceTrack=this.track;var tracks=this.player_.textTracks();_MenuItem.prototype.handleClick.call(this,event);if(!tracks){return;}
for(var i=0;i<tracks.length;i++){var track=tracks[i];if(this.kinds.indexOf(track.kind)===-1){continue;}
if(track===referenceTrack){if(track.mode!=='showing'){track.mode='showing';}}else if(track.mode!=='disabled'){track.mode='disabled';}}};_proto.handleTracksChange=function handleTracksChange(event){var shouldBeSelected=this.track.mode==='showing';if(shouldBeSelected!==this.isSelected_){this.selected(shouldBeSelected);}};_proto.handleSelectedLanguageChange=function handleSelectedLanguageChange(event){if(this.track.mode==='showing'){var 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:true,language:this.track.language,kind:this.track.kind};}};_proto.dispose=function dispose(){this.track=null;_MenuItem.prototype.dispose.call(this);};return TextTrackMenuItem;}(MenuItem);Component.registerComponent('TextTrackMenuItem',TextTrackMenuItem);var OffTextTrackMenuItem=function(_TextTrackMenuItem){inheritsLoose(OffTextTrackMenuItem,_TextTrackMenuItem);function OffTextTrackMenuItem(player,options){options.track={player:player,kind:options.kind,kinds:options.kinds,"default":false,mode:'disabled'};if(!options.kinds){options.kinds=[options.kind];}
if(options.label){options.track.label=options.label;}else{options.track.label=options.kinds.join(' and ')+' off';}
options.selectable=true;options.multiSelectable=false;return _TextTrackMenuItem.call(this,player,options)||this;}
var _proto=OffTextTrackMenuItem.prototype;_proto.handleTracksChange=function handleTracksChange(event){var tracks=this.player().textTracks();var shouldBeSelected=true;for(var i=0,l=tracks.length;i<l;i++){var track=tracks[i];if(this.options_.kinds.indexOf(track.kind)>-1&&track.mode==='showing'){shouldBeSelected=false;break;}}
if(shouldBeSelected!==this.isSelected_){this.selected(shouldBeSelected);}};_proto.handleSelectedLanguageChange=function handleSelectedLanguageChange(event){var tracks=this.player().textTracks();var allHidden=true;for(var i=0,l=tracks.length;i<l;i++){var track=tracks[i];if(['captions','descriptions','subtitles'].indexOf(track.kind)>-1&&track.mode==='showing'){allHidden=false;break;}}
if(allHidden){this.player_.cache_.selectedLanguage={enabled:false};}};return OffTextTrackMenuItem;}(TextTrackMenuItem);Component.registerComponent('OffTextTrackMenuItem',OffTextTrackMenuItem);var TextTrackButton=function(_TrackButton){inheritsLoose(TextTrackButton,_TrackButton);function TextTrackButton(player,options){if(options===void 0){options={};}
options.tracks=player.textTracks();return _TrackButton.call(this,player,options)||this;}
var _proto=TextTrackButton.prototype;_proto.createItems=function createItems(items,TrackMenuItem){if(items===void 0){items=[];}
if(TrackMenuItem===void 0){TrackMenuItem=TextTrackMenuItem;}
var label;if(this.label_){label=this.label_+" off";}
items.push(new OffTextTrackMenuItem(this.player_,{kinds:this.kinds_,kind:this.kind_,label:label}));this.hideThreshold_+=1;var tracks=this.player_.textTracks();if(!Array.isArray(this.kinds_)){this.kinds_=[this.kind_];}
for(var i=0;i<tracks.length;i++){var track=tracks[i];if(this.kinds_.indexOf(track.kind)>-1){var item=new TrackMenuItem(this.player_,{track:track,kinds:this.kinds_,kind:this.kind_,selectable:true,multiSelectable:false});item.addClass("vjs-"+track.kind+"-menu-item");items.push(item);}}
return items;};return TextTrackButton;}(TrackButton);Component.registerComponent('TextTrackButton',TextTrackButton);var ChaptersTrackMenuItem=function(_MenuItem){inheritsLoose(ChaptersTrackMenuItem,_MenuItem);function ChaptersTrackMenuItem(player,options){var _this;var track=options.track;var cue=options.cue;var currentTime=player.currentTime();options.selectable=true;options.multiSelectable=false;options.label=cue.text;options.selected=cue.startTime<=currentTime&&currentTime<cue.endTime;_this=_MenuItem.call(this,player,options)||this;_this.track=track;_this.cue=cue;track.addEventListener('cuechange',bind(assertThisInitialized(_this),_this.update));return _this;}
var _proto=ChaptersTrackMenuItem.prototype;_proto.handleClick=function handleClick(event){_MenuItem.prototype.handleClick.call(this);this.player_.currentTime(this.cue.startTime);this.update(this.cue.startTime);};_proto.update=function update(event){var cue=this.cue;var currentTime=this.player_.currentTime();this.selected(cue.startTime<=currentTime&&currentTime<cue.endTime);};return ChaptersTrackMenuItem;}(MenuItem);Component.registerComponent('ChaptersTrackMenuItem',ChaptersTrackMenuItem);var ChaptersButton=function(_TextTrackButton){inheritsLoose(ChaptersButton,_TextTrackButton);function ChaptersButton(player,options,ready){return _TextTrackButton.call(this,player,options,ready)||this;}
var _proto=ChaptersButton.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-chapters-button "+_TextTrackButton.prototype.buildCSSClass.call(this);};_proto.buildWrapperCSSClass=function buildWrapperCSSClass(){return"vjs-chapters-button "+_TextTrackButton.prototype.buildWrapperCSSClass.call(this);};_proto.update=function update(event){if(!this.track_||event&&(event.type==='addtrack'||event.type==='removetrack')){this.setTrack(this.findChaptersTrack());}
_TextTrackButton.prototype.update.call(this);};_proto.setTrack=function setTrack(track){if(this.track_===track){return;}
if(!this.updateHandler_){this.updateHandler_=this.update.bind(this);}
if(this.track_){var remoteTextTrackEl=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);if(remoteTextTrackEl){remoteTextTrackEl.removeEventListener('load',this.updateHandler_);}
this.track_=null;}
this.track_=track;if(this.track_){this.track_.mode='hidden';var _remoteTextTrackEl=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);if(_remoteTextTrackEl){_remoteTextTrackEl.addEventListener('load',this.updateHandler_);}}};_proto.findChaptersTrack=function findChaptersTrack(){var tracks=this.player_.textTracks()||[];for(var i=tracks.length-1;i>=0;i--){var track=tracks[i];if(track.kind===this.kind_){return track;}}};_proto.getMenuCaption=function getMenuCaption(){if(this.track_&&this.track_.label){return this.track_.label;}
return this.localize(toTitleCase(this.kind_));};_proto.createMenu=function createMenu(){this.options_.title=this.getMenuCaption();return _TextTrackButton.prototype.createMenu.call(this);};_proto.createItems=function createItems(){var items=[];if(!this.track_){return items;}
var cues=this.track_.cues;if(!cues){return items;}
for(var i=0,l=cues.length;i<l;i++){var cue=cues[i];var mi=new ChaptersTrackMenuItem(this.player_,{track:this.track_,cue:cue});items.push(mi);}
return items;};return ChaptersButton;}(TextTrackButton);ChaptersButton.prototype.kind_='chapters';ChaptersButton.prototype.controlText_='Chapters';Component.registerComponent('ChaptersButton',ChaptersButton);var DescriptionsButton=function(_TextTrackButton){inheritsLoose(DescriptionsButton,_TextTrackButton);function DescriptionsButton(player,options,ready){var _this;_this=_TextTrackButton.call(this,player,options,ready)||this;var tracks=player.textTracks();var changeHandler=bind(assertThisInitialized(_this),_this.handleTracksChange);tracks.addEventListener('change',changeHandler);_this.on('dispose',function(){tracks.removeEventListener('change',changeHandler);});return _this;}
var _proto=DescriptionsButton.prototype;_proto.handleTracksChange=function handleTracksChange(event){var tracks=this.player().textTracks();var disabled=false;for(var i=0,l=tracks.length;i<l;i++){var track=tracks[i];if(track.kind!==this.kind_&&track.mode==='showing'){disabled=true;break;}}
if(disabled){this.disable();}else{this.enable();}};_proto.buildCSSClass=function buildCSSClass(){return"vjs-descriptions-button "+_TextTrackButton.prototype.buildCSSClass.call(this);};_proto.buildWrapperCSSClass=function buildWrapperCSSClass(){return"vjs-descriptions-button "+_TextTrackButton.prototype.buildWrapperCSSClass.call(this);};return DescriptionsButton;}(TextTrackButton);DescriptionsButton.prototype.kind_='descriptions';DescriptionsButton.prototype.controlText_='Descriptions';Component.registerComponent('DescriptionsButton',DescriptionsButton);var SubtitlesButton=function(_TextTrackButton){inheritsLoose(SubtitlesButton,_TextTrackButton);function SubtitlesButton(player,options,ready){return _TextTrackButton.call(this,player,options,ready)||this;}
var _proto=SubtitlesButton.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-subtitles-button "+_TextTrackButton.prototype.buildCSSClass.call(this);};_proto.buildWrapperCSSClass=function buildWrapperCSSClass(){return"vjs-subtitles-button "+_TextTrackButton.prototype.buildWrapperCSSClass.call(this);};return SubtitlesButton;}(TextTrackButton);SubtitlesButton.prototype.kind_='subtitles';SubtitlesButton.prototype.controlText_='Subtitles';Component.registerComponent('SubtitlesButton',SubtitlesButton);var CaptionSettingsMenuItem=function(_TextTrackMenuItem){inheritsLoose(CaptionSettingsMenuItem,_TextTrackMenuItem);function CaptionSettingsMenuItem(player,options){var _this;options.track={player:player,kind:options.kind,label:options.kind+' settings',selectable:false,"default":false,mode:'disabled'};options.selectable=false;options.name='CaptionSettingsMenuItem';_this=_TextTrackMenuItem.call(this,player,options)||this;_this.addClass('vjs-texttrack-settings');_this.controlText(', opens '+options.kind+' settings dialog');return _this;}
var _proto=CaptionSettingsMenuItem.prototype;_proto.handleClick=function handleClick(event){this.player().getChild('textTrackSettings').open();};return CaptionSettingsMenuItem;}(TextTrackMenuItem);Component.registerComponent('CaptionSettingsMenuItem',CaptionSettingsMenuItem);var CaptionsButton=function(_TextTrackButton){inheritsLoose(CaptionsButton,_TextTrackButton);function CaptionsButton(player,options,ready){return _TextTrackButton.call(this,player,options,ready)||this;}
var _proto=CaptionsButton.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-captions-button "+_TextTrackButton.prototype.buildCSSClass.call(this);};_proto.buildWrapperCSSClass=function buildWrapperCSSClass(){return"vjs-captions-button "+_TextTrackButton.prototype.buildWrapperCSSClass.call(this);};_proto.createItems=function createItems(){var items=[];if(!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild('textTrackSettings')){items.push(new CaptionSettingsMenuItem(this.player_,{kind:this.kind_}));this.hideThreshold_+=1;}
return _TextTrackButton.prototype.createItems.call(this,items);};return CaptionsButton;}(TextTrackButton);CaptionsButton.prototype.kind_='captions';CaptionsButton.prototype.controlText_='Captions';Component.registerComponent('CaptionsButton',CaptionsButton);var SubsCapsMenuItem=function(_TextTrackMenuItem){inheritsLoose(SubsCapsMenuItem,_TextTrackMenuItem);function SubsCapsMenuItem(){return _TextTrackMenuItem.apply(this,arguments)||this;}
var _proto=SubsCapsMenuItem.prototype;_proto.createEl=function createEl(type,props,attrs){var innerHTML="<span class=\"vjs-menu-item-text\">"+this.localize(this.options_.label);if(this.options_.track.kind==='captions'){innerHTML+="\n        <span aria-hidden=\"true\" class=\"vjs-icon-placeholder\"></span>\n        <span class=\"vjs-control-text\"> "+this.localize('Captions')+"</span>\n      ";}
innerHTML+='</span>';var el=_TextTrackMenuItem.prototype.createEl.call(this,type,assign({innerHTML:innerHTML},props),attrs);return el;};return SubsCapsMenuItem;}(TextTrackMenuItem);Component.registerComponent('SubsCapsMenuItem',SubsCapsMenuItem);var SubsCapsButton=function(_TextTrackButton){inheritsLoose(SubsCapsButton,_TextTrackButton);function SubsCapsButton(player,options){var _this;if(options===void 0){options={};}
_this=_TextTrackButton.call(this,player,options)||this;_this.label_='subtitles';if(['en','en-us','en-ca','fr-ca'].indexOf(_this.player_.language_)>-1){_this.label_='captions';}
_this.menuButton_.controlText(toTitleCase(_this.label_));return _this;}
var _proto=SubsCapsButton.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-subs-caps-button "+_TextTrackButton.prototype.buildCSSClass.call(this);};_proto.buildWrapperCSSClass=function buildWrapperCSSClass(){return"vjs-subs-caps-button "+_TextTrackButton.prototype.buildWrapperCSSClass.call(this);};_proto.createItems=function createItems(){var items=[];if(!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild('textTrackSettings')){items.push(new CaptionSettingsMenuItem(this.player_,{kind:this.label_}));this.hideThreshold_+=1;}
items=_TextTrackButton.prototype.createItems.call(this,items,SubsCapsMenuItem);return items;};return SubsCapsButton;}(TextTrackButton);SubsCapsButton.prototype.kinds_=['captions','subtitles'];SubsCapsButton.prototype.controlText_='Subtitles';Component.registerComponent('SubsCapsButton',SubsCapsButton);var AudioTrackMenuItem=function(_MenuItem){inheritsLoose(AudioTrackMenuItem,_MenuItem);function AudioTrackMenuItem(player,options){var _this;var track=options.track;var tracks=player.audioTracks();options.label=track.label||track.language||'Unknown';options.selected=track.enabled;_this=_MenuItem.call(this,player,options)||this;_this.track=track;_this.addClass("vjs-"+track.kind+"-menu-item");var changeHandler=function changeHandler(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}
_this.handleTracksChange.apply(assertThisInitialized(_this),args);};tracks.addEventListener('change',changeHandler);_this.on('dispose',function(){tracks.removeEventListener('change',changeHandler);});return _this;}
var _proto=AudioTrackMenuItem.prototype;_proto.createEl=function createEl(type,props,attrs){var innerHTML="<span class=\"vjs-menu-item-text\">"+this.localize(this.options_.label);if(this.options_.track.kind==='main-desc'){innerHTML+="\n        <span aria-hidden=\"true\" class=\"vjs-icon-placeholder\"></span>\n        <span class=\"vjs-control-text\"> "+this.localize('Descriptions')+"</span>\n      ";}
innerHTML+='</span>';var el=_MenuItem.prototype.createEl.call(this,type,assign({innerHTML:innerHTML},props),attrs);return el;};_proto.handleClick=function handleClick(event){var tracks=this.player_.audioTracks();_MenuItem.prototype.handleClick.call(this,event);for(var i=0;i<tracks.length;i++){var track=tracks[i];track.enabled=track===this.track;}};_proto.handleTracksChange=function handleTracksChange(event){this.selected(this.track.enabled);};return AudioTrackMenuItem;}(MenuItem);Component.registerComponent('AudioTrackMenuItem',AudioTrackMenuItem);var AudioTrackButton=function(_TrackButton){inheritsLoose(AudioTrackButton,_TrackButton);function AudioTrackButton(player,options){if(options===void 0){options={};}
options.tracks=player.audioTracks();return _TrackButton.call(this,player,options)||this;}
var _proto=AudioTrackButton.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-audio-button "+_TrackButton.prototype.buildCSSClass.call(this);};_proto.buildWrapperCSSClass=function buildWrapperCSSClass(){return"vjs-audio-button "+_TrackButton.prototype.buildWrapperCSSClass.call(this);};_proto.createItems=function createItems(items){if(items===void 0){items=[];}
this.hideThreshold_=1;var tracks=this.player_.audioTracks();for(var i=0;i<tracks.length;i++){var track=tracks[i];items.push(new AudioTrackMenuItem(this.player_,{track:track,selectable:true,multiSelectable:false}));}
return items;};return AudioTrackButton;}(TrackButton);AudioTrackButton.prototype.controlText_='Audio Track';Component.registerComponent('AudioTrackButton',AudioTrackButton);var PlaybackRateMenuItem=function(_MenuItem){inheritsLoose(PlaybackRateMenuItem,_MenuItem);function PlaybackRateMenuItem(player,options){var _this;var label=options.rate;var rate=parseFloat(label,10);options.label=label;options.selected=rate===1;options.selectable=true;options.multiSelectable=false;_this=_MenuItem.call(this,player,options)||this;_this.label=label;_this.rate=rate;_this.on(player,'ratechange',_this.update);return _this;}
var _proto=PlaybackRateMenuItem.prototype;_proto.handleClick=function handleClick(event){_MenuItem.prototype.handleClick.call(this);this.player().playbackRate(this.rate);};_proto.update=function update(event){this.selected(this.player().playbackRate()===this.rate);};return PlaybackRateMenuItem;}(MenuItem);PlaybackRateMenuItem.prototype.contentElType='button';Component.registerComponent('PlaybackRateMenuItem',PlaybackRateMenuItem);var PlaybackRateMenuButton=function(_MenuButton){inheritsLoose(PlaybackRateMenuButton,_MenuButton);function PlaybackRateMenuButton(player,options){var _this;_this=_MenuButton.call(this,player,options)||this;_this.updateVisibility();_this.updateLabel();_this.on(player,'loadstart',_this.updateVisibility);_this.on(player,'ratechange',_this.updateLabel);return _this;}
var _proto=PlaybackRateMenuButton.prototype;_proto.createEl=function createEl$1(){var el=_MenuButton.prototype.createEl.call(this);this.labelEl_=createEl('div',{className:'vjs-playback-rate-value',innerHTML:'1x'});el.appendChild(this.labelEl_);return el;};_proto.dispose=function dispose(){this.labelEl_=null;_MenuButton.prototype.dispose.call(this);};_proto.buildCSSClass=function buildCSSClass(){return"vjs-playback-rate "+_MenuButton.prototype.buildCSSClass.call(this);};_proto.buildWrapperCSSClass=function buildWrapperCSSClass(){return"vjs-playback-rate "+_MenuButton.prototype.buildWrapperCSSClass.call(this);};_proto.createMenu=function createMenu(){var menu=new Menu(this.player());var rates=this.playbackRates();if(rates){for(var i=rates.length-1;i>=0;i--){menu.addChild(new PlaybackRateMenuItem(this.player(),{rate:rates[i]+'x'}));}}
return menu;};_proto.updateARIAAttributes=function updateARIAAttributes(){this.el().setAttribute('aria-valuenow',this.player().playbackRate());};_proto.handleClick=function handleClick(event){var currentRate=this.player().playbackRate();var rates=this.playbackRates();var newRate=rates[0];for(var i=0;i<rates.length;i++){if(rates[i]>currentRate){newRate=rates[i];break;}}
this.player().playbackRate(newRate);};_proto.playbackRates=function playbackRates(){return this.options_.playbackRates||this.options_.playerOptions&&this.options_.playerOptions.playbackRates;};_proto.playbackRateSupported=function playbackRateSupported(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0;};_proto.updateVisibility=function updateVisibility(event){if(this.playbackRateSupported()){this.removeClass('vjs-hidden');}else{this.addClass('vjs-hidden');}};_proto.updateLabel=function updateLabel(event){if(this.playbackRateSupported()){this.labelEl_.innerHTML=this.player().playbackRate()+'x';}};return PlaybackRateMenuButton;}(MenuButton);PlaybackRateMenuButton.prototype.controlText_='Playback Rate';Component.registerComponent('PlaybackRateMenuButton',PlaybackRateMenuButton);var Spacer=function(_Component){inheritsLoose(Spacer,_Component);function Spacer(){return _Component.apply(this,arguments)||this;}
var _proto=Spacer.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-spacer "+_Component.prototype.buildCSSClass.call(this);};_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'div',{className:this.buildCSSClass()});};return Spacer;}(Component);Component.registerComponent('Spacer',Spacer);var CustomControlSpacer=function(_Spacer){inheritsLoose(CustomControlSpacer,_Spacer);function CustomControlSpacer(){return _Spacer.apply(this,arguments)||this;}
var _proto=CustomControlSpacer.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-custom-control-spacer "+_Spacer.prototype.buildCSSClass.call(this);};_proto.createEl=function createEl(){var el=_Spacer.prototype.createEl.call(this,{className:this.buildCSSClass()});el.innerHTML="\xA0";return el;};return CustomControlSpacer;}(Spacer);Component.registerComponent('CustomControlSpacer',CustomControlSpacer);var ControlBar=function(_Component){inheritsLoose(ControlBar,_Component);function ControlBar(){return _Component.apply(this,arguments)||this;}
var _proto=ControlBar.prototype;_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'div',{className:'vjs-control-bar',dir:'ltr'});};return ControlBar;}(Component);ControlBar.prototype.options_={children:['playToggle','volumePanel','currentTimeDisplay','timeDivider','durationDisplay','progressControl','liveDisplay','seekToLive','remainingTimeDisplay','customControlSpacer','playbackRateMenuButton','chaptersButton','descriptionsButton','subsCapsButton','audioTrackButton','fullscreenToggle']};if('exitPictureInPicture'in document_1){ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length-1,0,'pictureInPictureToggle');}
Component.registerComponent('ControlBar',ControlBar);var ErrorDisplay=function(_ModalDialog){inheritsLoose(ErrorDisplay,_ModalDialog);function ErrorDisplay(player,options){var _this;_this=_ModalDialog.call(this,player,options)||this;_this.on(player,'error',_this.open);return _this;}
var _proto=ErrorDisplay.prototype;_proto.buildCSSClass=function buildCSSClass(){return"vjs-error-display "+_ModalDialog.prototype.buildCSSClass.call(this);};_proto.content=function content(){var error=this.player().error();return error?this.localize(error.message):'';};return ErrorDisplay;}(ModalDialog);ErrorDisplay.prototype.options_=_extends_1({},ModalDialog.prototype.options_,{pauseOnOpen:false,fillAlways:true,temporary:false,uncloseable:true});Component.registerComponent('ErrorDisplay',ErrorDisplay);var LOCAL_STORAGE_KEY='vjs-text-track-settings';var COLOR_BLACK=['#000','Black'];var COLOR_BLUE=['#00F','Blue'];var COLOR_CYAN=['#0FF','Cyan'];var COLOR_GREEN=['#0F0','Green'];var COLOR_MAGENTA=['#F0F','Magenta'];var COLOR_RED=['#F00','Red'];var COLOR_WHITE=['#FFF','White'];var COLOR_YELLOW=['#FF0','Yellow'];var OPACITY_OPAQUE=['1','Opaque'];var OPACITY_SEMI=['0.5','Semi-Transparent'];var OPACITY_TRANS=['0','Transparent'];var 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:'Transparency',options:[OPACITY_OPAQUE,OPACITY_SEMI,OPACITY_TRANS]},color:{selector:'.vjs-fg-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','Dropshadow']]},fontFamily:{selector:'.vjs-font-family > select',id:'captions-font-family-%s',label:'Font Family',options:[['proportionalSansSerif','Proportional Sans-Serif'],['monospaceSansSerif','Monospace Sans-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:function parser(v){return v==='1.00'?null:Number(v);}},textOpacity:{selector:'.vjs-text-opacity > select',id:'captions-foreground-opacity-%s',label:'Transparency',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:'Transparency',options:[OPACITY_TRANS,OPACITY_SEMI,OPACITY_OPAQUE]}};selectConfigs.windowColor.options=selectConfigs.backgroundColor.options;function parseOptionValue(value,parser){if(parser){value=parser(value);}
if(value&&value!=='none'){return value;}}
function getSelectedOptionValue(el,parser){var value=el.options[el.options.selectedIndex].value;return parseOptionValue(value,parser);}
function setSelectedOption(el,value,parser){if(!value){return;}
for(var i=0;i<el.options.length;i++){if(parseOptionValue(el.options[i].value,parser)===value){el.selectedIndex=i;break;}}}
var TextTrackSettings=function(_ModalDialog){inheritsLoose(TextTrackSettings,_ModalDialog);function TextTrackSettings(player,options){var _this;options.temporary=false;_this=_ModalDialog.call(this,player,options)||this;_this.updateDisplay=bind(assertThisInitialized(_this),_this.updateDisplay);_this.fill();_this.hasBeenOpened_=_this.hasBeenFilled_=true;_this.endDialog=createEl('p',{className:'vjs-control-text',textContent:_this.localize('End of dialog window.')});_this.el().appendChild(_this.endDialog);_this.setDefaults();if(options.persistTextTrackSettings===undefined){_this.options_.persistTextTrackSettings=_this.options_.playerOptions.persistTextTrackSettings;}
_this.on(_this.$('.vjs-done-button'),'click',function(){_this.saveSettings();_this.close();});_this.on(_this.$('.vjs-default-button'),'click',function(){_this.setDefaults();_this.updateDisplay();});each(selectConfigs,function(config){_this.on(_this.$(config.selector),'change',_this.updateDisplay);});if(_this.options_.persistTextTrackSettings){_this.restoreSettings();}
return _this;}
var _proto=TextTrackSettings.prototype;_proto.dispose=function dispose(){this.endDialog=null;_ModalDialog.prototype.dispose.call(this);};_proto.createElSelect_=function createElSelect_(key,legendId,type){var _this2=this;if(legendId===void 0){legendId='';}
if(type===void 0){type='label';}
var config=selectConfigs[key];var id=config.id.replace('%s',this.id_);var selectLabelledbyIds=[legendId,id].join(' ').trim();return["<"+type+" id=\""+id+"\" class=\""+(type==='label'?'vjs-label':'')+"\">",this.localize(config.label),"</"+type+">","<select aria-labelledby=\""+selectLabelledbyIds+"\">"].concat(config.options.map(function(o){var optionId=id+'-'+o[1].replace(/\W+/g,'');return["<option id=\""+optionId+"\" value=\""+o[0]+"\" ","aria-labelledby=\""+selectLabelledbyIds+" "+optionId+"\">",_this2.localize(o[1]),'</option>'].join('');})).concat('</select>').join('');};_proto.createElFgColor_=function createElFgColor_(){var legendId="captions-text-legend-"+this.id_;return['<fieldset class="vjs-fg-color vjs-track-setting">',"<legend id=\""+legendId+"\">",this.localize('Text'),'</legend>',this.createElSelect_('color',legendId),'<span class="vjs-text-opacity vjs-opacity">',this.createElSelect_('textOpacity',legendId),'</span>','</fieldset>'].join('');};_proto.createElBgColor_=function createElBgColor_(){var legendId="captions-background-"+this.id_;return['<fieldset class="vjs-bg-color vjs-track-setting">',"<legend id=\""+legendId+"\">",this.localize('Background'),'</legend>',this.createElSelect_('backgroundColor',legendId),'<span class="vjs-bg-opacity vjs-opacity">',this.createElSelect_('backgroundOpacity',legendId),'</span>','</fieldset>'].join('');};_proto.createElWinColor_=function createElWinColor_(){var legendId="captions-window-"+this.id_;return['<fieldset class="vjs-window-color vjs-track-setting">',"<legend id=\""+legendId+"\">",this.localize('Window'),'</legend>',this.createElSelect_('windowColor',legendId),'<span class="vjs-window-opacity vjs-opacity">',this.createElSelect_('windowOpacity',legendId),'</span>','</fieldset>'].join('');};_proto.createElColors_=function createElColors_(){return createEl('div',{className:'vjs-track-settings-colors',innerHTML:[this.createElFgColor_(),this.createElBgColor_(),this.createElWinColor_()].join('')});};_proto.createElFont_=function 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('')});};_proto.createElControls_=function createElControls_(){var 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=\""+defaultsDescription+"\">",this.localize('Reset'),"<span class=\"vjs-control-text\"> "+defaultsDescription+"</span>",'</button>',"<button type=\"button\" class=\"vjs-done-button\">"+this.localize('Done')+"</button>"].join('')});};_proto.content=function content(){return[this.createElColors_(),this.createElFont_(),this.createElControls_()];};_proto.label=function label(){return this.localize('Caption Settings Dialog');};_proto.description=function description(){return this.localize('Beginning of dialog window. Escape will cancel and close the window.');};_proto.buildCSSClass=function buildCSSClass(){return _ModalDialog.prototype.buildCSSClass.call(this)+' vjs-text-track-settings';};_proto.getValues=function getValues(){var _this3=this;return reduce(selectConfigs,function(accum,config,key){var value=getSelectedOptionValue(_this3.$(config.selector),config.parser);if(value!==undefined){accum[key]=value;}
return accum;},{});};_proto.setValues=function setValues(values){var _this4=this;each(selectConfigs,function(config,key){setSelectedOption(_this4.$(config.selector),values[key],config.parser);});};_proto.setDefaults=function setDefaults(){var _this5=this;each(selectConfigs,function(config){var index=config.hasOwnProperty('default')?config["default"]:0;_this5.$(config.selector).selectedIndex=index;});};_proto.restoreSettings=function restoreSettings(){var values;try{values=JSON.parse(window_1.localStorage.getItem(LOCAL_STORAGE_KEY));}catch(err){log.warn(err);}
if(values){this.setValues(values);}};_proto.saveSettings=function saveSettings(){if(!this.options_.persistTextTrackSettings){return;}
var values=this.getValues();try{if(Object.keys(values).length){window_1.localStorage.setItem(LOCAL_STORAGE_KEY,JSON.stringify(values));}else{window_1.localStorage.removeItem(LOCAL_STORAGE_KEY);}}catch(err){log.warn(err);}};_proto.updateDisplay=function updateDisplay(){var ttDisplay=this.player_.getChild('textTrackDisplay');if(ttDisplay){ttDisplay.updateDisplay();}};_proto.conditionalBlur_=function conditionalBlur_(){this.previouslyActiveEl_=null;var cb=this.player_.controlBar;var subsCapsBtn=cb&&cb.subsCapsButton;var ccBtn=cb&&cb.captionsButton;if(subsCapsBtn){subsCapsBtn.focus();}else if(ccBtn){ccBtn.focus();}};return TextTrackSettings;}(ModalDialog);Component.registerComponent('TextTrackSettings',TextTrackSettings);var ResizeManager=function(_Component){inheritsLoose(ResizeManager,_Component);function ResizeManager(player,options){var _this;var RESIZE_OBSERVER_AVAILABLE=options.ResizeObserver||window_1.ResizeObserver;if(options.ResizeObserver===null){RESIZE_OBSERVER_AVAILABLE=false;}
var options_=mergeOptions({createEl:!RESIZE_OBSERVER_AVAILABLE,reportTouchActivity:false},options);_this=_Component.call(this,player,options_)||this;_this.ResizeObserver=options.ResizeObserver||window_1.ResizeObserver;_this.loadListener_=null;_this.resizeObserver_=null;_this.debouncedHandler_=debounce(function(){_this.resizeHandler();},100,false,assertThisInitialized(_this));if(RESIZE_OBSERVER_AVAILABLE){_this.resizeObserver_=new _this.ResizeObserver(_this.debouncedHandler_);_this.resizeObserver_.observe(player.el());}else{_this.loadListener_=function(){if(!_this.el_||!_this.el_.contentWindow){return;}
var debouncedHandler_=_this.debouncedHandler_;var 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_);}
return _this;}
var _proto=ResizeManager.prototype;_proto.createEl=function createEl(){return _Component.prototype.createEl.call(this,'iframe',{className:'vjs-resize-manager',tabIndex:-1},{'aria-hidden':'true'});};_proto.resizeHandler=function resizeHandler(){if(!this.player_||!this.player_.trigger){return;}
this.player_.trigger('playerresize');};_proto.dispose=function dispose(){if(this.debouncedHandler_){this.debouncedHandler_.cancel();}
if(this.resizeObserver_){if(this.player_.el()){this.resizeObserver_.unobserve(this.player_.el());}
this.resizeObserver_.disconnect();}
if(this.loadListener_){this.off('load',this.loadListener_);}
if(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;_Component.prototype.dispose.call(this);};return ResizeManager;}(Component);Component.registerComponent('ResizeManager',ResizeManager);var defaults={trackingThreshold:30,liveTolerance:15};var LiveTracker=function(_Component){inheritsLoose(LiveTracker,_Component);function LiveTracker(player,options){var _this;var options_=mergeOptions(defaults,options,{createEl:false});_this=_Component.call(this,player,options_)||this;_this.reset_();_this.on(_this.player_,'durationchange',_this.handleDurationchange);if(IE_VERSION&&'hidden'in document_1&&'visibilityState'in document_1){_this.on(document_1,'visibilitychange',_this.handleVisibilityChange);}
return _this;}
var _proto=LiveTracker.prototype;_proto.handleVisibilityChange=function handleVisibilityChange(){if(this.player_.duration()!==Infinity){return;}
if(document_1.hidden){this.stopTracking();}else{this.startTracking();}};_proto.trackLive_=function trackLive_(){var seekable=this.player_.seekable();if(!seekable||!seekable.length){return;}
var newTime=Number(window_1.performance.now().toFixed(4));var deltaTime=this.lastTime_===-1?0:(newTime-this.lastTime_)/1000;this.lastTime_=newTime;this.pastSeekEnd_=this.pastSeekEnd()+deltaTime;var liveCurrentTime=this.liveCurrentTime();var currentTime=this.player_.currentTime();var isBehind=this.player_.paused()||this.seekedBehindLive_||Math.abs(liveCurrentTime-currentTime)>this.options_.liveTolerance;if(!this.timeupdateSeen_||liveCurrentTime===Infinity){isBehind=false;}
if(isBehind!==this.behindLiveEdge_){this.behindLiveEdge_=isBehind;this.trigger('liveedgechange');}};_proto.handleDurationchange=function handleDurationchange(){if(this.player_.duration()===Infinity&&this.liveWindow()>=this.options_.trackingThreshold){if(this.player_.options_.liveui){this.player_.addClass('vjs-liveui');}
this.startTracking();}else{this.player_.removeClass('vjs-liveui');this.stopTracking();}};_proto.startTracking=function startTracking(){if(this.isTracking()){return;}
if(!this.timeupdateSeen_){this.timeupdateSeen_=this.player_.hasStarted();}
this.trackingInterval_=this.setInterval(this.trackLive_,UPDATE_REFRESH_INTERVAL);this.trackLive_();this.on(this.player_,['play','pause'],this.trackLive_);if(!this.timeupdateSeen_){this.one(this.player_,'play',this.handlePlay);this.one(this.player_,'timeupdate',this.handleFirstTimeupdate);}else{this.on(this.player_,'seeked',this.handleSeeked);}};_proto.handleFirstTimeupdate=function handleFirstTimeupdate(){this.timeupdateSeen_=true;this.on(this.player_,'seeked',this.handleSeeked);};_proto.handleSeeked=function handleSeeked(){var timeDiff=Math.abs(this.liveCurrentTime()-this.player_.currentTime());this.seekedBehindLive_=this.skipNextSeeked_?false:timeDiff>2;this.skipNextSeeked_=false;this.trackLive_();};_proto.handlePlay=function handlePlay(){this.one(this.player_,'timeupdate',this.seekToLiveEdge);};_proto.reset_=function reset_(){this.lastTime_=-1;this.pastSeekEnd_=0;this.lastSeekEnd_=-1;this.behindLiveEdge_=true;this.timeupdateSeen_=false;this.seekedBehindLive_=false;this.skipNextSeeked_=false;this.clearInterval(this.trackingInterval_);this.trackingInterval_=null;this.off(this.player_,['play','pause'],this.trackLive_);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);};_proto.stopTracking=function stopTracking(){if(!this.isTracking()){return;}
this.reset_();this.trigger('liveedgechange');};_proto.seekableEnd=function seekableEnd(){var seekable=this.player_.seekable();var seekableEnds=[];var i=seekable?seekable.length:0;while(i--){seekableEnds.push(seekable.end(i));}
return seekableEnds.length?seekableEnds.sort()[seekableEnds.length-1]:Infinity;};_proto.seekableStart=function seekableStart(){var seekable=this.player_.seekable();var seekableStarts=[];var i=seekable?seekable.length:0;while(i--){seekableStarts.push(seekable.start(i));}
return seekableStarts.length?seekableStarts.sort()[0]:0;};_proto.liveWindow=function liveWindow(){var liveCurrentTime=this.liveCurrentTime();if(liveCurrentTime===Infinity){return 0;}
return liveCurrentTime-this.seekableStart();};_proto.isLive=function isLive(){return this.isTracking();};_proto.atLiveEdge=function atLiveEdge(){return!this.behindLiveEdge();};_proto.liveCurrentTime=function liveCurrentTime(){return this.pastSeekEnd()+this.seekableEnd();};_proto.pastSeekEnd=function pastSeekEnd(){var seekableEnd=this.seekableEnd();if(this.lastSeekEnd_!==-1&&seekableEnd!==this.lastSeekEnd_){this.pastSeekEnd_=0;}
this.lastSeekEnd_=seekableEnd;return this.pastSeekEnd_;};_proto.behindLiveEdge=function behindLiveEdge(){return this.behindLiveEdge_;};_proto.isTracking=function isTracking(){return typeof this.trackingInterval_==='number';};_proto.seekToLiveEdge=function seekToLiveEdge(){this.seekedBehindLive_=false;if(this.atLiveEdge()){return;}
this.skipNextSeeked_=true;this.player_.currentTime(this.liveCurrentTime());};_proto.dispose=function dispose(){this.off(document_1,'visibilitychange',this.handleVisibilityChange);this.stopTracking();_Component.prototype.dispose.call(this);};return LiveTracker;}(Component);Component.registerComponent('LiveTracker',LiveTracker);var sourcesetLoad=function sourcesetLoad(tech){var el=tech.el();if(el.hasAttribute('src')){tech.triggerSourceset(el.src);return true;}
var sources=tech.$$('source');var srcUrls=[];var src='';if(!sources.length){return false;}
for(var i=0;i<sources.length;i++){var url=sources[i].src;if(url&&srcUrls.indexOf(url)===-1){srcUrls.push(url);}}
if(!srcUrls.length){return false;}
if(srcUrls.length===1){src=srcUrls[0];}
tech.triggerSourceset(src);return true;};var innerHTMLDescriptorPolyfill=Object.defineProperty({},'innerHTML',{get:function get(){return this.cloneNode(true).innerHTML;},set:function set(v){var dummy=document_1.createElement(this.nodeName.toLowerCase());dummy.innerHTML=v;var docFrag=document_1.createDocumentFragment();while(dummy.childNodes.length){docFrag.appendChild(dummy.childNodes[0]);}
this.innerText='';window_1.Element.prototype.appendChild.call(this,docFrag);return this.innerHTML;}});var getDescriptor=function getDescriptor(priority,prop){var descriptor={};for(var i=0;i<priority.length;i++){descriptor=Object.getOwnPropertyDescriptor(priority[i],prop);if(descriptor&&descriptor.set&&descriptor.get){break;}}
descriptor.enumerable=true;descriptor.configurable=true;return descriptor;};var getInnerHTMLDescriptor=function getInnerHTMLDescriptor(tech){return getDescriptor([tech.el(),window_1.HTMLMediaElement.prototype,window_1.Element.prototype,innerHTMLDescriptorPolyfill],'innerHTML');};var firstSourceWatch=function firstSourceWatch(tech){var el=tech.el();if(el.resetSourceWatch_){return;}
var old={};var innerDescriptor=getInnerHTMLDescriptor(tech);var appendWrapper=function appendWrapper(appendFn){return function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}
var retval=appendFn.apply(el,args);sourcesetLoad(tech);return retval;};};['append','appendChild','insertAdjacentHTML'].forEach(function(k){if(!el[k]){return;}
old[k]=el[k];el[k]=appendWrapper(old[k]);});Object.defineProperty(el,'innerHTML',mergeOptions(innerDescriptor,{set:appendWrapper(innerDescriptor.set)}));el.resetSourceWatch_=function(){el.resetSourceWatch_=null;Object.keys(old).forEach(function(k){el[k]=old[k];});Object.defineProperty(el,'innerHTML',innerDescriptor);};tech.one('sourceset',el.resetSourceWatch_);};var srcDescriptorPolyfill=Object.defineProperty({},'src',{get:function get(){if(this.hasAttribute('src')){return getAbsoluteURL(window_1.Element.prototype.getAttribute.call(this,'src'));}
return'';},set:function set(v){window_1.Element.prototype.setAttribute.call(this,'src',v);return v;}});var getSrcDescriptor=function getSrcDescriptor(tech){return getDescriptor([tech.el(),window_1.HTMLMediaElement.prototype,srcDescriptorPolyfill],'src');};var setupSourceset=function setupSourceset(tech){if(!tech.featuresSourceset){return;}
var el=tech.el();if(el.resetSourceset_){return;}
var srcDescriptor=getSrcDescriptor(tech);var oldSetAttribute=el.setAttribute;var oldLoad=el.load;Object.defineProperty(el,'src',mergeOptions(srcDescriptor,{set:function set(v){var retval=srcDescriptor.set.call(el,v);tech.triggerSourceset(el.src);return retval;}}));el.setAttribute=function(n,v){var retval=oldSetAttribute.call(el,n,v);if(/src/i.test(n)){tech.triggerSourceset(el.src);}
return retval;};el.load=function(){var retval=oldLoad.call(el);if(!sourcesetLoad(tech)){tech.triggerSourceset('');firstSourceWatch(tech);}
return retval;};if(el.currentSrc){tech.triggerSourceset(el.currentSrc);}else if(!sourcesetLoad(tech)){firstSourceWatch(tech);}
el.resetSourceset_=function(){el.resetSourceset_=null;el.load=oldLoad;el.setAttribute=oldSetAttribute;Object.defineProperty(el,'src',srcDescriptor);if(el.resetSourceWatch_){el.resetSourceWatch_();}};};var defineLazyProperty=function defineLazyProperty(obj,key,getValue,setter){if(setter===void 0){setter=true;}
var set=function set(value){return Object.defineProperty(obj,key,{value:value,enumerable:true,writable:true});};var options={configurable:true,enumerable:true,get:function get(){var value=getValue();set(value);return value;}};if(setter){options.set=set;}
return Object.defineProperty(obj,key,options);};var Html5=function(_Tech){inheritsLoose(Html5,_Tech);function Html5(options,ready){var _this;_this=_Tech.call(this,options,ready)||this;var source=options.source;var crossoriginTracks=false;if(source&&(_this.el_.currentSrc!==source.src||options.tag&&options.tag.initNetworkState_===3)){_this.setSource(source);}else{_this.handleLateInit_(_this.el_);}
if(options.enableSourceset){_this.setupSourcesetHandling_();}
_this.isScrubbing_=false;if(_this.el_.hasChildNodes()){var nodes=_this.el_.childNodes;var nodesLength=nodes.length;var removeNodes=[];while(nodesLength--){var node=nodes[nodesLength];var nodeName=node.nodeName.toLowerCase();if(nodeName==='track'){if(!_this.featuresNativeTextTracks){removeNodes.push(node);}else{_this.remoteTextTrackEls().addTrackElement_(node);_this.remoteTextTracks().addTrack(node.track);_this.textTracks().addTrack(node.track);if(!crossoriginTracks&&!_this.el_.hasAttribute('crossorigin')&&isCrossOrigin(node.src)){crossoriginTracks=true;}}}}
for(var i=0;i<removeNodes.length;i++){_this.el_.removeChild(removeNodes[i]);}}
_this.proxyNativeTracks_();if(_this.featuresNativeTextTracks&&crossoriginTracks){log.warn('Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n'+'This may prevent text tracks from loading.');}
_this.restoreMetadataTracksInIOSNativePlayer_();if((TOUCH_ENABLED||IS_IPHONE||IS_NATIVE_ANDROID)&&options.nativeControlsForTouch===true){_this.setControls(true);}
_this.proxyWebkitFullscreen_();_this.triggerReady();return _this;}
var _proto=Html5.prototype;_proto.dispose=function dispose(){if(this.el_&&this.el_.resetSourceset_){this.el_.resetSourceset_();}
Html5.disposeMediaElement(this.el_);this.options_=null;_Tech.prototype.dispose.call(this);};_proto.setupSourcesetHandling_=function setupSourcesetHandling_(){setupSourceset(this);};_proto.restoreMetadataTracksInIOSNativePlayer_=function restoreMetadataTracksInIOSNativePlayer_(){var textTracks=this.textTracks();var metadataTracksPreFullscreenState;var takeMetadataTrackSnapshot=function takeMetadataTrackSnapshot(){metadataTracksPreFullscreenState=[];for(var i=0;i<textTracks.length;i++){var track=textTracks[i];if(track.kind==='metadata'){metadataTracksPreFullscreenState.push({track:track,storedMode:track.mode});}}};takeMetadataTrackSnapshot();textTracks.addEventListener('change',takeMetadataTrackSnapshot);this.on('dispose',function(){return textTracks.removeEventListener('change',takeMetadataTrackSnapshot);});var restoreTrackMode=function restoreTrackMode(){for(var i=0;i<metadataTracksPreFullscreenState.length;i++){var storedTrack=metadataTracksPreFullscreenState[i];if(storedTrack.track.mode==='disabled'&&storedTrack.track.mode!==storedTrack.storedMode){storedTrack.track.mode=storedTrack.storedMode;}}
textTracks.removeEventListener('change',restoreTrackMode);};this.on('webkitbeginfullscreen',function(){textTracks.removeEventListener('change',takeMetadataTrackSnapshot);textTracks.removeEventListener('change',restoreTrackMode);textTracks.addEventListener('change',restoreTrackMode);});this.on('webkitendfullscreen',function(){textTracks.removeEventListener('change',takeMetadataTrackSnapshot);textTracks.addEventListener('change',takeMetadataTrackSnapshot);textTracks.removeEventListener('change',restoreTrackMode);});};_proto.overrideNative_=function overrideNative_(type,override){var _this2=this;if(override!==this["featuresNative"+type+"Tracks"]){return;}
var lowerCaseType=type.toLowerCase();if(this[lowerCaseType+"TracksListeners_"]){Object.keys(this[lowerCaseType+"TracksListeners_"]).forEach(function(eventName){var elTracks=_this2.el()[lowerCaseType+"Tracks"];elTracks.removeEventListener(eventName,_this2[lowerCaseType+"TracksListeners_"][eventName]);});}
this["featuresNative"+type+"Tracks"]=!override;this[lowerCaseType+"TracksListeners_"]=null;this.proxyNativeTracksForType_(lowerCaseType);};_proto.overrideNativeAudioTracks=function overrideNativeAudioTracks(override){this.overrideNative_('Audio',override);};_proto.overrideNativeVideoTracks=function overrideNativeVideoTracks(override){this.overrideNative_('Video',override);};_proto.proxyNativeTracksForType_=function proxyNativeTracksForType_(name){var _this3=this;var props=NORMAL[name];var elTracks=this.el()[props.getterName];var techTracks=this[props.getterName]();if(!this["featuresNative"+props.capitalName+"Tracks"]||!elTracks||!elTracks.addEventListener){return;}
var listeners={change:function change(e){var event={type:'change',target:techTracks,currentTarget:techTracks,srcElement:techTracks};techTracks.trigger(event);if(name==='text'){_this3[REMOTE.remoteText.getterName]().trigger(event);}},addtrack:function addtrack(e){techTracks.addTrack(e.track);},removetrack:function removetrack(e){techTracks.removeTrack(e.track);}};var removeOldTracks=function removeOldTracks(){var removeTracks=[];for(var i=0;i<techTracks.length;i++){var found=false;for(var j=0;j<elTracks.length;j++){if(elTracks[j]===techTracks[i]){found=true;break;}}
if(!found){removeTracks.push(techTracks[i]);}}
while(removeTracks.length){techTracks.removeTrack(removeTracks.shift());}};this[props.getterName+'Listeners_']=listeners;Object.keys(listeners).forEach(function(eventName){var listener=listeners[eventName];elTracks.addEventListener(eventName,listener);_this3.on('dispose',function(e){return elTracks.removeEventListener(eventName,listener);});});this.on('loadstart',removeOldTracks);this.on('dispose',function(e){return _this3.off('loadstart',removeOldTracks);});};_proto.proxyNativeTracks_=function proxyNativeTracks_(){var _this4=this;NORMAL.names.forEach(function(name){_this4.proxyNativeTracksForType_(name);});};_proto.createEl=function createEl(){var el=this.options_.tag;if(!el||!(this.options_.playerElIngest||this.movingMediaElementInDOM)){if(el){var clone=el.cloneNode(true);if(el.parentNode){el.parentNode.insertBefore(clone,el);}
Html5.disposeMediaElement(el);el=clone;}else{el=document_1.createElement('video');var tagAttributes=this.options_.tag&&getAttributes(this.options_.tag);var attributes=mergeOptions({},tagAttributes);if(!TOUCH_ENABLED||this.options_.nativeControlsForTouch!==true){delete attributes.controls;}
setAttributes(el,assign(attributes,{id:this.options_.techId,"class":'vjs-tech'}));}
el.playerId=this.options_.playerId;}
if(typeof this.options_.preload!=='undefined'){setAttribute(el,'preload',this.options_.preload);}
if(this.options_.disablePictureInPicture!==undefined){el.disablePictureInPicture=this.options_.disablePictureInPicture;}
var settingsAttrs=['loop','muted','playsinline','autoplay'];for(var i=0;i<settingsAttrs.length;i++){var attr=settingsAttrs[i];var value=this.options_[attr];if(typeof value!=='undefined'){if(value){setAttribute(el,attr,attr);}else{removeAttribute(el,attr);}
el[attr]=value;}}
return el;};_proto.handleLateInit_=function handleLateInit_(el){if(el.networkState===0||el.networkState===3){return;}
if(el.readyState===0){var loadstartFired=false;var setLoadstartFired=function setLoadstartFired(){loadstartFired=true;};this.on('loadstart',setLoadstartFired);var triggerLoadstart=function triggerLoadstart(){if(!loadstartFired){this.trigger('loadstart');}};this.on('loadedmetadata',triggerLoadstart);this.ready(function(){this.off('loadstart',setLoadstartFired);this.off('loadedmetadata',triggerLoadstart);if(!loadstartFired){this.trigger('loadstart');}});return;}
var eventsToTrigger=['loadstart'];eventsToTrigger.push('loadedmetadata');if(el.readyState>=2){eventsToTrigger.push('loadeddata');}
if(el.readyState>=3){eventsToTrigger.push('canplay');}
if(el.readyState>=4){eventsToTrigger.push('canplaythrough');}
this.ready(function(){eventsToTrigger.forEach(function(type){this.trigger(type);},this);});};_proto.setScrubbing=function setScrubbing(isScrubbing){this.isScrubbing_=isScrubbing;};_proto.scrubbing=function scrubbing(){return this.isScrubbing_;};_proto.setCurrentTime=function setCurrentTime(seconds){try{if(this.isScrubbing_&&this.el_.fastSeek&&IS_ANY_SAFARI){this.el_.fastSeek(seconds);}else{this.el_.currentTime=seconds;}}catch(e){log(e,'Video is not ready. (Video.js)');}};_proto.duration=function duration(){var _this5=this;if(this.el_.duration===Infinity&&IS_ANDROID&&IS_CHROME&&this.el_.currentTime===0){var checkProgress=function checkProgress(){if(_this5.el_.currentTime>0){if(_this5.el_.duration===Infinity){_this5.trigger('durationchange');}
_this5.off('timeupdate',checkProgress);}};this.on('timeupdate',checkProgress);return NaN;}
return this.el_.duration||NaN;};_proto.width=function width(){return this.el_.offsetWidth;};_proto.height=function height(){return this.el_.offsetHeight;};_proto.proxyWebkitFullscreen_=function proxyWebkitFullscreen_(){var _this6=this;if(!('webkitDisplayingFullscreen'in this.el_)){return;}
var endFn=function endFn(){this.trigger('fullscreenchange',{isFullscreen:false});};var beginFn=function beginFn(){if('webkitPresentationMode'in this.el_&&this.el_.webkitPresentationMode!=='picture-in-picture'){this.one('webkitendfullscreen',endFn);this.trigger('fullscreenchange',{isFullscreen:true,nativeIOSFullscreen:true});}};this.on('webkitbeginfullscreen',beginFn);this.on('dispose',function(){_this6.off('webkitbeginfullscreen',beginFn);_this6.off('webkitendfullscreen',endFn);});};_proto.supportsFullScreen=function supportsFullScreen(){if(typeof this.el_.webkitEnterFullScreen==='function'){var userAgent=window_1.navigator&&window_1.navigator.userAgent||'';if(/Android/.test(userAgent)||!/Chrome|Mac OS X 10.5/.test(userAgent)){return true;}}
return false;};_proto.enterFullScreen=function enterFullScreen(){var video=this.el_;if(video.paused&&video.networkState<=video.HAVE_METADATA){silencePromise(this.el_.play());this.setTimeout(function(){video.pause();try{video.webkitEnterFullScreen();}catch(e){this.trigger('fullscreenerror',e);}},0);}else{try{video.webkitEnterFullScreen();}catch(e){this.trigger('fullscreenerror',e);}}};_proto.exitFullScreen=function exitFullScreen(){if(!this.el_.webkitDisplayingFullscreen){this.trigger('fullscreenerror',new Error('The video is not fullscreen'));return;}
this.el_.webkitExitFullScreen();};_proto.requestPictureInPicture=function requestPictureInPicture(){return this.el_.requestPictureInPicture();};_proto.src=function src(_src){if(_src===undefined){return this.el_.src;}
this.setSrc(_src);};_proto.reset=function reset(){Html5.resetMediaElement(this.el_);};_proto.currentSrc=function currentSrc(){if(this.currentSource_){return this.currentSource_.src;}
return this.el_.currentSrc;};_proto.setControls=function setControls(val){this.el_.controls=!!val;};_proto.addTextTrack=function addTextTrack(kind,label,language){if(!this.featuresNativeTextTracks){return _Tech.prototype.addTextTrack.call(this,kind,label,language);}
return this.el_.addTextTrack(kind,label,language);};_proto.createRemoteTextTrack=function createRemoteTextTrack(options){if(!this.featuresNativeTextTracks){return _Tech.prototype.createRemoteTextTrack.call(this,options);}
var htmlTrackElement=document_1.createElement('track');if(options.kind){htmlTrackElement.kind=options.kind;}
if(options.label){htmlTrackElement.label=options.label;}
if(options.language||options.srclang){htmlTrackElement.srclang=options.language||options.srclang;}
if(options["default"]){htmlTrackElement["default"]=options["default"];}
if(options.id){htmlTrackElement.id=options.id;}
if(options.src){htmlTrackElement.src=options.src;}
return htmlTrackElement;};_proto.addRemoteTextTrack=function addRemoteTextTrack(options,manualCleanup){var htmlTrackElement=_Tech.prototype.addRemoteTextTrack.call(this,options,manualCleanup);if(this.featuresNativeTextTracks){this.el().appendChild(htmlTrackElement);}
return htmlTrackElement;};_proto.removeRemoteTextTrack=function removeRemoteTextTrack(track){_Tech.prototype.removeRemoteTextTrack.call(this,track);if(this.featuresNativeTextTracks){var tracks=this.$$('track');var i=tracks.length;while(i--){if(track===tracks[i]||track===tracks[i].track){this.el().removeChild(tracks[i]);}}}};_proto.getVideoPlaybackQuality=function getVideoPlaybackQuality(){if(typeof this.el().getVideoPlaybackQuality==='function'){return this.el().getVideoPlaybackQuality();}
var videoPlaybackQuality={};if(typeof this.el().webkitDroppedFrameCount!=='undefined'&&typeof this.el().webkitDecodedFrameCount!=='undefined'){videoPlaybackQuality.droppedVideoFrames=this.el().webkitDroppedFrameCount;videoPlaybackQuality.totalVideoFrames=this.el().webkitDecodedFrameCount;}
if(window_1.performance&&typeof window_1.performance.now==='function'){videoPlaybackQuality.creationTime=window_1.performance.now();}else if(window_1.performance&&window_1.performance.timing&&typeof window_1.performance.timing.navigationStart==='number'){videoPlaybackQuality.creationTime=window_1.Date.now()-window_1.performance.timing.navigationStart;}
return videoPlaybackQuality;};return Html5;}(Tech);defineLazyProperty(Html5,'TEST_VID',function(){if(!isReal()){return;}
var video=document_1.createElement('video');var track=document_1.createElement('track');track.kind='captions';track.srclang='en';track.label='English';video.appendChild(track);return video;});Html5.isSupported=function(){try{Html5.TEST_VID.volume=0.5;}catch(e){return false;}
return!!(Html5.TEST_VID&&Html5.TEST_VID.canPlayType);};Html5.canPlayType=function(type){return Html5.TEST_VID.canPlayType(type);};Html5.canPlaySource=function(srcObj,options){return Html5.canPlayType(srcObj.type);};Html5.canControlVolume=function(){try{var volume=Html5.TEST_VID.volume;Html5.TEST_VID.volume=volume/2+0.1;return volume!==Html5.TEST_VID.volume;}catch(e){return false;}};Html5.canMuteVolume=function(){try{var muted=Html5.TEST_VID.muted;Html5.TEST_VID.muted=!muted;if(Html5.TEST_VID.muted){setAttribute(Html5.TEST_VID,'muted','muted');}else{removeAttribute(Html5.TEST_VID,'muted','muted');}
return muted!==Html5.TEST_VID.muted;}catch(e){return false;}};Html5.canControlPlaybackRate=function(){if(IS_ANDROID&&IS_CHROME&&CHROME_VERSION<58){return false;}
try{var playbackRate=Html5.TEST_VID.playbackRate;Html5.TEST_VID.playbackRate=playbackRate/2+0.1;return playbackRate!==Html5.TEST_VID.playbackRate;}catch(e){return false;}};Html5.canOverrideAttributes=function(){try{var noop=function noop(){};Object.defineProperty(document_1.createElement('video'),'src',{get:noop,set:noop});Object.defineProperty(document_1.createElement('audio'),'src',{get:noop,set:noop});Object.defineProperty(document_1.createElement('video'),'innerHTML',{get:noop,set:noop});Object.defineProperty(document_1.createElement('audio'),'innerHTML',{get:noop,set:noop});}catch(e){return false;}
return true;};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'];[['featuresVolumeControl','canControlVolume'],['featuresMuteControl','canMuteVolume'],['featuresPlaybackRate','canControlPlaybackRate'],['featuresSourceset','canOverrideAttributes'],['featuresNativeTextTracks','supportsNativeTextTracks'],['featuresNativeVideoTracks','supportsNativeVideoTracks'],['featuresNativeAudioTracks','supportsNativeAudioTracks']].forEach(function(_ref){var key=_ref[0],fn=_ref[1];defineLazyProperty(Html5.prototype,key,function(){return Html5[fn]();},true);});Html5.prototype.movingMediaElementInDOM=!IS_IOS;Html5.prototype.featuresFullscreenResize=true;Html5.prototype.featuresProgressEvents=true;Html5.prototype.featuresTimeupdateEvents=true;var canPlayType;Html5.patchCanPlayType=function(){if(ANDROID_VERSION>=4.0&&!IS_FIREFOX&&!IS_CHROME){canPlayType=Html5.TEST_VID&&Html5.TEST_VID.constructor.prototype.canPlayType;Html5.TEST_VID.constructor.prototype.canPlayType=function(type){var mpegurlRE=/^application\/(?:x-|vnd\.apple\.)mpegurl/i;if(type&&mpegurlRE.test(type)){return'maybe';}
return canPlayType.call(this,type);};}};Html5.unpatchCanPlayType=function(){var r=Html5.TEST_VID.constructor.prototype.canPlayType;if(canPlayType){Html5.TEST_VID.constructor.prototype.canPlayType=canPlayType;}
return r;};Html5.patchCanPlayType();Html5.disposeMediaElement=function(el){if(!el){return;}
if(el.parentNode){el.parentNode.removeChild(el);}
while(el.hasChildNodes()){el.removeChild(el.firstChild);}
el.removeAttribute('src');if(typeof el.load==='function'){(function(){try{el.load();}catch(e){}})();}};Html5.resetMediaElement=function(el){if(!el){return;}
var sources=el.querySelectorAll('source');var i=sources.length;while(i--){el.removeChild(sources[i]);}
el.removeAttribute('src');if(typeof el.load==='function'){(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(prop)]=function(v){this.el_[prop]=v;if(v){this.el_.setAttribute(prop,prop);}else{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(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);}else if(source.src){var ext=getFileExtension(source.src);return Html5.nativeSourceHandler.canPlayType("video/"+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);var TECH_EVENTS_RETRIGGER=['progress','abort','suspend','emptied','stalled','loadedmetadata','loadeddata','timeupdate','resize','volumechange','texttrackchange'];var TECH_EVENTS_QUEUE={canplay:'CanPlay',canplaythrough:'CanPlayThrough',playing:'Playing',seeked:'Seeked'};var BREAKPOINT_ORDER=['tiny','xsmall','small','medium','large','xlarge','huge'];var BREAKPOINT_CLASSES={};BREAKPOINT_ORDER.forEach(function(k){var v=k.charAt(0)==='x'?"x-"+k.substring(1):k;BREAKPOINT_CLASSES[k]="vjs-layout-"+v;});var DEFAULT_BREAKPOINTS={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:Infinity};var Player=function(_Component){inheritsLoose(Player,_Component);function Player(tag,options,ready){var _this;tag.id=tag.id||options.id||"vjs_video_"+newGUID();options=assign(Player.getTagSettings(tag),options);options.initChildren=false;options.createEl=false;options.evented=false;options.reportTouchActivity=false;if(!options.language){if(typeof tag.closest==='function'){var closest=tag.closest('[lang]');if(closest&&closest.getAttribute){options.language=closest.getAttribute('lang');}}else{var element=tag;while(element&&element.nodeType===1){if(getAttributes(element).hasOwnProperty('lang')){options.language=element.getAttribute('lang');break;}
element=element.parentNode;}}}
_this=_Component.call(this,null,options,ready)||this;_this.boundDocumentFullscreenChange_=function(e){return _this.documentFullscreenChange_(e);};_this.boundFullWindowOnEscKey_=function(e){return _this.fullWindowOnEscKey(e);};_this.isFullscreen_=false;_this.log=createLogger$1(_this.id_);_this.fsApi_=FullscreenApi;_this.isPosterFromTech_=false;_this.queuedCallbacks_=[];_this.isReady_=false;_this.hasStarted_=false;_this.userActive_=false;_this.debugEnabled_=false;if(!_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?');}
_this.tag=tag;_this.tagAttributes=tag&&getAttributes(tag);_this.language(_this.options_.language);if(options.languages){var 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=false;tag.removeAttribute('controls');_this.changingSrc_=false;_this.playCallbacks_=[];_this.playTerminatedQueue_=[];if(tag.hasAttribute('autoplay')){_this.autoplay(true);}else{_this.autoplay(_this.options_.autoplay);}
if(options.plugins){Object.keys(options.plugins).forEach(function(name){if(typeof _this[name]!=='function'){throw new Error("plugin \""+name+"\" does not exist");}});}
_this.scrubbing_=false;_this.el_=_this.createEl();evented(assertThisInitialized(_this),{eventBusKey:'el_'});if(_this.fsApi_.requestFullscreen){on(document_1,_this.fsApi_.fullscreenchange,_this.boundDocumentFullscreenChange_);_this.on(_this.fsApi_.fullscreenchange,_this.boundDocumentFullscreenChange_);}
if(_this.fluid_){_this.on(['playerreset','resize'],_this.updateStyleEl_);}
var playerOptionsCopy=mergeOptions(_this.options_);if(options.plugins){Object.keys(options.plugins).forEach(function(name){_this[name](options.plugins[name]);});}
if(options.debug){_this.debug(true);}
_this.options_.playerOptions=playerOptionsCopy;_this.middleware_=[];_this.initChildren();_this.isAudio(tag.nodeName.toLowerCase()==='audio');if(_this.controls()){_this.addClass('vjs-controls-enabled');}else{_this.addClass('vjs-controls-disabled');}
_this.el_.setAttribute('role','region');if(_this.isAudio()){_this.el_.setAttribute('aria-label',_this.localize('Audio Player'));}else{_this.el_.setAttribute('aria-label',_this.localize('Video Player'));}
if(_this.isAudio()){_this.addClass('vjs-audio');}
if(_this.flexNotSupported_()){_this.addClass('vjs-no-flex');}
if(TOUCH_ENABLED){_this.addClass('vjs-touch-enabled');}
if(!IS_IOS){_this.addClass('vjs-workinghover');}
Player.players[_this.id_]=assertThisInitialized(_this);var majorVersion=version.split('.')[0];_this.addClass("vjs-v"+majorVersion);_this.userActive(true);_this.reportUserActivity();_this.one('play',_this.listenForUserActivity_);_this.on('stageclick',_this.handleStageClick_);_this.on('keydown',_this.handleKeyDown);_this.on('languagechange',_this.handleLanguagechange);_this.breakpoints(_this.options_.breakpoints);_this.responsive(_this.options_.responsive);return _this;}
var _proto=Player.prototype;_proto.dispose=function dispose(){var _this2=this;this.trigger('dispose');this.off('dispose');off(document_1,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_);off(document_1,'keydown',this.boundFullWindowOnEscKey_);if(this.styleEl_&&this.styleEl_.parentNode){this.styleEl_.parentNode.removeChild(this.styleEl_);this.styleEl_=null;}
Player.players[this.id_]=null;if(this.tag&&this.tag.player){this.tag.player=null;}
if(this.el_&&this.el_.player){this.el_.player=null;}
if(this.tech_){this.tech_.dispose();this.isPosterFromTech_=false;this.poster_='';}
if(this.playerElIngest_){this.playerElIngest_=null;}
if(this.tag){this.tag=null;}
clearCacheForPlayer(this);ALL.names.forEach(function(name){var props=ALL[name];var list=_this2[props.getterName]();if(list&&list.off){list.off();}});_Component.prototype.dispose.call(this);};_proto.createEl=function createEl(){var tag=this.tag;var el;var playerElIngest=this.playerElIngest_=tag.parentNode&&tag.parentNode.hasAttribute&&tag.parentNode.hasAttribute('data-vjs-player');var divEmbed=this.tag.tagName.toLowerCase()==='video-js';if(playerElIngest){el=this.el_=tag.parentNode;}else if(!divEmbed){el=this.el_=_Component.prototype.createEl.call(this,'div');}
var attrs=getAttributes(tag);if(divEmbed){el=this.el_=tag;tag=this.tag=document_1.createElement('video');while(el.children.length){tag.appendChild(el.firstChild);}
if(!hasClass(el,'video-js')){addClass(el,'video-js');}
el.appendChild(tag);playerElIngest=this.playerElIngest_=el;Object.keys(el).forEach(function(k){try{tag[k]=el[k];}catch(e){}});}
tag.setAttribute('tabindex','-1');attrs.tabindex='-1';if(IE_VERSION||IS_CHROME&&IS_WINDOWS){tag.setAttribute('role','application');attrs.role='application';}
tag.removeAttribute('width');tag.removeAttribute('height');if('width'in attrs){delete attrs.width;}
if('height'in attrs){delete attrs.height;}
Object.getOwnPropertyNames(attrs).forEach(function(attr){if(!(divEmbed&&attr==='class')){el.setAttribute(attr,attrs[attr]);}
if(divEmbed){tag.setAttribute(attr,attrs[attr]);}});tag.playerId=tag.id;tag.id+='_html5_api';tag.className='vjs-tech';tag.player=el.player=this;this.addClass('vjs-paused');if(window_1.VIDEOJS_NO_DYNAMIC_STYLE!==true){this.styleEl_=createStyleElement('vjs-styles-dimensions');var defaultsStyleEl=$('.vjs-styles-defaults');var head=$('head');head.insertBefore(this.styleEl_,defaultsStyleEl?defaultsStyleEl.nextSibling:head.firstChild);}
this.fill_=false;this.fluid_=false;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);var links=tag.getElementsByTagName('a');for(var i=0;i<links.length;i++){var linkEl=links.item(i);addClass(linkEl,'vjs-hidden');linkEl.setAttribute('hidden','hidden');}
tag.initNetworkState_=tag.networkState;if(tag.parentNode&&!playerElIngest){tag.parentNode.insertBefore(el,tag);}
prependTo(tag,el);this.children_.unshift(tag);this.el_.setAttribute('lang',this.language_);this.el_=el;return el;};_proto.crossOrigin=function crossOrigin(value){if(!value){return this.techGet_('crossOrigin');}
if(value!=='anonymous'&&value!=='use-credentials'){log.warn("crossOrigin must be \"anonymous\" or \"use-credentials\", given \""+value+"\"");return;}
this.techCall_('setCrossOrigin',value);return;};_proto.width=function width(value){return this.dimension('width',value);};_proto.height=function height(value){return this.dimension('height',value);};_proto.dimension=function dimension(_dimension,value){var privDimension=_dimension+'_';if(value===undefined){return this[privDimension]||0;}
if(value===''||value==='auto'){this[privDimension]=undefined;this.updateStyleEl_();return;}
var parsedVal=parseFloat(value);if(isNaN(parsedVal)){log.error("Improper value \""+value+"\" supplied for for "+_dimension);return;}
this[privDimension]=parsedVal;this.updateStyleEl_();};_proto.fluid=function fluid(bool){var _this3=this;if(bool===undefined){return!!this.fluid_;}
this.fluid_=!!bool;if(isEvented(this)){this.off(['playerreset','resize'],this.updateStyleEl_);}
if(bool){this.addClass('vjs-fluid');this.fill(false);addEventedCallback(this,function(){_this3.on(['playerreset','resize'],_this3.updateStyleEl_);});}else{this.removeClass('vjs-fluid');}
this.updateStyleEl_();};_proto.fill=function fill(bool){if(bool===undefined){return!!this.fill_;}
this.fill_=!!bool;if(bool){this.addClass('vjs-fill');this.fluid(false);}else{this.removeClass('vjs-fill');}};_proto.aspectRatio=function aspectRatio(ratio){if(ratio===undefined){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(true);this.updateStyleEl_();};_proto.updateStyleEl_=function updateStyleEl_(){if(window_1.VIDEOJS_NO_DYNAMIC_STYLE===true){var _width=typeof this.width_==='number'?this.width_:this.options_.width;var _height=typeof this.height_==='number'?this.height_:this.options_.height;var techEl=this.tech_&&this.tech_.el();if(techEl){if(_width>=0){techEl.width=_width;}
if(_height>=0){techEl.height=_height;}}
return;}
var width;var height;var aspectRatio;var idClass;if(this.aspectRatio_!==undefined&&this.aspectRatio_!=='auto'){aspectRatio=this.aspectRatio_;}else if(this.videoWidth()>0){aspectRatio=this.videoWidth()+':'+this.videoHeight();}else{aspectRatio='16:9';}
var ratioParts=aspectRatio.split(':');var ratioMultiplier=ratioParts[1]/ratioParts[0];if(this.width_!==undefined){width=this.width_;}else if(this.height_!==undefined){width=this.height_/ratioMultiplier;}else{width=this.videoWidth()||300;}
if(this.height_!==undefined){height=this.height_;}else{height=width*ratioMultiplier;}
if(/^[^a-zA-Z]/.test(this.id())){idClass='dimensions-'+this.id();}else{idClass=this.id()+'-dimensions';}
this.addClass(idClass);setTextContent(this.styleEl_,"\n      ."+idClass+" {\n        width: "+width+"px;\n        height: "+height+"px;\n      }\n\n      ."+idClass+".vjs-fluid {\n        padding-top: "+ratioMultiplier*100+"%;\n      }\n    ");};_proto.loadTech_=function loadTech_(techName,source){var _this4=this;if(this.tech_){this.unloadTech_();}
var titleTechName=toTitleCase(techName);var camelTechName=techName.charAt(0).toLowerCase()+techName.slice(1);if(titleTechName!=='Html5'&&this.tag){Tech.getTech('Html5').disposeMediaElement(this.tag);this.tag.player=null;this.tag=null;}
this.techName_=titleTechName;this.isReady_=false;var autoplay=typeof this.autoplay()==='string'?false:this.autoplay();var techOptions={source:source,autoplay:autoplay,'nativeControlsForTouch':this.options_.nativeControlsForTouch,'playerId':this.id(),'techId':this.id()+"_"+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_||false,'vtt.js':this.options_['vtt.js'],'canOverridePoster':!!this.options_.techCanOverridePoster,'enableSourceset':this.options_.enableSourceset,'Promise':this.options_.Promise};ALL.names.forEach(function(name){var props=ALL[name];techOptions[props.getterName]=_this4[props.privateName];});assign(techOptions,this.options_[titleTechName]);assign(techOptions,this.options_[camelTechName]);assign(techOptions,this.options_[techName.toLowerCase()]);if(this.tag){techOptions.tag=this.tag;}
if(source&&source.src===this.cache_.src&&this.cache_.currentTime>0){techOptions.startTime=this.cache_.currentTime;}
var TechClass=Tech.getTech(techName);if(!TechClass){throw new Error("No Tech named '"+titleTechName+"' exists! '"+titleTechName+"' should be registered using videojs.registerTech()'");}
this.tech_=new TechClass(techOptions);this.tech_.ready(bind(this,this.handleTechReady_),true);textTrackConverter.jsonToTextTracks(this.textTracksJson_||[],this.tech_);TECH_EVENTS_RETRIGGER.forEach(function(event){_this4.on(_this4.tech_,event,_this4["handleTech"+toTitleCase(event)+"_"]);});Object.keys(TECH_EVENTS_QUEUE).forEach(function(event){_this4.on(_this4.tech_,event,function(eventObj){if(_this4.tech_.playbackRate()===0&&_this4.tech_.seeking()){_this4.queuedCallbacks_.push({callback:_this4["handleTech"+TECH_EVENTS_QUEUE[event]+"_"].bind(_this4),event:eventObj});return;}
_this4["handleTech"+TECH_EVENTS_QUEUE[event]+"_"](eventObj);});});this.on(this.tech_,'loadstart',this.handleTechLoadStart_);this.on(this.tech_,'sourceset',this.handleTechSourceset_);this.on(this.tech_,'waiting',this.handleTechWaiting_);this.on(this.tech_,'ended',this.handleTechEnded_);this.on(this.tech_,'seeking',this.handleTechSeeking_);this.on(this.tech_,'play',this.handleTechPlay_);this.on(this.tech_,'firstplay',this.handleTechFirstPlay_);this.on(this.tech_,'pause',this.handleTechPause_);this.on(this.tech_,'durationchange',this.handleTechDurationChange_);this.on(this.tech_,'fullscreenchange',this.handleTechFullscreenChange_);this.on(this.tech_,'fullscreenerror',this.handleTechFullscreenError_);this.on(this.tech_,'enterpictureinpicture',this.handleTechEnterPictureInPicture_);this.on(this.tech_,'leavepictureinpicture',this.handleTechLeavePictureInPicture_);this.on(this.tech_,'error',this.handleTechError_);this.on(this.tech_,'loadedmetadata',this.updateStyleEl_);this.on(this.tech_,'posterchange',this.handleTechPosterChange_);this.on(this.tech_,'textdata',this.handleTechTextData_);this.on(this.tech_,'ratechange',this.handleTechRateChange_);this.usingNativeControls(this.techGet_('controls'));if(this.controls()&&!this.usingNativeControls()){this.addTechControlsListeners_();}
if(this.tech_.el().parentNode!==this.el()&&(titleTechName!=='Html5'||!this.tag)){prependTo(this.tech_.el(),this.el());}
if(this.tag){this.tag.player=null;this.tag=null;}};_proto.unloadTech_=function unloadTech_(){var _this5=this;ALL.names.forEach(function(name){var props=ALL[name];_this5[props.privateName]=_this5[props.getterName]();});this.textTracksJson_=textTrackConverter.textTracksToJson(this.tech_);this.isReady_=false;this.tech_.dispose();this.tech_=false;if(this.isPosterFromTech_){this.poster_='';this.trigger('posterchange');}
this.isPosterFromTech_=false;};_proto.tech=function tech(safety){if(safety===undefined){log.warn('Using the tech directly can be dangerous. I hope you know what you\'re doing.\n'+'See https://github.com/videojs/video.js/issues/2617 for more info.\n');}
return this.tech_;};_proto.addTechControlsListeners_=function addTechControlsListeners_(){this.removeTechControlsListeners_();this.on(this.tech_,'mouseup',this.handleTechClick_);this.on(this.tech_,'dblclick',this.handleTechDoubleClick_);this.on(this.tech_,'touchstart',this.handleTechTouchStart_);this.on(this.tech_,'touchmove',this.handleTechTouchMove_);this.on(this.tech_,'touchend',this.handleTechTouchEnd_);this.on(this.tech_,'tap',this.handleTechTap_);};_proto.removeTechControlsListeners_=function removeTechControlsListeners_(){this.off(this.tech_,'tap',this.handleTechTap_);this.off(this.tech_,'touchstart',this.handleTechTouchStart_);this.off(this.tech_,'touchmove',this.handleTechTouchMove_);this.off(this.tech_,'touchend',this.handleTechTouchEnd_);this.off(this.tech_,'mouseup',this.handleTechClick_);this.off(this.tech_,'dblclick',this.handleTechDoubleClick_);};_proto.handleTechReady_=function handleTechReady_(){this.triggerReady();if(this.cache_.volume){this.techCall_('setVolume',this.cache_.volume);}
this.handleTechPosterChange_();this.handleTechDurationChange_();};_proto.handleTechLoadStart_=function handleTechLoadStart_(){this.removeClass('vjs-ended');this.removeClass('vjs-seeking');this.error(null);this.handleTechDurationChange_();if(!this.paused()){this.trigger('loadstart');this.trigger('firstplay');}else{this.hasStarted(false);this.trigger('loadstart');}
this.manualAutoplay_(this.autoplay());};_proto.manualAutoplay_=function manualAutoplay_(type){var _this6=this;if(!this.tech_||typeof type!=='string'){return;}
var muted=function muted(){var previouslyMuted=_this6.muted();_this6.muted(true);var restoreMuted=function restoreMuted(){_this6.muted(previouslyMuted);};_this6.playTerminatedQueue_.push(restoreMuted);var mutedPromise=_this6.play();if(!isPromise(mutedPromise)){return;}
return mutedPromise["catch"](restoreMuted);};var promise;if(type==='any'&&this.muted()!==true){promise=this.play();if(isPromise(promise)){promise=promise["catch"](muted);}}else if(type==='muted'&&this.muted()!==true){promise=muted();}else{promise=this.play();}
if(!isPromise(promise)){return;}
return promise.then(function(){_this6.trigger({type:'autoplay-success',autoplay:type});})["catch"](function(e){_this6.trigger({type:'autoplay-failure',autoplay:type});});};_proto.updateSourceCaches_=function updateSourceCaches_(srcObj){if(srcObj===void 0){srcObj='';}
var src=srcObj;var type='';if(typeof src!=='string'){src=srcObj.src;type=srcObj.type;}
this.cache_.source=this.cache_.source||{};this.cache_.sources=this.cache_.sources||[];if(src&&!type){type=findMimetype(this,src);}
this.cache_.source=mergeOptions({},srcObj,{src:src,type:type});var matchingSources=this.cache_.sources.filter(function(s){return s.src&&s.src===src;});var sourceElSources=[];var sourceEls=this.$$('source');var matchingSourceEls=[];for(var i=0;i<sourceEls.length;i++){var sourceObj=getAttributes(sourceEls[i]);sourceElSources.push(sourceObj);if(sourceObj.src&&sourceObj.src===src){matchingSourceEls.push(sourceObj.src);}}
if(matchingSourceEls.length&&!matchingSources.length){this.cache_.sources=sourceElSources;}else if(!matchingSources.length){this.cache_.sources=[this.cache_.source];}
this.cache_.src=src;};_proto.handleTechSourceset_=function handleTechSourceset_(event){var _this7=this;if(!this.changingSrc_){var updateSourceCaches=function updateSourceCaches(src){return _this7.updateSourceCaches_(src);};var playerSrc=this.currentSource().src;var eventSrc=event.src;if(playerSrc&&!/^blob:/.test(playerSrc)&&/^blob:/.test(eventSrc)){if(!this.lastSource_||this.lastSource_.tech!==eventSrc&&this.lastSource_.player!==playerSrc){updateSourceCaches=function updateSourceCaches(){};}}
updateSourceCaches(eventSrc);if(!event.src){this.tech_.any(['sourceset','loadstart'],function(e){if(e.type==='sourceset'){return;}
var techSrc=_this7.techGet('currentSrc');_this7.lastSource_.tech=techSrc;_this7.updateSourceCaches_(techSrc);});}}
this.lastSource_={player:this.currentSource().src,tech:event.src};this.trigger({src:event.src,type:'sourceset'});};_proto.hasStarted=function hasStarted(request){if(request===undefined){return this.hasStarted_;}
if(request===this.hasStarted_){return;}
this.hasStarted_=request;if(this.hasStarted_){this.addClass('vjs-has-started');this.trigger('firstplay');}else{this.removeClass('vjs-has-started');}};_proto.handleTechPlay_=function handleTechPlay_(){this.removeClass('vjs-ended');this.removeClass('vjs-paused');this.addClass('vjs-playing');this.hasStarted(true);this.trigger('play');};_proto.handleTechRateChange_=function handleTechRateChange_(){if(this.tech_.playbackRate()>0&&this.cache_.lastPlaybackRate===0){this.queuedCallbacks_.forEach(function(queued){return queued.callback(queued.event);});this.queuedCallbacks_=[];}
this.cache_.lastPlaybackRate=this.tech_.playbackRate();this.trigger('ratechange');};_proto.handleTechWaiting_=function handleTechWaiting_(){var _this8=this;this.addClass('vjs-waiting');this.trigger('waiting');var timeWhenWaiting=this.currentTime();var timeUpdateListener=function timeUpdateListener(){if(timeWhenWaiting!==_this8.currentTime()){_this8.removeClass('vjs-waiting');_this8.off('timeupdate',timeUpdateListener);}};this.on('timeupdate',timeUpdateListener);};_proto.handleTechCanPlay_=function handleTechCanPlay_(){this.removeClass('vjs-waiting');this.trigger('canplay');};_proto.handleTechCanPlayThrough_=function handleTechCanPlayThrough_(){this.removeClass('vjs-waiting');this.trigger('canplaythrough');};_proto.handleTechPlaying_=function handleTechPlaying_(){this.removeClass('vjs-waiting');this.trigger('playing');};_proto.handleTechSeeking_=function handleTechSeeking_(){this.addClass('vjs-seeking');this.trigger('seeking');};_proto.handleTechSeeked_=function handleTechSeeked_(){this.removeClass('vjs-seeking');this.removeClass('vjs-ended');this.trigger('seeked');};_proto.handleTechFirstPlay_=function handleTechFirstPlay_(){if(this.options_.starttime){log.warn('Passing the `starttime` option to the player will be deprecated in 6.0');this.currentTime(this.options_.starttime);}
this.addClass('vjs-has-started');this.trigger('firstplay');};_proto.handleTechPause_=function handleTechPause_(){this.removeClass('vjs-playing');this.addClass('vjs-paused');this.trigger('pause');};_proto.handleTechEnded_=function handleTechEnded_(){this.addClass('vjs-ended');if(this.options_.loop){this.currentTime(0);this.play();}else if(!this.paused()){this.pause();}
this.trigger('ended');};_proto.handleTechDurationChange_=function handleTechDurationChange_(){this.duration(this.techGet_('duration'));};_proto.handleTechClick_=function handleTechClick_(event){if(!isSingleLeftClick(event)){return;}
if(!this.controls_){return;}
if(this.paused()){silencePromise(this.play());}else{this.pause();}};_proto.handleTechDoubleClick_=function handleTechDoubleClick_(event){if(!this.controls_){return;}
var inAllowedEls=Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'),function(el){return el.contains(event.target);});if(!inAllowedEls){if(this.options_===undefined||this.options_.userActions===undefined||this.options_.userActions.doubleClick===undefined||this.options_.userActions.doubleClick!==false){if(this.options_!==undefined&&this.options_.userActions!==undefined&&typeof this.options_.userActions.doubleClick==='function'){this.options_.userActions.doubleClick.call(this,event);}else if(this.isFullscreen()){this.exitFullscreen();}else{this.requestFullscreen();}}}};_proto.handleTechTap_=function handleTechTap_(){this.userActive(!this.userActive());};_proto.handleTechTouchStart_=function handleTechTouchStart_(){this.userWasActive=this.userActive();};_proto.handleTechTouchMove_=function handleTechTouchMove_(){if(this.userWasActive){this.reportUserActivity();}};_proto.handleTechTouchEnd_=function handleTechTouchEnd_(event){if(event.cancelable){event.preventDefault();}};_proto.handleStageClick_=function handleStageClick_(){this.reportUserActivity();};_proto.toggleFullscreenClass_=function toggleFullscreenClass_(){if(this.isFullscreen()){this.addClass('vjs-fullscreen');}else{this.removeClass('vjs-fullscreen');}};_proto.documentFullscreenChange_=function documentFullscreenChange_(e){var targetPlayer=e.target.player;if(targetPlayer&&targetPlayer!==this){return;}
var el=this.el();var isFs=document_1[this.fsApi_.fullscreenElement]===el;if(!isFs&&el.matches){isFs=el.matches(':'+this.fsApi_.fullscreen);}else if(!isFs&&el.msMatchesSelector){isFs=el.msMatchesSelector(':'+this.fsApi_.fullscreen);}
this.isFullscreen(isFs);};_proto.handleTechFullscreenChange_=function handleTechFullscreenChange_(event,data){if(data){if(data.nativeIOSFullscreen){this.toggleClass('vjs-ios-native-fs');}
this.isFullscreen(data.isFullscreen);}};_proto.handleTechFullscreenError_=function handleTechFullscreenError_(event,err){this.trigger('fullscreenerror',err);};_proto.togglePictureInPictureClass_=function togglePictureInPictureClass_(){if(this.isInPictureInPicture()){this.addClass('vjs-picture-in-picture');}else{this.removeClass('vjs-picture-in-picture');}};_proto.handleTechEnterPictureInPicture_=function handleTechEnterPictureInPicture_(event){this.isInPictureInPicture(true);};_proto.handleTechLeavePictureInPicture_=function handleTechLeavePictureInPicture_(event){this.isInPictureInPicture(false);};_proto.handleTechError_=function handleTechError_(){var error=this.tech_.error();this.error(error);};_proto.handleTechTextData_=function handleTechTextData_(){var data=null;if(arguments.length>1){data=arguments[1];}
this.trigger('textdata',data);};_proto.getCache=function getCache(){return this.cache_;};_proto.resetCache_=function resetCache_(){this.cache_={currentTime:0,initTime:0,inactivityTimeout:this.options_.inactivityTimeout,duration:NaN,lastVolume:1,lastPlaybackRate:this.defaultPlaybackRate(),media:null,src:'',source:{},sources:[],volume:1};};_proto.techCall_=function techCall_(method,arg){this.ready(function(){if(method in allowedSetters){return set(this.middleware_,this.tech_,method,arg);}else if(method in allowedMediators){return mediate(this.middleware_,this.tech_,method,arg);}
try{if(this.tech_){this.tech_[method](arg);}}catch(e){log(e);throw e;}},true);};_proto.techGet_=function techGet_(method){if(!this.tech_||!this.tech_.isReady_){return;}
if(method in allowedGetters){return get(this.middleware_,this.tech_,method);}else if(method in allowedMediators){return mediate(this.middleware_,this.tech_,method);}
try{return this.tech_[method]();}catch(e){if(this.tech_[method]===undefined){log("Video.js: "+method+" method not defined for "+this.techName_+" playback technology.",e);throw e;}
if(e.name==='TypeError'){log("Video.js: "+method+" unavailable on "+this.techName_+" playback technology element.",e);this.tech_.isReady_=false;throw e;}
log(e);throw e;}};_proto.play=function play(){var _this9=this;var PromiseClass=this.options_.Promise||window_1.Promise;if(PromiseClass){return new PromiseClass(function(resolve){_this9.play_(resolve);});}
return this.play_();};_proto.play_=function play_(callback){var _this10=this;if(callback===void 0){callback=silencePromise;}
this.playCallbacks_.push(callback);var isSrcReady=Boolean(!this.changingSrc_&&(this.src()||this.currentSrc()));if(this.waitToPlay_){this.off(['ready','loadstart'],this.waitToPlay_);this.waitToPlay_=null;}
if(!this.isReady_||!isSrcReady){this.waitToPlay_=function(e){_this10.play_();};this.one(['ready','loadstart'],this.waitToPlay_);if(!isSrcReady&&(IS_ANY_SAFARI||IS_IOS)){this.load();}
return;}
var val=this.techGet_('play');if(val===null){this.runPlayTerminatedQueue_();}else{this.runPlayCallbacks_(val);}};_proto.runPlayTerminatedQueue_=function runPlayTerminatedQueue_(){var queue=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[];queue.forEach(function(q){q();});};_proto.runPlayCallbacks_=function runPlayCallbacks_(val){var callbacks=this.playCallbacks_.slice(0);this.playCallbacks_=[];this.playTerminatedQueue_=[];callbacks.forEach(function(cb){cb(val);});};_proto.pause=function pause(){this.techCall_('pause');};_proto.paused=function paused(){return this.techGet_('paused')===false?false:true;};_proto.played=function played(){return this.techGet_('played')||createTimeRanges(0,0);};_proto.scrubbing=function scrubbing(isScrubbing){if(typeof isScrubbing==='undefined'){return this.scrubbing_;}
this.scrubbing_=!!isScrubbing;this.techCall_('setScrubbing',this.scrubbing_);if(isScrubbing){this.addClass('vjs-scrubbing');}else{this.removeClass('vjs-scrubbing');}};_proto.currentTime=function currentTime(seconds){if(typeof seconds!=='undefined'){if(seconds<0){seconds=0;}
if(!this.isReady_||this.changingSrc_||!this.tech_||!this.tech_.isReady_){this.cache_.initTime=seconds;this.off('canplay',this.applyInitTime_);this.one('canplay',this.applyInitTime_);return;}
this.techCall_('setCurrentTime',seconds);this.cache_.initTime=0;return;}
this.cache_.currentTime=this.techGet_('currentTime')||0;return this.cache_.currentTime;};_proto.applyInitTime_=function applyInitTime_(){this.currentTime(this.cache_.initTime);};_proto.duration=function duration(seconds){if(seconds===undefined){return this.cache_.duration!==undefined?this.cache_.duration:NaN;}
seconds=parseFloat(seconds);if(seconds<0){seconds=Infinity;}
if(seconds!==this.cache_.duration){this.cache_.duration=seconds;if(seconds===Infinity){this.addClass('vjs-live');}else{this.removeClass('vjs-live');}
if(!isNaN(seconds)){this.trigger('durationchange');}}};_proto.remainingTime=function remainingTime(){return this.duration()-this.currentTime();};_proto.remainingTimeDisplay=function remainingTimeDisplay(){return Math.floor(this.duration())-Math.floor(this.currentTime());};_proto.buffered=function buffered(){var buffered=this.techGet_('buffered');if(!buffered||!buffered.length){buffered=createTimeRanges(0,0);}
return buffered;};_proto.bufferedPercent=function bufferedPercent$1(){return bufferedPercent(this.buffered(),this.duration());};_proto.bufferedEnd=function bufferedEnd(){var buffered=this.buffered();var duration=this.duration();var end=buffered.end(buffered.length-1);if(end>duration){end=duration;}
return end;};_proto.volume=function volume(percentAsDecimal){var vol;if(percentAsDecimal!==undefined){vol=Math.max(0,Math.min(1,parseFloat(percentAsDecimal)));this.cache_.volume=vol;this.techCall_('setVolume',vol);if(vol>0){this.lastVolume_(vol);}
return;}
vol=parseFloat(this.techGet_('volume'));return isNaN(vol)?1:vol;};_proto.muted=function muted(_muted){if(_muted!==undefined){this.techCall_('setMuted',_muted);return;}
return this.techGet_('muted')||false;};_proto.defaultMuted=function defaultMuted(_defaultMuted){if(_defaultMuted!==undefined){return this.techCall_('setDefaultMuted',_defaultMuted);}
return this.techGet_('defaultMuted')||false;};_proto.lastVolume_=function lastVolume_(percentAsDecimal){if(percentAsDecimal!==undefined&&percentAsDecimal!==0){this.cache_.lastVolume=percentAsDecimal;return;}
return this.cache_.lastVolume;};_proto.supportsFullScreen=function supportsFullScreen(){return this.techGet_('supportsFullScreen')||false;};_proto.isFullscreen=function isFullscreen(isFS){if(isFS!==undefined){var oldValue=this.isFullscreen_;this.isFullscreen_=Boolean(isFS);if(this.isFullscreen_!==oldValue&&this.fsApi_.prefixed){this.trigger('fullscreenchange');}
this.toggleFullscreenClass_();return;}
return this.isFullscreen_;};_proto.requestFullscreen=function requestFullscreen(fullscreenOptions){var PromiseClass=this.options_.Promise||window_1.Promise;if(PromiseClass){var self=this;return new PromiseClass(function(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);var promise=self.requestFullscreenHelper_(fullscreenOptions);if(promise){promise.then(offHandler,offHandler);return promise;}});}
return this.requestFullscreenHelper_();};_proto.requestFullscreenHelper_=function requestFullscreenHelper_(fullscreenOptions){var _this11=this;var fsOptions;if(!this.fsApi_.prefixed){fsOptions=this.options_.fullscreen&&this.options_.fullscreen.options||{};if(fullscreenOptions!==undefined){fsOptions=fullscreenOptions;}}
if(this.fsApi_.requestFullscreen){var promise=this.el_[this.fsApi_.requestFullscreen](fsOptions);if(promise){promise.then(function(){return _this11.isFullscreen(true);},function(){return _this11.isFullscreen(false);});}
return promise;}else if(this.tech_.supportsFullScreen()){this.techCall_('enterFullScreen');}else{this.enterFullWindow();}};_proto.exitFullscreen=function exitFullscreen(){var PromiseClass=this.options_.Promise||window_1.Promise;if(PromiseClass){var self=this;return new PromiseClass(function(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);var promise=self.exitFullscreenHelper_();if(promise){promise.then(offHandler,offHandler);return promise;}});}
return this.exitFullscreenHelper_();};_proto.exitFullscreenHelper_=function exitFullscreenHelper_(){var _this12=this;if(this.fsApi_.requestFullscreen){var promise=document_1[this.fsApi_.exitFullscreen]();if(promise){promise.then(function(){return _this12.isFullscreen(false);});}
return promise;}else if(this.tech_.supportsFullScreen()){this.techCall_('exitFullScreen');}else{this.exitFullWindow();}};_proto.enterFullWindow=function enterFullWindow(){this.isFullscreen(true);this.isFullWindow=true;this.docOrigOverflow=document_1.documentElement.style.overflow;on(document_1,'keydown',this.boundFullWindowOnEscKey_);document_1.documentElement.style.overflow='hidden';addClass(document_1.body,'vjs-full-window');this.trigger('enterFullWindow');};_proto.fullWindowOnEscKey=function fullWindowOnEscKey(event){if(keycode.isEventKey(event,'Esc')){if(this.isFullscreen()===true){this.exitFullscreen();}else{this.exitFullWindow();}}};_proto.exitFullWindow=function exitFullWindow(){this.isFullscreen(false);this.isFullWindow=false;off(document_1,'keydown',this.boundFullWindowOnEscKey_);document_1.documentElement.style.overflow=this.docOrigOverflow;removeClass(document_1.body,'vjs-full-window');this.trigger('exitFullWindow');};_proto.disablePictureInPicture=function disablePictureInPicture(value){if(value===undefined){return this.techGet_('disablePictureInPicture');}
this.techCall_('setDisablePictureInPicture',value);this.options_.disablePictureInPicture=value;this.trigger('disablepictureinpicturechanged');};_proto.isInPictureInPicture=function isInPictureInPicture(isPiP){if(isPiP!==undefined){this.isInPictureInPicture_=!!isPiP;this.togglePictureInPictureClass_();return;}
return!!this.isInPictureInPicture_;};_proto.requestPictureInPicture=function requestPictureInPicture(){if('pictureInPictureEnabled'in document_1&&this.disablePictureInPicture()===false){return this.techGet_('requestPictureInPicture');}};_proto.exitPictureInPicture=function exitPictureInPicture(){if('pictureInPictureEnabled'in document_1){return document_1.exitPictureInPicture();}};_proto.handleKeyDown=function handleKeyDown(event){var userActions=this.options_.userActions;if(!userActions||!userActions.hotkeys){return;}
var excludeElement=function excludeElement(el){var tagName=el.tagName.toLowerCase();if(el.isContentEditable){return true;}
var allowedInputTypes=['button','checkbox','hidden','radio','reset','submit'];if(tagName==='input'){return allowedInputTypes.indexOf(el.type)===-1;}
var excludedTags=['textarea'];return excludedTags.indexOf(tagName)!==-1;};if(excludeElement(this.el_.ownerDocument.activeElement)){return;}
if(typeof userActions.hotkeys==='function'){userActions.hotkeys.call(this,event);}else{this.handleHotkeys(event);}};_proto.handleHotkeys=function handleHotkeys(event){var hotkeys=this.options_.userActions?this.options_.userActions.hotkeys:{};var _hotkeys$fullscreenKe=hotkeys.fullscreenKey,fullscreenKey=_hotkeys$fullscreenKe===void 0?function(keydownEvent){return keycode.isEventKey(keydownEvent,'f');}:_hotkeys$fullscreenKe,_hotkeys$muteKey=hotkeys.muteKey,muteKey=_hotkeys$muteKey===void 0?function(keydownEvent){return keycode.isEventKey(keydownEvent,'m');}:_hotkeys$muteKey,_hotkeys$playPauseKey=hotkeys.playPauseKey,playPauseKey=_hotkeys$playPauseKey===void 0?function(keydownEvent){return keycode.isEventKey(keydownEvent,'k')||keycode.isEventKey(keydownEvent,'Space');}:_hotkeys$playPauseKey;if(fullscreenKey.call(this,event)){event.preventDefault();event.stopPropagation();var FSToggle=Component.getComponent('FullscreenToggle');if(document_1[this.fsApi_.fullscreenEnabled]!==false){FSToggle.prototype.handleClick.call(this,event);}}else if(muteKey.call(this,event)){event.preventDefault();event.stopPropagation();var MuteToggle=Component.getComponent('MuteToggle');MuteToggle.prototype.handleClick.call(this,event);}else if(playPauseKey.call(this,event)){event.preventDefault();event.stopPropagation();var PlayToggle=Component.getComponent('PlayToggle');PlayToggle.prototype.handleClick.call(this,event);}};_proto.canPlayType=function canPlayType(type){var can;for(var i=0,j=this.options_.techOrder;i<j.length;i++){var techName=j[i];var tech=Tech.getTech(techName);if(!tech){tech=Component.getComponent(techName);}
if(!tech){log.error("The \""+techName+"\" tech is undefined. Skipped browser support check for that tech.");continue;}
if(tech.isSupported()){can=tech.canPlayType(type);if(can){return can;}}}
return'';};_proto.selectSource=function selectSource(sources){var _this13=this;var techs=this.options_.techOrder.map(function(techName){return[techName,Tech.getTech(techName)];}).filter(function(_ref){var techName=_ref[0],tech=_ref[1];if(tech){return tech.isSupported();}
log.error("The \""+techName+"\" tech is undefined. Skipped browser support check for that tech.");return false;});var findFirstPassingTechSourcePair=function findFirstPassingTechSourcePair(outerArray,innerArray,tester){var found;outerArray.some(function(outerChoice){return innerArray.some(function(innerChoice){found=tester(outerChoice,innerChoice);if(found){return true;}});});return found;};var foundSourceAndTech;var flip=function flip(fn){return function(a,b){return fn(b,a);};};var finder=function finder(_ref2,source){var techName=_ref2[0],tech=_ref2[1];if(tech.canPlaySource(source,_this13.options_[techName.toLowerCase()])){return{source:source,tech:techName};}};if(this.options_.sourceOrder){foundSourceAndTech=findFirstPassingTechSourcePair(sources,techs,flip(finder));}else{foundSourceAndTech=findFirstPassingTechSourcePair(techs,sources,finder);}
return foundSourceAndTech||false;};_proto.src=function src(source){var _this14=this;if(typeof source==='undefined'){return this.cache_.src||'';}
var sources=filterSource(source);if(!sources.length){this.setTimeout(function(){this.error({code:4,message:this.localize(this.options_.notSupportedMessage)});},0);return;}
this.changingSrc_=true;this.cache_.sources=sources;this.updateSourceCaches_(sources[0]);setSource(this,sources[0],function(middlewareSource,mws){_this14.middleware_=mws;_this14.cache_.sources=sources;_this14.updateSourceCaches_(middlewareSource);var err=_this14.src_(middlewareSource);if(err){if(sources.length>1){return _this14.src(sources.slice(1));}
_this14.changingSrc_=false;_this14.setTimeout(function(){this.error({code:4,message:this.localize(this.options_.notSupportedMessage)});},0);_this14.triggerReady();return;}
setTech(mws,_this14.tech_);});};_proto.src_=function src_(source){var _this15=this;var sourceTech=this.selectSource([source]);if(!sourceTech){return true;}
if(!titleCaseEquals(sourceTech.tech,this.techName_)){this.changingSrc_=true;this.loadTech_(sourceTech.tech,sourceTech.source);this.tech_.ready(function(){_this15.changingSrc_=false;});return false;}
this.ready(function(){if(this.tech_.constructor.prototype.hasOwnProperty('setSource')){this.techCall_('setSource',source);}else{this.techCall_('src',source.src);}
this.changingSrc_=false;},true);return false;};_proto.load=function load(){this.techCall_('load');};_proto.reset=function reset(){var _this16=this;var PromiseClass=this.options_.Promise||window_1.Promise;if(this.paused()||!PromiseClass){this.doReset_();}else{var playPromise=this.play();silencePromise(playPromise.then(function(){return _this16.doReset_();}));}};_proto.doReset_=function doReset_(){if(this.tech_){this.tech_.clearTracks('text');}
this.resetCache_();this.poster('');this.loadTech_(this.options_.techOrder[0],null);this.techCall_('reset');this.resetControlBarUI_();if(isEvented(this)){this.trigger('playerreset');}};_proto.resetControlBarUI_=function resetControlBarUI_(){this.resetProgressBar_();this.resetPlaybackRate_();this.resetVolumeBar_();};_proto.resetProgressBar_=function resetProgressBar_(){this.currentTime(0);var _this$controlBar=this.controlBar,durationDisplay=_this$controlBar.durationDisplay,remainingTimeDisplay=_this$controlBar.remainingTimeDisplay;if(durationDisplay){durationDisplay.updateContent();}
if(remainingTimeDisplay){remainingTimeDisplay.updateContent();}};_proto.resetPlaybackRate_=function resetPlaybackRate_(){this.playbackRate(this.defaultPlaybackRate());this.handleTechRateChange_();};_proto.resetVolumeBar_=function resetVolumeBar_(){this.volume(1.0);this.trigger('volumechange');};_proto.currentSources=function currentSources(){var source=this.currentSource();var sources=[];if(Object.keys(source).length!==0){sources.push(source);}
return this.cache_.sources||sources;};_proto.currentSource=function currentSource(){return this.cache_.source||{};};_proto.currentSrc=function currentSrc(){return this.currentSource()&&this.currentSource().src||'';};_proto.currentType=function currentType(){return this.currentSource()&&this.currentSource().type||'';};_proto.preload=function preload(value){if(value!==undefined){this.techCall_('setPreload',value);this.options_.preload=value;return;}
return this.techGet_('preload');};_proto.autoplay=function autoplay(value){if(value===undefined){return this.options_.autoplay||false;}
var techAutoplay;if(typeof value==='string'&&/(any|play|muted)/.test(value)){this.options_.autoplay=value;this.manualAutoplay_(value);techAutoplay=false;}else if(!value){this.options_.autoplay=false;}else{this.options_.autoplay=true;}
techAutoplay=typeof techAutoplay==='undefined'?this.options_.autoplay:techAutoplay;if(this.tech_){this.techCall_('setAutoplay',techAutoplay);}};_proto.playsinline=function playsinline(value){if(value!==undefined){this.techCall_('setPlaysinline',value);this.options_.playsinline=value;return this;}
return this.techGet_('playsinline');};_proto.loop=function loop(value){if(value!==undefined){this.techCall_('setLoop',value);this.options_.loop=value;return;}
return this.techGet_('loop');};_proto.poster=function poster(src){if(src===undefined){return this.poster_;}
if(!src){src='';}
if(src===this.poster_){return;}
this.poster_=src;this.techCall_('setPoster',src);this.isPosterFromTech_=false;this.trigger('posterchange');};_proto.handleTechPosterChange_=function handleTechPosterChange_(){if((!this.poster_||this.options_.techCanOverridePoster)&&this.tech_&&this.tech_.poster){var newPoster=this.tech_.poster()||'';if(newPoster!==this.poster_){this.poster_=newPoster;this.isPosterFromTech_=true;this.trigger('posterchange');}}};_proto.controls=function controls(bool){if(bool===undefined){return!!this.controls_;}
bool=!!bool;if(this.controls_===bool){return;}
this.controls_=bool;if(this.usingNativeControls()){this.techCall_('setControls',bool);}
if(this.controls_){this.removeClass('vjs-controls-disabled');this.addClass('vjs-controls-enabled');this.trigger('controlsenabled');if(!this.usingNativeControls()){this.addTechControlsListeners_();}}else{this.removeClass('vjs-controls-enabled');this.addClass('vjs-controls-disabled');this.trigger('controlsdisabled');if(!this.usingNativeControls()){this.removeTechControlsListeners_();}}};_proto.usingNativeControls=function usingNativeControls(bool){if(bool===undefined){return!!this.usingNativeControls_;}
bool=!!bool;if(this.usingNativeControls_===bool){return;}
this.usingNativeControls_=bool;if(this.usingNativeControls_){this.addClass('vjs-using-native-controls');this.trigger('usingnativecontrols');}else{this.removeClass('vjs-using-native-controls');this.trigger('usingcustomcontrols');}};_proto.error=function error(err){if(err===undefined){return this.error_||null;}
if(this.options_.suppressNotSupportedError&&err&&err.code===4){var triggerSuppressedError=function triggerSuppressedError(){this.error(err);};this.options_.suppressNotSupportedError=false;this.any(['click','touchstart'],triggerSuppressedError);this.one('loadstart',function(){this.off(['click','touchstart'],triggerSuppressedError);});return;}
if(err===null){this.error_=err;this.removeClass('vjs-error');if(this.errorDisplay){this.errorDisplay.close();}
return;}
this.error_=new MediaError(err);this.addClass('vjs-error');log.error("(CODE:"+this.error_.code+" "+MediaError.errorTypes[this.error_.code]+")",this.error_.message,this.error_);this.trigger('error');return;};_proto.reportUserActivity=function reportUserActivity(event){this.userActivity_=true;};_proto.userActive=function userActive(bool){if(bool===undefined){return this.userActive_;}
bool=!!bool;if(bool===this.userActive_){return;}
this.userActive_=bool;if(this.userActive_){this.userActivity_=true;this.removeClass('vjs-user-inactive');this.addClass('vjs-user-active');this.trigger('useractive');return;}
if(this.tech_){this.tech_.one('mousemove',function(e){e.stopPropagation();e.preventDefault();});}
this.userActivity_=false;this.removeClass('vjs-user-active');this.addClass('vjs-user-inactive');this.trigger('userinactive');};_proto.listenForUserActivity_=function listenForUserActivity_(){var mouseInProgress;var lastMoveX;var lastMoveY;var handleActivity=bind(this,this.reportUserActivity);var handleMouseMove=function handleMouseMove(e){if(e.screenX!==lastMoveX||e.screenY!==lastMoveY){lastMoveX=e.screenX;lastMoveY=e.screenY;handleActivity();}};var handleMouseDown=function handleMouseDown(){handleActivity();this.clearInterval(mouseInProgress);mouseInProgress=this.setInterval(handleActivity,250);};var handleMouseUpAndMouseLeave=function handleMouseUpAndMouseLeave(event){handleActivity();this.clearInterval(mouseInProgress);};this.on('mousedown',handleMouseDown);this.on('mousemove',handleMouseMove);this.on('mouseup',handleMouseUpAndMouseLeave);this.on('mouseleave',handleMouseUpAndMouseLeave);var controlBar=this.getChild('controlBar');if(controlBar&&!IS_IOS&&!IS_ANDROID){controlBar.on('mouseenter',function(event){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);var inactivityTimeout;this.setInterval(function(){if(!this.userActivity_){return;}
this.userActivity_=false;this.userActive(true);this.clearTimeout(inactivityTimeout);var timeout=this.options_.inactivityTimeout;if(timeout<=0){return;}
inactivityTimeout=this.setTimeout(function(){if(!this.userActivity_){this.userActive(false);}},timeout);},250);};_proto.playbackRate=function playbackRate(rate){if(rate!==undefined){this.techCall_('setPlaybackRate',rate);return;}
if(this.tech_&&this.tech_.featuresPlaybackRate){return this.cache_.lastPlaybackRate||this.techGet_('playbackRate');}
return 1.0;};_proto.defaultPlaybackRate=function defaultPlaybackRate(rate){if(rate!==undefined){return this.techCall_('setDefaultPlaybackRate',rate);}
if(this.tech_&&this.tech_.featuresPlaybackRate){return this.techGet_('defaultPlaybackRate');}
return 1.0;};_proto.isAudio=function isAudio(bool){if(bool!==undefined){this.isAudio_=!!bool;return;}
return!!this.isAudio_;};_proto.addTextTrack=function addTextTrack(kind,label,language){if(this.tech_){return this.tech_.addTextTrack(kind,label,language);}};_proto.addRemoteTextTrack=function addRemoteTextTrack(options,manualCleanup){if(this.tech_){return this.tech_.addRemoteTextTrack(options,manualCleanup);}};_proto.removeRemoteTextTrack=function removeRemoteTextTrack(obj){if(obj===void 0){obj={};}
var _obj=obj,track=_obj.track;if(!track){track=obj;}
if(this.tech_){return this.tech_.removeRemoteTextTrack(track);}};_proto.getVideoPlaybackQuality=function getVideoPlaybackQuality(){return this.techGet_('getVideoPlaybackQuality');};_proto.videoWidth=function videoWidth(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0;};_proto.videoHeight=function videoHeight(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0;};_proto.language=function language(code){if(code===undefined){return this.language_;}
if(this.language_!==String(code).toLowerCase()){this.language_=String(code).toLowerCase();if(isEvented(this)){this.trigger('languagechange');}}};_proto.languages=function languages(){return mergeOptions(Player.prototype.options_.languages,this.languages_);};_proto.toJSON=function toJSON(){var options=mergeOptions(this.options_);var tracks=options.tracks;options.tracks=[];for(var i=0;i<tracks.length;i++){var track=tracks[i];track=mergeOptions(track);track.player=undefined;options.tracks[i]=track;}
return options;};_proto.createModal=function createModal(content,options){var _this17=this;options=options||{};options.content=content||'';var modal=new ModalDialog(this,options);this.addChild(modal);modal.on('dispose',function(){_this17.removeChild(modal);});modal.open();return modal;};_proto.updateCurrentBreakpoint_=function updateCurrentBreakpoint_(){if(!this.responsive()){return;}
var currentBreakpoint=this.currentBreakpoint();var currentWidth=this.currentWidth();for(var i=0;i<BREAKPOINT_ORDER.length;i++){var candidateBreakpoint=BREAKPOINT_ORDER[i];var maxWidth=this.breakpoints_[candidateBreakpoint];if(currentWidth<=maxWidth){if(currentBreakpoint===candidateBreakpoint){return;}
if(currentBreakpoint){this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);}
this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);this.breakpoint_=candidateBreakpoint;break;}}};_proto.removeCurrentBreakpoint_=function removeCurrentBreakpoint_(){var className=this.currentBreakpointClass();this.breakpoint_='';if(className){this.removeClass(className);}};_proto.breakpoints=function breakpoints(_breakpoints){if(_breakpoints===undefined){return assign(this.breakpoints_);}
this.breakpoint_='';this.breakpoints_=assign({},DEFAULT_BREAKPOINTS,_breakpoints);this.updateCurrentBreakpoint_();return assign(this.breakpoints_);};_proto.responsive=function responsive(value){if(value===undefined){return this.responsive_;}
value=Boolean(value);var current=this.responsive_;if(value===current){return;}
this.responsive_=value;if(value){this.on('playerresize',this.updateCurrentBreakpoint_);this.updateCurrentBreakpoint_();}else{this.off('playerresize',this.updateCurrentBreakpoint_);this.removeCurrentBreakpoint_();}
return value;};_proto.currentBreakpoint=function currentBreakpoint(){return this.breakpoint_;};_proto.currentBreakpointClass=function currentBreakpointClass(){return BREAKPOINT_CLASSES[this.breakpoint_]||'';};_proto.loadMedia=function loadMedia(media,ready){var _this18=this;if(!media||typeof media!=='object'){return;}
this.reset();this.cache_.media=mergeOptions(media);var _this$cache_$media=this.cache_.media,artwork=_this$cache_$media.artwork,poster=_this$cache_$media.poster,src=_this$cache_$media.src,textTracks=_this$cache_$media.textTracks;if(!artwork&&poster){this.cache_.media.artwork=[{src:poster,type:getMimetype(poster)}];}
if(src){this.src(src);}
if(poster){this.poster(poster);}
if(Array.isArray(textTracks)){textTracks.forEach(function(tt){return _this18.addRemoteTextTrack(tt,false);});}
this.ready(ready);};_proto.getMedia=function getMedia(){if(!this.cache_.media){var poster=this.poster();var src=this.currentSources();var textTracks=Array.prototype.map.call(this.remoteTextTracks(),function(tt){return{kind:tt.kind,label:tt.label,language:tt.language,src:tt.src};});var media={src:src,textTracks:textTracks};if(poster){media.poster=poster;media.artwork=[{src:media.poster,type:getMimetype(media.poster)}];}
return media;}
return mergeOptions(this.cache_.media);};Player.getTagSettings=function getTagSettings(tag){var baseOptions={sources:[],tracks:[]};var tagOptions=getAttributes(tag);var dataSetup=tagOptions['data-setup'];if(hasClass(tag,'vjs-fill')){tagOptions.fill=true;}
if(hasClass(tag,'vjs-fluid')){tagOptions.fluid=true;}
if(dataSetup!==null){var _safeParseTuple=tuple(dataSetup||'{}'),err=_safeParseTuple[0],data=_safeParseTuple[1];if(err){log.error(err);}
assign(tagOptions,data);}
assign(baseOptions,tagOptions);if(tag.hasChildNodes()){var children=tag.childNodes;for(var i=0,j=children.length;i<j;i++){var child=children[i];var childName=child.nodeName.toLowerCase();if(childName==='source'){baseOptions.sources.push(getAttributes(child));}else if(childName==='track'){baseOptions.tracks.push(getAttributes(child));}}}
return baseOptions;};_proto.flexNotSupported_=function flexNotSupported_(){var elem=document_1.createElement('i');return!('flexBasis'in elem.style||'webkitFlexBasis'in elem.style||'mozFlexBasis'in elem.style||'msFlexBasis'in elem.style||'msFlexOrder'in elem.style);};_proto.debug=function debug(enabled){if(enabled===undefined){return this.debugEnabled_;}
if(enabled){this.trigger('debugon');this.previousLogLevel_=this.log.level;this.log.level('debug');this.debugEnabled_=true;}else{this.trigger('debugoff');this.log.level(this.previousLogLevel_);this.previousLogLevel_=undefined;this.debugEnabled_=false;}};return Player;}(Component);ALL.names.forEach(function(name){var props=ALL[name];Player.prototype[props.getterName]=function(){if(this.tech_){return this.tech_[props.getterName]();}
this[props.privateName]=this[props.privateName]||new props.ListClass();return this[props.privateName];};});Player.prototype.crossorigin=Player.prototype.crossOrigin;Player.players={};var navigator=window_1.navigator;Player.prototype.options_={techOrder:Tech.defaultTechOrder_,html5:{},inactivityTimeout:2000,playbackRates:[],liveui:false,children:['mediaLoader','posterImage','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.',fullscreen:{options:{navigationUI:'hide'}},breakpoints:{},responsive:false};['ended','seeking','seekable','networkState','readyState'].forEach(function(fn){Player.prototype[fn]=function(){return this.techGet_(fn);};});TECH_EVENTS_RETRIGGER.forEach(function(event){Player.prototype["handleTech"+toTitleCase(event)+"_"]=function(){return this.trigger(event);};});Component.registerComponent('Player',Player);var setPrototypeOf=createCommonjsModule(function(module){function _setPrototypeOf(o,p){module.exports=_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}
module.exports=_setPrototypeOf;});function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],function(){}));return true;}catch(e){return false;}}
var isNativeReflectConstruct=_isNativeReflectConstruct;var construct=createCommonjsModule(function(module){function _construct(Parent,args,Class){if(isNativeReflectConstruct()){module.exports=_construct=Reflect.construct;}else{module.exports=_construct=function _construct(Parent,args,Class){var a=[null];a.push.apply(a,args);var Constructor=Function.bind.apply(Parent,a);var instance=new Constructor();if(Class)setPrototypeOf(instance,Class.prototype);return instance;};}
return _construct.apply(null,arguments);}
module.exports=_construct;});var BASE_PLUGIN_NAME='plugin';var PLUGIN_CACHE_KEY='activePlugins_';var pluginStorage={};var pluginExists=function pluginExists(name){return pluginStorage.hasOwnProperty(name);};var getPlugin=function getPlugin(name){return pluginExists(name)?pluginStorage[name]:undefined;};var markPluginAsActive=function markPluginAsActive(player,name){player[PLUGIN_CACHE_KEY]=player[PLUGIN_CACHE_KEY]||{};player[PLUGIN_CACHE_KEY][name]=true;};var triggerSetupEvent=function triggerSetupEvent(player,hash,before){var eventName=(before?'before':'')+'pluginsetup';player.trigger(eventName,hash);player.trigger(eventName+':'+hash.name,hash);};var createBasicPlugin=function createBasicPlugin(name,plugin){var basicPluginWrapper=function basicPluginWrapper(){triggerSetupEvent(this,{name:name,plugin:plugin,instance:null},true);var instance=plugin.apply(this,arguments);markPluginAsActive(this,name);triggerSetupEvent(this,{name:name,plugin:plugin,instance:instance});return instance;};Object.keys(plugin).forEach(function(prop){basicPluginWrapper[prop]=plugin[prop];});return basicPluginWrapper;};var createPluginFactory=function createPluginFactory(name,PluginSubClass){PluginSubClass.prototype.name=name;return function(){triggerSetupEvent(this,{name:name,plugin:PluginSubClass,instance:null},true);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}
var instance=construct(PluginSubClass,[this].concat(args));this[name]=function(){return instance;};triggerSetupEvent(this,instance.getEventHash());return instance;};};var Plugin=function(){function Plugin(player){if(this.constructor===Plugin){throw new Error('Plugin must be sub-classed; not directly instantiated.');}
this.player=player;if(!this.log){this.log=this.player.log.createLogger(this.name);}
evented(this);delete this.trigger;stateful(this,this.constructor.defaultState);markPluginAsActive(player,this.name);this.dispose=bind(this,this.dispose);player.on('dispose',this.dispose);}
var _proto=Plugin.prototype;_proto.version=function version(){return this.constructor.VERSION;};_proto.getEventHash=function getEventHash(hash){if(hash===void 0){hash={};}
hash.name=this.name;hash.plugin=this.constructor;hash.instance=this;return hash;};_proto.trigger=function trigger$1(event,hash){if(hash===void 0){hash={};}
return trigger(this.eventBusEl_,event,this.getEventHash(hash));};_proto.handleStateChanged=function handleStateChanged(e){};_proto.dispose=function dispose(){var name=this.name,player=this.player;this.trigger('dispose');this.off();player.off('dispose',this.dispose);player[PLUGIN_CACHE_KEY][name]=false;this.player=this.state=null;player[name]=createPluginFactory(name,pluginStorage[name]);};Plugin.isBasic=function isBasic(plugin){var p=typeof plugin==='string'?getPlugin(plugin):plugin;return typeof p==='function'&&!Plugin.prototype.isPrototypeOf(p.prototype);};Plugin.registerPlugin=function registerPlugin(name,plugin){if(typeof name!=='string'){throw new Error("Illegal plugin name, \""+name+"\", must be a string, was "+typeof name+".");}
if(pluginExists(name)){log.warn("A plugin named \""+name+"\" already exists. You may want to avoid re-registering plugins!");}else if(Player.prototype.hasOwnProperty(name)){throw new Error("Illegal plugin name, \""+name+"\", cannot share a name with an existing player method!");}
if(typeof plugin!=='function'){throw new Error("Illegal plugin for \""+name+"\", must be a function, was "+typeof plugin+".");}
pluginStorage[name]=plugin;if(name!==BASE_PLUGIN_NAME){if(Plugin.isBasic(plugin)){Player.prototype[name]=createBasicPlugin(name,plugin);}else{Player.prototype[name]=createPluginFactory(name,plugin);}}
return plugin;};Plugin.deregisterPlugin=function deregisterPlugin(name){if(name===BASE_PLUGIN_NAME){throw new Error('Cannot de-register base plugin.');}
if(pluginExists(name)){delete pluginStorage[name];delete Player.prototype[name];}};Plugin.getPlugins=function getPlugins(names){if(names===void 0){names=Object.keys(pluginStorage);}
var result;names.forEach(function(name){var plugin=getPlugin(name);if(plugin){result=result||{};result[name]=plugin;}});return result;};Plugin.getPluginVersion=function getPluginVersion(name){var plugin=getPlugin(name);return plugin&&plugin.VERSION||'';};return Plugin;}();Plugin.getPlugin=getPlugin;Plugin.BASE_PLUGIN_NAME=BASE_PLUGIN_NAME;Plugin.registerPlugin(BASE_PLUGIN_NAME,Plugin);Player.prototype.usingPlugin=function(name){return!!this[PLUGIN_CACHE_KEY]&&this[PLUGIN_CACHE_KEY][name]===true;};Player.prototype.hasPlugin=function(name){return!!pluginExists(name);};function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}
subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)setPrototypeOf(subClass,superClass);}
var inherits=_inherits;var extend=function extend(superClass,subClassMethods){if(subClassMethods===void 0){subClassMethods={};}
var subClass=function subClass(){superClass.apply(this,arguments);};var methods={};if(typeof subClassMethods==='object'){if(subClassMethods.constructor!==Object.prototype.constructor){subClass=subClassMethods.constructor;}
methods=subClassMethods;}else if(typeof subClassMethods==='function'){subClass=subClassMethods;}
inherits(subClass,superClass);if(superClass){subClass.super_=superClass;}
for(var name in methods){if(methods.hasOwnProperty(name)){subClass.prototype[name]=methods[name];}}
return subClass;};var normalizeId=function normalizeId(id){return id.indexOf('#')===0?id.slice(1):id;};function videojs$1(id,options,ready){var player=videojs$1.getPlayer(id);if(player){if(options){log.warn("Player \""+id+"\" is already initialised. Options will not be applied.");}
if(ready){player.ready(ready);}
return player;}
var el=typeof id==='string'?$('#'+normalizeId(id)):id;if(!isEl(el)){throw new TypeError('The element or ID supplied is not valid. (videojs)');}
if(!el.ownerDocument.defaultView||!el.ownerDocument.body.contains(el)){log.warn('The element supplied is not included in the DOM');}
options=options||{};videojs$1.hooks('beforesetup').forEach(function(hookFunction){var opts=hookFunction(el,mergeOptions(options));if(!isObject(opts)||Array.isArray(opts)){log.error('please return an object in beforesetup hooks');return;}
options=mergeOptions(options,opts);});var PlayerComponent=Component.getComponent('Player');player=new PlayerComponent(el,options,ready);videojs$1.hooks('setup').forEach(function(hookFunction){return hookFunction(player);});return player;}
videojs$1.hooks_={};videojs$1.hooks=function(type,fn){videojs$1.hooks_[type]=videojs$1.hooks_[type]||[];if(fn){videojs$1.hooks_[type]=videojs$1.hooks_[type].concat(fn);}
return videojs$1.hooks_[type];};videojs$1.hook=function(type,fn){videojs$1.hooks(type,fn);};videojs$1.hookOnce=function(type,fn){videojs$1.hooks(type,[].concat(fn).map(function(original){var wrapper=function wrapper(){videojs$1.removeHook(type,wrapper);return original.apply(void 0,arguments);};return wrapper;}));};videojs$1.removeHook=function(type,fn){var index=videojs$1.hooks(type).indexOf(fn);if(index<=-1){return false;}
videojs$1.hooks_[type]=videojs$1.hooks_[type].slice();videojs$1.hooks_[type].splice(index,1);return true;};if(window_1.VIDEOJS_NO_DYNAMIC_STYLE!==true&&isReal()){var style=$('.vjs-styles-defaults');if(!style){style=createStyleElement('vjs-styles-defaults');var head=$('head');if(head){head.insertBefore(style,head.firstChild);}
setTextContent(style,"\n      .video-js {\n        width: 300px;\n        height: 150px;\n      }\n\n      .vjs-fluid {\n        padding-top: 56.25%\n      }\n    ");}}
autoSetupTimeout(1,videojs$1);videojs$1.VERSION=version;videojs$1.options=Player.prototype.options_;videojs$1.getPlayers=function(){return Player.players;};videojs$1.getPlayer=function(id){var players=Player.players;var tag;if(typeof id==='string'){var nId=normalizeId(id);var player=players[nId];if(player){return player;}
tag=$('#'+nId);}else{tag=id;}
if(isEl(tag)){var _tag=tag,_player=_tag.player,playerId=_tag.playerId;if(_player||players[playerId]){return _player||players[playerId];}}};videojs$1.getAllPlayers=function(){return(Object.keys(Player.players).map(function(k){return Player.players[k];}).filter(Boolean));};videojs$1.players=Player.players;videojs$1.getComponent=Component.getComponent;videojs$1.registerComponent=function(name,comp){if(Tech.isTech(comp)){log.warn("The "+name+" tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)");}
Component.registerComponent.call(Component,name,comp);};videojs$1.getTech=Tech.getTech;videojs$1.registerTech=Tech.registerTech;videojs$1.use=use;Object.defineProperty(videojs$1,'middleware',{value:{},writeable:false,enumerable:true});Object.defineProperty(videojs$1.middleware,'TERMINATOR',{value:TERMINATOR,writeable:false,enumerable:true});videojs$1.browser=browser;videojs$1.TOUCH_ENABLED=TOUCH_ENABLED;videojs$1.extend=extend;videojs$1.mergeOptions=mergeOptions;videojs$1.bind=bind;videojs$1.registerPlugin=Plugin.registerPlugin;videojs$1.deregisterPlugin=Plugin.deregisterPlugin;videojs$1.plugin=function(name,plugin){log.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');return Plugin.registerPlugin(name,plugin);};videojs$1.getPlugins=Plugin.getPlugins;videojs$1.getPlugin=Plugin.getPlugin;videojs$1.getPluginVersion=Plugin.getPluginVersion;videojs$1.addLanguage=function(code,data){var _mergeOptions;code=(''+code).toLowerCase();videojs$1.options.languages=mergeOptions(videojs$1.options.languages,(_mergeOptions={},_mergeOptions[code]=data,_mergeOptions));return videojs$1.options.languages[code];};videojs$1.log=log;videojs$1.createLogger=createLogger$1;videojs$1.createTimeRange=videojs$1.createTimeRanges=createTimeRanges;videojs$1.formatTime=formatTime;videojs$1.setFormatTime=setFormatTime;videojs$1.resetFormatTime=resetFormatTime;videojs$1.parseUrl=parseUrl;videojs$1.isCrossOrigin=isCrossOrigin;videojs$1.EventTarget=EventTarget;videojs$1.on=on;videojs$1.one=one;videojs$1.off=off;videojs$1.trigger=trigger;videojs$1.xhr=xhr;videojs$1.TextTrack=TextTrack;videojs$1.AudioTrack=AudioTrack;videojs$1.VideoTrack=VideoTrack;['isEl','isTextNode','createEl','hasClass','addClass','removeClass','toggleClass','setAttributes','getAttributes','emptyEl','appendContent','insertContent'].forEach(function(k){videojs$1[k]=function(){log.warn("videojs."+k+"() is deprecated; use videojs.dom."+k+"() instead");return Dom[k].apply(null,arguments);};});videojs$1.computedStyle=computedStyle;videojs$1.dom=Dom;videojs$1.url=Url;videojs$1.defineLazyProperty=defineLazyProperty;function _assertThisInitialized$1(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}
return self;}
var assertThisInitialized$1=_assertThisInitialized$1;function _inheritsLoose$1(subClass,superClass){subClass.prototype=Object.create(superClass.prototype);subClass.prototype.constructor=subClass;subClass.__proto__=superClass;}
var inheritsLoose$1=_inheritsLoose$1;var topLevel$1=typeof commonjsGlobal!=='undefined'?commonjsGlobal:typeof window!=='undefined'?window:{};var doccy$1;if(typeof document!=='undefined'){doccy$1=document;}else{doccy$1=topLevel$1['__GLOBAL_DOCUMENT_CACHE@4'];if(!doccy$1){doccy$1=topLevel$1['__GLOBAL_DOCUMENT_CACHE@4']=minDoc;}}
var document_1$1=doccy$1;var win$2;if(typeof window!=="undefined"){win$2=window;}else if(typeof commonjsGlobal!=="undefined"){win$2=commonjsGlobal;}else if(typeof self!=="undefined"){win$2=self;}else{win$2={};}
var window_1$2=win$2;var urlToolkit=createCommonjsModule(function(module,exports){(function(root){var URL_REGEX=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/;var FIRST_SEGMENT_REGEX=/^([^\/?#]*)(.*)$/;var SLASH_DOT_REGEX=/(?:\/|^)\.(?=\/)/g;var SLASH_DOT_DOT_REGEX=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;var URLToolkit={buildAbsoluteURL:function buildAbsoluteURL(baseURL,relativeURL,opts){opts=opts||{};baseURL=baseURL.trim();relativeURL=relativeURL.trim();if(!relativeURL){if(!opts.alwaysNormalize){return baseURL;}
var basePartsForNormalise=URLToolkit.parseURL(baseURL);if(!basePartsForNormalise){throw new Error('Error trying to parse base URL.');}
basePartsForNormalise.path=URLToolkit.normalizePath(basePartsForNormalise.path);return URLToolkit.buildURLFromParts(basePartsForNormalise);}
var relativeParts=URLToolkit.parseURL(relativeURL);if(!relativeParts){throw new Error('Error trying to parse relative URL.');}
if(relativeParts.scheme){if(!opts.alwaysNormalize){return relativeURL;}
relativeParts.path=URLToolkit.normalizePath(relativeParts.path);return URLToolkit.buildURLFromParts(relativeParts);}
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];}
if(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;if(relativeParts.path[0]!=='/'){if(!relativeParts.path){builtParts.path=baseParts.path;if(!relativeParts.params){builtParts.params=baseParts.params;if(!relativeParts.query){builtParts.query=baseParts.query;}}}else{var baseURLPath=baseParts.path;var newPath=baseURLPath.substring(0,baseURLPath.lastIndexOf('/')+1)+relativeParts.path;builtParts.path=URLToolkit.normalizePath(newPath);}}}
if(builtParts.path===null){builtParts.path=opts.alwaysNormalize?URLToolkit.normalizePath(relativeParts.path):relativeParts.path;}
return URLToolkit.buildURLFromParts(builtParts);},parseURL:function parseURL(url){var parts=URL_REGEX.exec(url);if(!parts){return null;}
return{scheme:parts[1]||'',netLoc:parts[2]||'',path:parts[3]||'',params:parts[4]||'',query:parts[5]||'',fragment:parts[6]||''};},normalizePath:function normalizePath(path){path=path.split('').reverse().join('').replace(SLASH_DOT_REGEX,'');while(path.length!==(path=path.replace(SLASH_DOT_DOT_REGEX,'')).length){}
return path.split('').reverse().join('');},buildURLFromParts:function buildURLFromParts(parts){return parts.scheme+parts.netLoc+parts.path+parts.params+parts.query+parts.fragment;}};module.exports=URLToolkit;})();});function _interopDefault(ex){return ex&&typeof ex==='object'&&'default'in ex?ex['default']:ex;}
var URLToolkit=_interopDefault(urlToolkit);var window$1=_interopDefault(window_1);var resolveUrl=function resolveUrl(baseUrl,relativeUrl){if(/^[a-z]+:/i.test(relativeUrl)){return relativeUrl;}
if(!/\/\//i.test(baseUrl)){baseUrl=URLToolkit.buildAbsoluteURL(window$1.location&&window$1.location.href||'',baseUrl);}
return URLToolkit.buildAbsoluteURL(baseUrl,relativeUrl);};var resolveUrl_1=resolveUrl;var Stream=function(){function Stream(){this.listeners={};}
var _proto=Stream.prototype;_proto.on=function on(type,listener){if(!this.listeners[type]){this.listeners[type]=[];}
this.listeners[type].push(listener);};_proto.off=function off(type,listener){if(!this.listeners[type]){return false;}
var index=this.listeners[type].indexOf(listener);this.listeners[type]=this.listeners[type].slice(0);this.listeners[type].splice(index,1);return index>-1;};_proto.trigger=function trigger(type){var callbacks=this.listeners[type];if(!callbacks){return;}
if(arguments.length===2){var length=callbacks.length;for(var i=0;i<length;++i){callbacks[i].call(this,arguments[1]);}}else{var args=Array.prototype.slice.call(arguments,1);var _length=callbacks.length;for(var _i=0;_i<_length;++_i){callbacks[_i].apply(this,args);}}};_proto.dispose=function dispose(){this.listeners={};};_proto.pipe=function pipe(destination){this.on('data',function(data){destination.push(data);});};return Stream;}();var stream=Stream;function _interopDefault$1(ex){return ex&&typeof ex==='object'&&'default'in ex?ex['default']:ex;}
var window$2=_interopDefault$1(window_1);var atob=function atob(s){return window$2.atob?window$2.atob(s):Buffer.from(s,'base64').toString('binary');};function decodeB64ToUint8Array(b64Text){var decodedString=atob(b64Text);var array=new Uint8Array(decodedString.length);for(var i=0;i<decodedString.length;i++){array[i]=decodedString.charCodeAt(i);}
return array;}
var decodeB64ToUint8Array_1=decodeB64ToUint8Array;var LineStream=function(_Stream){inheritsLoose(LineStream,_Stream);function LineStream(){var _this;_this=_Stream.call(this)||this;_this.buffer='';return _this;}
var _proto=LineStream.prototype;_proto.push=function push(data){var nextNewline;this.buffer+=data;nextNewline=this.buffer.indexOf('\n');for(;nextNewline>-1;nextNewline=this.buffer.indexOf('\n')){this.trigger('data',this.buffer.substring(0,nextNewline));this.buffer=this.buffer.substring(nextNewline+1);}};return LineStream;}(stream);var attributeSeparator=function attributeSeparator(){var key='[^=]*';var value='"[^"]*"|[^,]*';var keyvalue='(?:'+key+')=(?:'+value+')';return new RegExp('(?:^|,)('+keyvalue+')');};var parseAttributes=function parseAttributes(attributes){var attrs=attributes.split(attributeSeparator());var result={};var i=attrs.length;var attr;while(i--){if(attrs[i]===''){continue;}
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;};var ParseStream=function(_Stream){inheritsLoose(ParseStream,_Stream);function ParseStream(){var _this;_this=_Stream.call(this)||this;_this.customParsers=[];_this.tagMappers=[];return _this;}
var _proto=ParseStream.prototype;_proto.push=function push(line){var _this2=this;var match;var event;line=line.trim();if(line.length===0){return;}
if(line[0]!=='#'){this.trigger('data',{type:'uri',uri:line});return;}
var newLines=this.tagMappers.reduce(function(acc,mapper){var mappedLine=mapper(line);if(mappedLine===line){return acc;}
return acc.concat([mappedLine]);},[line]);newLines.forEach(function(newLine){for(var i=0;i<_this2.customParsers.length;i++){if(_this2.customParsers[i].call(_this2,newLine)){return;}}
if(newLine.indexOf('#EXT')!==0){_this2.trigger('data',{type:'comment',text:newLine.slice(1)});return;}
newLine=newLine.replace('\r','');match=/^#EXTM3U/.exec(newLine);if(match){_this2.trigger('data',{type:'tag',tagType:'m3u'});return;}
match=/^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(newLine);if(match){event={type:'tag',tagType:'inf'};if(match[1]){event.duration=parseFloat(match[1]);}
if(match[2]){event.title=match[2];}
_this2.trigger('data',event);return;}
match=/^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(newLine);if(match){event={type:'tag',tagType:'targetduration'};if(match[1]){event.duration=parseInt(match[1],10);}
_this2.trigger('data',event);return;}
match=/^#ZEN-TOTAL-DURATION:?([0-9.]*)?/.exec(newLine);if(match){event={type:'tag',tagType:'totalduration'};if(match[1]){event.duration=parseInt(match[1],10);}
_this2.trigger('data',event);return;}
match=/^#EXT-X-VERSION:?([0-9.]*)?/.exec(newLine);if(match){event={type:'tag',tagType:'version'};if(match[1]){event.version=parseInt(match[1],10);}
_this2.trigger('data',event);return;}
match=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);if(match){event={type:'tag',tagType:'media-sequence'};if(match[1]){event.number=parseInt(match[1],10);}
_this2.trigger('data',event);return;}
match=/^#EXT-X-DISCONTINUITY-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);if(match){event={type:'tag',tagType:'discontinuity-sequence'};if(match[1]){event.number=parseInt(match[1],10);}
_this2.trigger('data',event);return;}
match=/^#EXT-X-PLAYLIST-TYPE:?(.*)?$/.exec(newLine);if(match){event={type:'tag',tagType:'playlist-type'};if(match[1]){event.playlistType=match[1];}
_this2.trigger('data',event);return;}
match=/^#EXT-X-BYTERANGE:?([0-9.]*)?@?([0-9.]*)?/.exec(newLine);if(match){event={type:'tag',tagType:'byterange'};if(match[1]){event.length=parseInt(match[1],10);}
if(match[2]){event.offset=parseInt(match[2],10);}
_this2.trigger('data',event);return;}
match=/^#EXT-X-ALLOW-CACHE:?(YES|NO)?/.exec(newLine);if(match){event={type:'tag',tagType:'allow-cache'};if(match[1]){event.allowed=!/NO/.test(match[1]);}
_this2.trigger('data',event);return;}
match=/^#EXT-X-MAP:?(.*)$/.exec(newLine);if(match){event={type:'tag',tagType:'map'};if(match[1]){var attributes=parseAttributes(match[1]);if(attributes.URI){event.uri=attributes.URI;}
if(attributes.BYTERANGE){var _attributes$BYTERANGE=attributes.BYTERANGE.split('@'),length=_attributes$BYTERANGE[0],offset=_attributes$BYTERANGE[1];event.byterange={};if(length){event.byterange.length=parseInt(length,10);}
if(offset){event.byterange.offset=parseInt(offset,10);}}}
_this2.trigger('data',event);return;}
match=/^#EXT-X-STREAM-INF:?(.*)$/.exec(newLine);if(match){event={type:'tag',tagType:'stream-inf'};if(match[1]){event.attributes=parseAttributes(match[1]);if(event.attributes.RESOLUTION){var split=event.attributes.RESOLUTION.split('x');var resolution={};if(split[0]){resolution.width=parseInt(split[0],10);}
if(split[1]){resolution.height=parseInt(split[1],10);}
event.attributes.RESOLUTION=resolution;}
if(event.attributes.BANDWIDTH){event.attributes.BANDWIDTH=parseInt(event.attributes.BANDWIDTH,10);}
if(event.attributes['PROGRAM-ID']){event.attributes['PROGRAM-ID']=parseInt(event.attributes['PROGRAM-ID'],10);}}
_this2.trigger('data',event);return;}
match=/^#EXT-X-MEDIA:?(.*)$/.exec(newLine);if(match){event={type:'tag',tagType:'media'};if(match[1]){event.attributes=parseAttributes(match[1]);}
_this2.trigger('data',event);return;}
match=/^#EXT-X-ENDLIST/.exec(newLine);if(match){_this2.trigger('data',{type:'tag',tagType:'endlist'});return;}
match=/^#EXT-X-DISCONTINUITY/.exec(newLine);if(match){_this2.trigger('data',{type:'tag',tagType:'discontinuity'});return;}
match=/^#EXT-X-PROGRAM-DATE-TIME:?(.*)$/.exec(newLine);if(match){event={type:'tag',tagType:'program-date-time'};if(match[1]){event.dateTimeString=match[1];event.dateTimeObject=new Date(match[1]);}
_this2.trigger('data',event);return;}
match=/^#EXT-X-KEY:?(.*)$/.exec(newLine);if(match){event={type:'tag',tagType:'key'};if(match[1]){event.attributes=parseAttributes(match[1]);if(event.attributes.IV){if(event.attributes.IV.substring(0,2).toLowerCase()==='0x'){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);}}
_this2.trigger('data',event);return;}
match=/^#EXT-X-START:?(.*)$/.exec(newLine);if(match){event={type:'tag',tagType:'start'};if(match[1]){event.attributes=parseAttributes(match[1]);event.attributes['TIME-OFFSET']=parseFloat(event.attributes['TIME-OFFSET']);event.attributes.PRECISE=/YES/.test(event.attributes.PRECISE);}
_this2.trigger('data',event);return;}
match=/^#EXT-X-CUE-OUT-CONT:?(.*)?$/.exec(newLine);if(match){event={type:'tag',tagType:'cue-out-cont'};if(match[1]){event.data=match[1];}else{event.data='';}
_this2.trigger('data',event);return;}
match=/^#EXT-X-CUE-OUT:?(.*)?$/.exec(newLine);if(match){event={type:'tag',tagType:'cue-out'};if(match[1]){event.data=match[1];}else{event.data='';}
_this2.trigger('data',event);return;}
match=/^#EXT-X-CUE-IN:?(.*)?$/.exec(newLine);if(match){event={type:'tag',tagType:'cue-in'};if(match[1]){event.data=match[1];}else{event.data='';}
_this2.trigger('data',event);return;}
_this2.trigger('data',{type:'tag',data:newLine.slice(4)});});};_proto.addParser=function addParser(_ref){var _this3=this;var expression=_ref.expression,customType=_ref.customType,dataParser=_ref.dataParser,segment=_ref.segment;if(typeof dataParser!=='function'){dataParser=function dataParser(line){return line;};}
this.customParsers.push(function(line){var match=expression.exec(line);if(match){_this3.trigger('data',{type:'custom',data:dataParser(line),customType:customType,segment:segment});return true;}});};_proto.addTagMapper=function addTagMapper(_ref2){var expression=_ref2.expression,map=_ref2.map;var mapFn=function mapFn(line){if(expression.test(line)){return map(line);}
return line;};this.tagMappers.push(mapFn);};return ParseStream;}(stream);var Parser=function(_Stream){inheritsLoose(Parser,_Stream);function Parser(){var _this;_this=_Stream.call(this)||this;_this.lineStream=new LineStream();_this.parseStream=new ParseStream();_this.lineStream.pipe(_this.parseStream);var self=assertThisInitialized(_this);var uris=[];var currentUri={};var currentMap;var _key;var noop=function noop(){};var defaultMediaGroups={'AUDIO':{},'VIDEO':{},'CLOSED-CAPTIONS':{},'SUBTITLES':{}};var widevineUuid='urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed';var currentTimeline=0;_this.manifest={allowCache:true,discontinuityStarts:[],segments:[]};var lastByterangeEnd=0;_this.parseStream.on('data',function(entry){var mediaGroup;var rendition;({tag:function tag(){(({'allow-cache':function allowCache(){this.manifest.allowCache=entry.allowed;if(!('allowed'in entry)){this.trigger('info',{message:'defaulting allowCache to YES'});this.manifest.allowCache=true;}},byterange:function byterange(){var byterange={};if('length'in entry){currentUri.byterange=byterange;byterange.length=entry.length;if(!('offset'in entry)){entry.offset=lastByterangeEnd;}}
if('offset'in entry){currentUri.byterange=byterange;byterange.offset=entry.offset;}
lastByterangeEnd=byterange.offset+byterange.length;},endlist:function endlist(){this.manifest.endList=true;},inf:function inf(){if(!('mediaSequence'in this.manifest)){this.manifest.mediaSequence=0;this.trigger('info',{message:'defaulting media sequence to zero'});}
if(!('discontinuitySequence'in this.manifest)){this.manifest.discontinuitySequence=0;this.trigger('info',{message:'defaulting discontinuity sequence to zero'});}
if(entry.duration>0){currentUri.duration=entry.duration;}
if(entry.duration===0){currentUri.duration=0.01;this.trigger('info',{message:'updating zero segment duration to a small value'});}
this.manifest.segments=uris;},key:function key(){if(!entry.attributes){this.trigger('warn',{message:'ignoring key declaration without attribute list'});return;}
if(entry.attributes.METHOD==='NONE'){_key=null;return;}
if(!entry.attributes.URI){this.trigger('warn',{message:'ignoring key declaration without URI'});return;}
if(entry.attributes.KEYFORMAT===widevineUuid){var VALID_METHODS=['SAMPLE-AES','SAMPLE-AES-CTR','SAMPLE-AES-CENC'];if(VALID_METHODS.indexOf(entry.attributes.METHOD)===-1){this.trigger('warn',{message:'invalid key method provided for Widevine'});return;}
if(entry.attributes.METHOD==='SAMPLE-AES-CENC'){this.trigger('warn',{message:'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'});}
if(entry.attributes.URI.substring(0,23)!=='data:text/plain;base64,'){this.trigger('warn',{message:'invalid key URI provided for Widevine'});return;}
if(!(entry.attributes.KEYID&&entry.attributes.KEYID.substring(0,2)==='0x')){this.trigger('warn',{message:'invalid key ID provided for Widevine'});return;}
this.manifest.contentProtection={'com.widevine.alpha':{attributes:{schemeIdUri:entry.attributes.KEYFORMAT,keyId:entry.attributes.KEYID.substring(2)},pssh:decodeB64ToUint8Array_1(entry.attributes.URI.split(',')[1])}};return;}
if(!entry.attributes.METHOD){this.trigger('warn',{message:'defaulting key method to AES-128'});}
_key={method:entry.attributes.METHOD||'AES-128',uri:entry.attributes.URI};if(typeof entry.attributes.IV!=='undefined'){_key.iv=entry.attributes.IV;}},'media-sequence':function mediaSequence(){if(!isFinite(entry.number)){this.trigger('warn',{message:'ignoring invalid media sequence: '+entry.number});return;}
this.manifest.mediaSequence=entry.number;},'discontinuity-sequence':function discontinuitySequence(){if(!isFinite(entry.number)){this.trigger('warn',{message:'ignoring invalid discontinuity sequence: '+entry.number});return;}
this.manifest.discontinuitySequence=entry.number;currentTimeline=entry.number;},'playlist-type':function playlistType(){if(!/VOD|EVENT/.test(entry.playlistType)){this.trigger('warn',{message:'ignoring unknown playlist type: '+entry.playlist});return;}
this.manifest.playlistType=entry.playlistType;},map:function map(){currentMap={};if(entry.uri){currentMap.uri=entry.uri;}
if(entry.byterange){currentMap.byterange=entry.byterange;}},'stream-inf':function streamInf(){this.manifest.playlists=uris;this.manifest.mediaGroups=this.manifest.mediaGroups||defaultMediaGroups;if(!entry.attributes){this.trigger('warn',{message:'ignoring empty stream-inf attributes'});return;}
if(!currentUri.attributes){currentUri.attributes={};}
_extends_1(currentUri.attributes,entry.attributes);},media:function media(){this.manifest.mediaGroups=this.manifest.mediaGroups||defaultMediaGroups;if(!(entry.attributes&&entry.attributes.TYPE&&entry.attributes['GROUP-ID']&&entry.attributes.NAME)){this.trigger('warn',{message:'ignoring incomplete or missing media group'});return;}
var 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)};if(rendition["default"]){rendition.autoselect=true;}else{rendition.autoselect=/yes/i.test(entry.attributes.AUTOSELECT);}
if(entry.attributes.LANGUAGE){rendition.language=entry.attributes.LANGUAGE;}
if(entry.attributes.URI){rendition.uri=entry.attributes.URI;}
if(entry.attributes['INSTREAM-ID']){rendition.instreamId=entry.attributes['INSTREAM-ID'];}
if(entry.attributes.CHARACTERISTICS){rendition.characteristics=entry.attributes.CHARACTERISTICS;}
if(entry.attributes.FORCED){rendition.forced=/yes/i.test(entry.attributes.FORCED);}
mediaGroup[entry.attributes.NAME]=rendition;},discontinuity:function discontinuity(){currentTimeline+=1;currentUri.discontinuity=true;this.manifest.discontinuityStarts.push(uris.length);},'program-date-time':function programDateTime(){if(typeof this.manifest.dateTimeString==='undefined'){this.manifest.dateTimeString=entry.dateTimeString;this.manifest.dateTimeObject=entry.dateTimeObject;}
currentUri.dateTimeString=entry.dateTimeString;currentUri.dateTimeObject=entry.dateTimeObject;},targetduration:function targetduration(){if(!isFinite(entry.duration)||entry.duration<0){this.trigger('warn',{message:'ignoring invalid target duration: '+entry.duration});return;}
this.manifest.targetDuration=entry.duration;},totalduration:function totalduration(){if(!isFinite(entry.duration)||entry.duration<0){this.trigger('warn',{message:'ignoring invalid total duration: '+entry.duration});return;}
this.manifest.totalDuration=entry.duration;},start:function start(){if(!entry.attributes||isNaN(entry.attributes['TIME-OFFSET'])){this.trigger('warn',{message:'ignoring start declaration without appropriate attribute list'});return;}
this.manifest.start={timeOffset:entry.attributes['TIME-OFFSET'],precise:entry.attributes.PRECISE};},'cue-out':function cueOut(){currentUri.cueOut=entry.data;},'cue-out-cont':function cueOutCont(){currentUri.cueOutCont=entry.data;},'cue-in':function cueIn(){currentUri.cueIn=entry.data;}})[entry.tagType]||noop).call(self);},uri:function uri(){currentUri.uri=entry.uri;uris.push(currentUri);if(this.manifest.targetDuration&&!('duration'in currentUri)){this.trigger('warn',{message:'defaulting segment duration to the target duration'});currentUri.duration=this.manifest.targetDuration;}
if(_key){currentUri.key=_key;}
currentUri.timeline=currentTimeline;if(currentMap){currentUri.map=currentMap;}
currentUri={};},comment:function comment(){},custom:function custom(){if(entry.segment){currentUri.custom=currentUri.custom||{};currentUri.custom[entry.customType]=entry.data;}else{this.manifest.custom=this.manifest.custom||{};this.manifest.custom[entry.customType]=entry.data;}}})[entry.type].call(self);});return _this;}
var _proto=Parser.prototype;_proto.push=function push(chunk){this.lineStream.push(chunk);};_proto.end=function end(){this.lineStream.push('\n');};_proto.addParser=function addParser(options){this.parseStream.addParser(options);};_proto.addTagMapper=function addTagMapper(options){this.parseStream.addTagMapper(options);};return Parser;}(stream);var mediaTypes=createCommonjsModule(function(module,exports){Object.defineProperty(exports,'__esModule',{value:true});var MPEGURL_REGEX=/^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;var DASH_REGEX=/^application\/dash\+xml/i;var simpleTypeFromSourceType=function simpleTypeFromSourceType(type){if(MPEGURL_REGEX.test(type)){return'hls';}
if(DASH_REGEX.test(type)){return'dash';}
if(type==='application/vnd.videojs.vhs+json'){return'vhs-json';}
return null;};exports.simpleTypeFromSourceType=simpleTypeFromSourceType;});unwrapExports(mediaTypes);var mediaTypes_1=mediaTypes.simpleTypeFromSourceType;var 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]/;var nameChar=new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");var tagNamePattern=new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');var S_TAG=0;var S_ATTR=1;var S_ATTR_SPACE=2;var S_EQ=3;var S_ATTR_NOQUOT_VALUE=4;var S_ATTR_END=5;var S_TAG_SPACE=6;var S_TAG_CLOSE=7;function XMLReader(){}
XMLReader.prototype={parse:function parse(source,defaultNSMap,entityMap){var domBuilder=this.domBuilder;domBuilder.startDocument();_copy(defaultNSMap,defaultNSMap={});_parse(source,defaultNSMap,entityMap,domBuilder,this.errorHandler);domBuilder.endDocument();}};function _parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){function fixedFromCharCode(code){if(code>0xffff){code-=0x10000;var surrogate1=0xd800+(code>>10),surrogate2=0xdc00+(code&0x3ff);return String.fromCharCode(surrogate1,surrogate2);}else{return String.fromCharCode(code);}}
function entityReplacer(a){var k=a.slice(1,-1);if(k in entityMap){return entityMap[k];}else if(k.charAt(0)==='#'){return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')));}else{errorHandler.error('entity not found:'+a);return a;}}
function appendText(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){while(p>=lineEnd&&(m=linePattern.exec(source))){lineStart=m.index;lineEnd=lineStart+m[0].length;locator.lineNumber++;}
locator.columnNumber=p-lineStart+1;}
var lineStart=0;var lineEnd=0;var linePattern=/.*(?:\r\n?|\n)|.*$/g;var locator=domBuilder.locator;var parseStack=[{currentNSMap:defaultNSMapCopy}];var closeMap={};var start=0;while(true){try{var tagStart=source.indexOf('<',start);if(tagStart<0){if(!source.substr(start).match(/^\s*$/)){var doc=domBuilder.doc;var text=doc.createTextNode(source.substr(start));doc.appendChild(text);domBuilder.currentElement=text;}
return;}
if(tagStart>start){appendText(tagStart);}
switch(source.charAt(tagStart+1)){case'/':var end=source.indexOf('>',tagStart+3);var tagName=source.substring(tagStart+2,end);var config=parseStack.pop();if(end<0){tagName=source.substring(tagStart+2).replace(/[\s<].*/,'');errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);end=tagStart+1+tagName.length;}else if(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;var endMatch=config.tagName==tagName;var endIgnoreCaseMach=endMatch||config.tagName&&config.tagName.toLowerCase()==tagName.toLowerCase();if(endIgnoreCaseMach){domBuilder.endElement(config.uri,config.localName,tagName);if(localNSMap){for(var prefix in localNSMap){domBuilder.endPrefixMapping(prefix);}}
if(!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();var currentNSMap=parseStack[parseStack.length-1].currentNSMap;var end=parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);var len=el.length;if(!el.closed&&fixSelfClosed(source,end,el.tagName,closeMap)){el.closed=true;if(!entityMap.nbsp){errorHandler.warning('unclosed xml attribute');}}
if(locator&&len){var locator2=copyLocator(locator,{});for(var i=0;i<len;i++){var a=el[i];position(a.offset);a.locator=copyLocator(locator,{});}
domBuilder.locator=locator2;if(appendElement(el,domBuilder,currentNSMap)){parseStack.push(el);}
domBuilder.locator=locator;}else{if(appendElement(el,domBuilder,currentNSMap)){parseStack.push(el);}}
if(el.uri==='http://www.w3.org/1999/xhtml'&&!el.closed){end=parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder);}else{end++;}}}catch(e){errorHandler.error('element parse error: '+e);end=-1;}
if(end>start){start=end;}else{appendText(Math.max(tagStart,start)+1);}}}
function copyLocator(f,t){t.lineNumber=f.lineNumber;t.columnNumber=f.columnNumber;return t;}
function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){var attrName;var value;var p=++start;var s=S_TAG;while(true){var c=source.charAt(p);switch(c){case'=':if(s===S_ATTR){attrName=source.slice(start,p);s=S_EQ;}else if(s===S_ATTR_SPACE){s=S_EQ;}else{throw new Error('attribute equal must after attrName');}
break;case'\'':case'"':if(s===S_EQ||s===S_ATTR){if(s===S_ATTR){errorHandler.warning('attribute value must after "="');attrName=source.slice(start,p);}
start=p+1;p=source.indexOf(c,start);if(p>0){value=source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);el.add(attrName,value,start-1);s=S_ATTR_END;}else{throw new Error('attribute value no end \''+c+'\' match');}}else if(s==S_ATTR_NOQUOT_VALUE){value=source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);el.add(attrName,value,start);errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');start=p+1;s=S_ATTR_END;}else{throw new Error('attribute value must after "="');}
break;case'/':switch(s){case S_TAG:el.setTagName(source.slice(start,p));case S_ATTR_END:case S_TAG_SPACE:case S_TAG_CLOSE:s=S_TAG_CLOSE;el.closed=true;case S_ATTR_NOQUOT_VALUE:case S_ATTR:case S_ATTR_SPACE:break;default:throw new Error("attribute invalid close char('/')");}
break;case'':errorHandler.error('unexpected end of input');if(s==S_TAG){el.setTagName(source.slice(start,p));}
return p;case'>':switch(s){case S_TAG:el.setTagName(source.slice(start,p));case S_ATTR_END:case S_TAG_SPACE:case S_TAG_CLOSE:break;case S_ATTR_NOQUOT_VALUE:case S_ATTR:value=source.slice(start,p);if(value.slice(-1)==='/'){el.closed=true;value=value.slice(0,-1);}
case S_ATTR_SPACE:if(s===S_ATTR_SPACE){value=attrName;}
if(s==S_ATTR_NOQUOT_VALUE){errorHandler.warning('attribute "'+value+'" missed quot(")!!');el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start);}else{if(currentNSMap['']!=='http://www.w3.org/1999/xhtml'||!value.match(/^(?:disabled|checked|selected)$/i)){errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!');}
el.add(value,value,start);}
break;case S_EQ:throw new Error('attribute value missed!!');}
return p;case"\x80":c=' ';default:if(c<=' '){switch(s){case S_TAG:el.setTagName(source.slice(start,p));s=S_TAG_SPACE;break;case S_ATTR:attrName=source.slice(start,p);s=S_ATTR_SPACE;break;case S_ATTR_NOQUOT_VALUE:var value=source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);errorHandler.warning('attribute "'+value+'" missed quot(")!!');el.add(attrName,value,start);case S_ATTR_END:s=S_TAG_SPACE;break;}}else{switch(s){case S_ATTR_SPACE:var tagName=el.tagName;if(currentNSMap['']!=='http://www.w3.org/1999/xhtml'||!attrName.match(/^(?:disabled|checked|selected)$/i)){errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!');}
el.add(attrName,attrName,start);start=p;s=S_ATTR;break;case S_ATTR_END:errorHandler.warning('attribute space is required"'+attrName+'"!!');case S_TAG_SPACE:s=S_ATTR;start=p;break;case S_EQ:s=S_ATTR_NOQUOT_VALUE;start=p;break;case S_TAG_CLOSE:throw new Error("elements closed character '/' and '>' must be connected to");}}}
p++;}}
function appendElement(el,domBuilder,currentNSMap){var tagName=el.tagName;var localNSMap=null;var i=el.length;while(i--){var a=el[i];var qName=a.qName;var value=a.value;var nsp=qName.indexOf(':');if(nsp>0){var prefix=a.prefix=qName.slice(0,nsp);var localName=qName.slice(nsp+1);var nsPrefix=prefix==='xmlns'&&localName;}else{localName=qName;prefix=null;nsPrefix=qName==='xmlns'&&'';}
a.localName=localName;if(nsPrefix!==false){if(localNSMap==null){localNSMap={};_copy(currentNSMap,currentNSMap={});}
currentNSMap[nsPrefix]=localNSMap[nsPrefix]=value;a.uri='http://www.w3.org/2000/xmlns/';domBuilder.startPrefixMapping(nsPrefix,value);}}
var i=el.length;while(i--){a=el[i];var prefix=a.prefix;if(prefix){if(prefix==='xml'){a.uri='http://www.w3.org/XML/1998/namespace';}
if(prefix!=='xmlns'){a.uri=currentNSMap[prefix||''];}}}
var nsp=tagName.indexOf(':');if(nsp>0){prefix=el.prefix=tagName.slice(0,nsp);localName=el.localName=tagName.slice(nsp+1);}else{prefix=null;localName=el.localName=tagName;}
var ns=el.uri=currentNSMap[prefix||''];domBuilder.startElement(ns,localName,tagName,el);if(el.closed){domBuilder.endElement(ns,localName,tagName);if(localNSMap){for(prefix in localNSMap){domBuilder.endPrefixMapping(prefix);}}}else{el.currentNSMap=currentNSMap;el.localNSMap=localNSMap;return true;}}
function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){if(/^(?:script|textarea)$/i.test(tagName)){var elEndStart=source.indexOf('</'+tagName+'>',elStartEnd);var text=source.substring(elStartEnd+1,elEndStart);if(/[&<]/.test(text)){if(/^script$/i.test(tagName)){domBuilder.characters(text,0,text.length);return elEndStart;}
text=text.replace(/&#?\w+;/g,entityReplacer);domBuilder.characters(text,0,text.length);return elEndStart;}}
return elStartEnd+1;}
function fixSelfClosed(source,elStartEnd,tagName,closeMap){var pos=closeMap[tagName];if(pos==null){pos=source.lastIndexOf('</'+tagName+'>');if(pos<elStartEnd){pos=source.lastIndexOf('</'+tagName);}
closeMap[tagName]=pos;}
return pos<elStartEnd;}
function _copy(source,target){for(var n in source){target[n]=source[n];}}
function parseDCC(source,start,domBuilder,errorHandler){var next=source.charAt(start+2);switch(next){case'-':if(source.charAt(start+3)==='-'){var end=source.indexOf('-->',start+4);if(end>start){domBuilder.comment(source,start+4,end-start-4);return end+3;}else{errorHandler.error("Unclosed comment");return-1;}}else{return-1;}
default:if(source.substr(start+3,6)=='CDATA['){var end=source.indexOf(']]>',start+9);domBuilder.startCDATA();domBuilder.characters(source,start+9,end-start-9);domBuilder.endCDATA();return end+3;}
var matchs=split(source,start);var len=matchs.length;if(len>1&&/!doctype/i.test(matchs[0][0])){var name=matchs[1][0];var pubid=len>3&&/^public$/i.test(matchs[2][0])&&matchs[3][0];var sysid=len>4&&matchs[4][0];var lastMatch=matchs[len-1];domBuilder.startDTD(name,pubid&&pubid.replace(/^(['"])(.*?)\1$/,'$2'),sysid&&sysid.replace(/^(['"])(.*?)\1$/,'$2'));domBuilder.endDTD();return 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*$/);if(match){var len=match[0].length;domBuilder.processingInstruction(match[1],match[2]);return end+2;}else{return-1;}}
return-1;}
function ElementAttributes(source){}
ElementAttributes.prototype={setTagName:function setTagName(tagName){if(!tagNamePattern.test(tagName)){throw new Error('invalid tagName:'+tagName);}
this.tagName=tagName;},add:function add(qName,value,offset){if(!tagNamePattern.test(qName)){throw new Error('invalid attribute:'+qName);}
this[this.length++]={qName:qName,value:value,offset:offset};},length:0,getLocalName:function getLocalName(i){return this[i].localName;},getLocator:function getLocator(i){return this[i].locator;},getQName:function getQName(i){return this[i].qName;},getURI:function getURI(i){return this[i].uri;},getValue:function getValue(i){return this[i].value;}};function _set_proto_(thiz,parent){thiz.__proto__=parent;return thiz;}
if(!(_set_proto_({},_set_proto_.prototype)instanceof _set_proto_)){_set_proto_=function _set_proto_(thiz,parent){function p(){}
p.prototype=parent;p=new p();for(parent in thiz){p[parent]=thiz[parent];}
return p;};}
function split(source,start){var match;var buf=[];var reg=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;reg.lastIndex=start;reg.exec(source);while(match=reg.exec(source)){buf.push(match);if(match[1])return buf;}}
var XMLReader_1=XMLReader;var sax={XMLReader:XMLReader_1};function copy(src,dest){for(var p in src){dest[p]=src[p];}}
function _extends(Class,Super){var pt=Class.prototype;if(Object.create){var ppt=Object.create(Super.prototype);pt.__proto__=ppt;}
if(!(pt instanceof Super)){var t=function t(){};t.prototype=Super.prototype;t=new t();copy(pt,t);Class.prototype=pt=t;}
if(pt.constructor!=Class){if(typeof Class!='function'){console.error("unknow Class:"+Class);}
pt.constructor=Class;}}
var htmlns='http://www.w3.org/1999/xhtml';var NodeType={};var ELEMENT_NODE=NodeType.ELEMENT_NODE=1;var ATTRIBUTE_NODE=NodeType.ATTRIBUTE_NODE=2;var TEXT_NODE=NodeType.TEXT_NODE=3;var CDATA_SECTION_NODE=NodeType.CDATA_SECTION_NODE=4;var ENTITY_REFERENCE_NODE=NodeType.ENTITY_REFERENCE_NODE=5;var ENTITY_NODE=NodeType.ENTITY_NODE=6;var PROCESSING_INSTRUCTION_NODE=NodeType.PROCESSING_INSTRUCTION_NODE=7;var COMMENT_NODE=NodeType.COMMENT_NODE=8;var DOCUMENT_NODE=NodeType.DOCUMENT_NODE=9;var DOCUMENT_TYPE_NODE=NodeType.DOCUMENT_TYPE_NODE=10;var DOCUMENT_FRAGMENT_NODE=NodeType.DOCUMENT_FRAGMENT_NODE=11;var NOTATION_NODE=NodeType.NOTATION_NODE=12;var ExceptionCode={};var ExceptionMessage={};var INDEX_SIZE_ERR=ExceptionCode.INDEX_SIZE_ERR=(ExceptionMessage[1]="Index size error",1);var DOMSTRING_SIZE_ERR=ExceptionCode.DOMSTRING_SIZE_ERR=(ExceptionMessage[2]="DOMString size error",2);var HIERARCHY_REQUEST_ERR=ExceptionCode.HIERARCHY_REQUEST_ERR=(ExceptionMessage[3]="Hierarchy request error",3);var WRONG_DOCUMENT_ERR=ExceptionCode.WRONG_DOCUMENT_ERR=(ExceptionMessage[4]="Wrong document",4);var INVALID_CHARACTER_ERR=ExceptionCode.INVALID_CHARACTER_ERR=(ExceptionMessage[5]="Invalid character",5);var NO_DATA_ALLOWED_ERR=ExceptionCode.NO_DATA_ALLOWED_ERR=(ExceptionMessage[6]="No data allowed",6);var NO_MODIFICATION_ALLOWED_ERR=ExceptionCode.NO_MODIFICATION_ALLOWED_ERR=(ExceptionMessage[7]="No modification allowed",7);var NOT_FOUND_ERR=ExceptionCode.NOT_FOUND_ERR=(ExceptionMessage[8]="Not found",8);var NOT_SUPPORTED_ERR=ExceptionCode.NOT_SUPPORTED_ERR=(ExceptionMessage[9]="Not supported",9);var INUSE_ATTRIBUTE_ERR=ExceptionCode.INUSE_ATTRIBUTE_ERR=(ExceptionMessage[10]="Attribute in use",10);var INVALID_STATE_ERR=ExceptionCode.INVALID_STATE_ERR=(ExceptionMessage[11]="Invalid state",11);var SYNTAX_ERR=ExceptionCode.SYNTAX_ERR=(ExceptionMessage[12]="Syntax error",12);var INVALID_MODIFICATION_ERR=ExceptionCode.INVALID_MODIFICATION_ERR=(ExceptionMessage[13]="Invalid modification",13);var NAMESPACE_ERR=ExceptionCode.NAMESPACE_ERR=(ExceptionMessage[14]="Invalid namespace",14);var INVALID_ACCESS_ERR=ExceptionCode.INVALID_ACCESS_ERR=(ExceptionMessage[15]="Invalid access",15);function DOMException(code,message){if(message instanceof Error){var error=message;}else{error=this;Error.call(this,ExceptionMessage[code]);this.message=ExceptionMessage[code];if(Error.captureStackTrace)Error.captureStackTrace(this,DOMException);}
error.code=code;if(message)this.message=this.message+": "+message;return error;}
DOMException.prototype=Error.prototype;copy(ExceptionCode,DOMException);function NodeList(){}
NodeList.prototype={length:0,item:function item(index){return this[index]||null;},toString:function toString(isHTML,nodeFilter){for(var buf=[],i=0;i<this.length;i++){serializeToString(this[i],buf,isHTML,nodeFilter);}
return buf.join('');}};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);__set__(list,'length',ls.length);copy(ls,list);list._inc=inc;}}
LiveNodeList.prototype.item=function(i){_updateLiveList(this);return this[i];};_extends(LiveNodeList,NodeList);function NamedNodeMap(){}
function _findNodeIndex(list,node){var i=list.length;while(i--){if(list[i]===node){return i;}}}
function _addNamedNode(el,list,newAttr,oldAttr){if(oldAttr){list[_findNodeIndex(list,oldAttr)]=newAttr;}else{list[list.length++]=newAttr;}
if(el){newAttr.ownerElement=el;var doc=el.ownerDocument;if(doc){oldAttr&&_onRemoveAttribute(doc,el,oldAttr);_onAddAttribute(doc,el,newAttr);}}}
function _removeNamedNode(el,list,attr){var i=_findNodeIndex(list,attr);if(i>=0){var lastIndex=list.length-1;while(i<lastIndex){list[i]=list[++i];}
list.length=lastIndex;if(el){var doc=el.ownerDocument;if(doc){_onRemoveAttribute(doc,el,attr);attr.ownerElement=null;}}}else{throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr));}}
NamedNodeMap.prototype={length:0,item:NodeList.prototype.item,getNamedItem:function getNamedItem(key){var i=this.length;while(i--){var attr=this[i];if(attr.nodeName==key){return attr;}}},setNamedItem:function setNamedItem(attr){var el=attr.ownerElement;if(el&&el!=this._ownerElement){throw new DOMException(INUSE_ATTRIBUTE_ERR);}
var oldAttr=this.getNamedItem(attr.nodeName);_addNamedNode(this._ownerElement,this,attr,oldAttr);return oldAttr;},setNamedItemNS:function setNamedItemNS(attr){var el=attr.ownerElement,oldAttr;if(el&&el!=this._ownerElement){throw new DOMException(INUSE_ATTRIBUTE_ERR);}
oldAttr=this.getNamedItemNS(attr.namespaceURI,attr.localName);_addNamedNode(this._ownerElement,this,attr,oldAttr);return oldAttr;},removeNamedItem:function removeNamedItem(key){var attr=this.getNamedItem(key);_removeNamedNode(this._ownerElement,this,attr);return attr;},removeNamedItemNS:function removeNamedItemNS(namespaceURI,localName){var attr=this.getNamedItemNS(namespaceURI,localName);_removeNamedNode(this._ownerElement,this,attr);return attr;},getNamedItemNS:function getNamedItemNS(namespaceURI,localName){var i=this.length;while(i--){var node=this[i];if(node.localName==localName&&node.namespaceURI==namespaceURI){return node;}}
return null;}};function DOMImplementation(features){this._features={};if(features){for(var feature in features){this._features=features[feature];}}}
DOMImplementation.prototype={hasFeature:function hasFeature(feature,version){var versions=this._features[feature.toLowerCase()];if(versions&&(!version||version in versions)){return true;}else{return false;}},createDocument:function createDocument(namespaceURI,qualifiedName,doctype){var doc=new Document();doc.implementation=this;doc.childNodes=new NodeList();doc.doctype=doctype;if(doctype){doc.appendChild(doctype);}
if(qualifiedName){var root=doc.createElementNS(namespaceURI,qualifiedName);doc.appendChild(root);}
return doc;},createDocumentType:function createDocumentType(qualifiedName,publicId,systemId){var node=new DocumentType();node.name=qualifiedName;node.nodeName=qualifiedName;node.publicId=publicId;node.systemId=systemId;return node;}};function 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 insertBefore(newChild,refChild){return _insertBefore(this,newChild,refChild);},replaceChild:function replaceChild(newChild,oldChild){this.insertBefore(newChild,oldChild);if(oldChild){this.removeChild(oldChild);}},removeChild:function removeChild(oldChild){return _removeChild(this,oldChild);},appendChild:function appendChild(newChild){return this.insertBefore(newChild,null);},hasChildNodes:function hasChildNodes(){return this.firstChild!=null;},cloneNode:function cloneNode(deep){return _cloneNode(this.ownerDocument||this,this,deep);},normalize:function normalize(){var child=this.firstChild;while(child){var next=child.nextSibling;if(next&&next.nodeType==TEXT_NODE&&child.nodeType==TEXT_NODE){this.removeChild(next);child.appendData(next.data);}else{child.normalize();child=next;}}},isSupported:function isSupported(feature,version){return this.ownerDocument.implementation.hasFeature(feature,version);},hasAttributes:function hasAttributes(){return this.attributes.length>0;},lookupPrefix:function lookupPrefix(namespaceURI){var el=this;while(el){var map=el._nsMap;if(map){for(var n in map){if(map[n]==namespaceURI){return n;}}}
el=el.nodeType==ATTRIBUTE_NODE?el.ownerDocument:el.parentNode;}
return null;},lookupNamespaceURI:function lookupNamespaceURI(prefix){var el=this;while(el){var map=el._nsMap;if(map){if(prefix in map){return map[prefix];}}
el=el.nodeType==ATTRIBUTE_NODE?el.ownerDocument:el.parentNode;}
return null;},isDefaultNamespace:function isDefaultNamespace(namespaceURI){var prefix=this.lookupPrefix(namespaceURI);return prefix==null;}};function _xmlEncoder(c){return c=='<'&&'&lt;'||c=='>'&&'&gt;'||c=='&'&&'&amp;'||c=='"'&&'&quot;'||'&#'+c.charCodeAt()+';';}
copy(NodeType,Node);copy(NodeType,Node.prototype);function _visitNode(node,callback){if(callback(node)){return true;}
if(node=node.firstChild){do{if(_visitNode(node,callback)){return true;}}while(node=node.nextSibling);}}
function Document(){}
function _onAddAttribute(doc,el,newAttr){doc&&doc._inc++;var ns=newAttr.namespaceURI;if(ns=='http://www.w3.org/2000/xmlns/'){el._nsMap[newAttr.prefix?newAttr.localName:'']=newAttr.value;}}
function _onRemoveAttribute(doc,el,newAttr,remove){doc&&doc._inc++;var ns=newAttr.namespaceURI;if(ns=='http://www.w3.org/2000/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{var child=el.firstChild;var i=0;while(child){cs[i++]=child;child=child.nextSibling;}
cs.length=i;}}}
function _removeChild(parentNode,child){var previous=child.previousSibling;var next=child.nextSibling;if(previous){previous.nextSibling=next;}else{parentNode.firstChild=next;}
if(next){next.previousSibling=previous;}else{parentNode.lastChild=previous;}
_onUpdateChild(parentNode.ownerDocument,parentNode);return child;}
function _insertBefore(parentNode,newChild,nextChild){var cp=newChild.parentNode;if(cp){cp.removeChild(newChild);}
if(newChild.nodeType===DOCUMENT_FRAGMENT_NODE){var newFirst=newChild.firstChild;if(newFirst==null){return newChild;}
var newLast=newChild.lastChild;}else{newFirst=newLast=newChild;}
var pre=nextChild?nextChild.previousSibling:parentNode.lastChild;newFirst.previousSibling=pre;newLast.nextSibling=nextChild;if(pre){pre.nextSibling=newFirst;}else{parentNode.firstChild=newFirst;}
if(nextChild==null){parentNode.lastChild=newLast;}else{nextChild.previousSibling=newLast;}
do{newFirst.parentNode=parentNode;}while(newFirst!==newLast&&(newFirst=newFirst.nextSibling));_onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);if(newChild.nodeType==DOCUMENT_FRAGMENT_NODE){newChild.firstChild=newChild.lastChild=null;}
return newChild;}
function _appendSingleChild(parentNode,newChild){var cp=newChild.parentNode;if(cp){var pre=parentNode.lastChild;cp.removeChild(newChild);var pre=parentNode.lastChild;}
var pre=parentNode.lastChild;newChild.parentNode=parentNode;newChild.previousSibling=pre;newChild.nextSibling=null;if(pre){pre.nextSibling=newChild;}else{parentNode.firstChild=newChild;}
parentNode.lastChild=newChild;_onUpdateChild(parentNode.ownerDocument,parentNode,newChild);return newChild;}
Document.prototype={nodeName:'#document',nodeType:DOCUMENT_NODE,doctype:null,documentElement:null,_inc:1,insertBefore:function insertBefore(newChild,refChild){if(newChild.nodeType==DOCUMENT_FRAGMENT_NODE){var child=newChild.firstChild;while(child){var next=child.nextSibling;this.insertBefore(child,refChild);child=next;}
return newChild;}
if(this.documentElement==null&&newChild.nodeType==ELEMENT_NODE){this.documentElement=newChild;}
return _insertBefore(this,newChild,refChild),newChild.ownerDocument=this,newChild;},removeChild:function removeChild(oldChild){if(this.documentElement==oldChild){this.documentElement=null;}
return _removeChild(this,oldChild);},importNode:function importNode(importedNode,deep){return _importNode(this,importedNode,deep);},getElementById:function getElementById(id){var rtv=null;_visitNode(this.documentElement,function(node){if(node.nodeType==ELEMENT_NODE){if(node.getAttribute('id')==id){rtv=node;return true;}}});return rtv;},createElement:function createElement(tagName){var node=new Element();node.ownerDocument=this;node.nodeName=tagName;node.tagName=tagName;node.childNodes=new NodeList();var attrs=node.attributes=new NamedNodeMap();attrs._ownerElement=node;return node;},createDocumentFragment:function createDocumentFragment(){var node=new DocumentFragment();node.ownerDocument=this;node.childNodes=new NodeList();return node;},createTextNode:function createTextNode(data){var node=new Text();node.ownerDocument=this;node.appendData(data);return node;},createComment:function createComment(data){var node=new Comment();node.ownerDocument=this;node.appendData(data);return node;},createCDATASection:function createCDATASection(data){var node=new CDATASection();node.ownerDocument=this;node.appendData(data);return node;},createProcessingInstruction:function createProcessingInstruction(target,data){var node=new ProcessingInstruction();node.ownerDocument=this;node.tagName=node.target=target;node.nodeValue=node.data=data;return node;},createAttribute:function createAttribute(name){var node=new Attr();node.ownerDocument=this;node.name=name;node.nodeName=name;node.localName=name;node.specified=true;return node;},createEntityReference:function createEntityReference(name){var node=new EntityReference();node.ownerDocument=this;node.nodeName=name;return node;},createElementNS:function createElementNS(namespaceURI,qualifiedName){var node=new Element();var pl=qualifiedName.split(':');var attrs=node.attributes=new NamedNodeMap();node.childNodes=new NodeList();node.ownerDocument=this;node.nodeName=qualifiedName;node.tagName=qualifiedName;node.namespaceURI=namespaceURI;if(pl.length==2){node.prefix=pl[0];node.localName=pl[1];}else{node.localName=qualifiedName;}
attrs._ownerElement=node;return node;},createAttributeNS:function createAttributeNS(namespaceURI,qualifiedName){var node=new Attr();var pl=qualifiedName.split(':');node.ownerDocument=this;node.nodeName=qualifiedName;node.name=qualifiedName;node.namespaceURI=namespaceURI;node.specified=true;if(pl.length==2){node.prefix=pl[0];node.localName=pl[1];}else{node.localName=qualifiedName;}
return node;}};_extends(Document,Node);function Element(){this._nsMap={};}
Element.prototype={nodeType:ELEMENT_NODE,hasAttribute:function hasAttribute(name){return this.getAttributeNode(name)!=null;},getAttribute:function getAttribute(name){var attr=this.getAttributeNode(name);return attr&&attr.value||'';},getAttributeNode:function getAttributeNode(name){return this.attributes.getNamedItem(name);},setAttribute:function setAttribute(name,value){var attr=this.ownerDocument.createAttribute(name);attr.value=attr.nodeValue=""+value;this.setAttributeNode(attr);},removeAttribute:function removeAttribute(name){var attr=this.getAttributeNode(name);attr&&this.removeAttributeNode(attr);},appendChild:function appendChild(newChild){if(newChild.nodeType===DOCUMENT_FRAGMENT_NODE){return this.insertBefore(newChild,null);}else{return _appendSingleChild(this,newChild);}},setAttributeNode:function setAttributeNode(newAttr){return this.attributes.setNamedItem(newAttr);},setAttributeNodeNS:function setAttributeNodeNS(newAttr){return this.attributes.setNamedItemNS(newAttr);},removeAttributeNode:function removeAttributeNode(oldAttr){return this.attributes.removeNamedItem(oldAttr.nodeName);},removeAttributeNS:function removeAttributeNS(namespaceURI,localName){var old=this.getAttributeNodeNS(namespaceURI,localName);old&&this.removeAttributeNode(old);},hasAttributeNS:function hasAttributeNS(namespaceURI,localName){return this.getAttributeNodeNS(namespaceURI,localName)!=null;},getAttributeNS:function getAttributeNS(namespaceURI,localName){var attr=this.getAttributeNodeNS(namespaceURI,localName);return attr&&attr.value||'';},setAttributeNS:function setAttributeNS(namespaceURI,qualifiedName,value){var attr=this.ownerDocument.createAttributeNS(namespaceURI,qualifiedName);attr.value=attr.nodeValue=""+value;this.setAttributeNode(attr);},getAttributeNodeNS:function getAttributeNodeNS(namespaceURI,localName){return this.attributes.getNamedItemNS(namespaceURI,localName);},getElementsByTagName:function getElementsByTagName(tagName){return new LiveNodeList(this,function(base){var ls=[];_visitNode(base,function(node){if(node!==base&&node.nodeType==ELEMENT_NODE&&(tagName==='*'||node.tagName==tagName)){ls.push(node);}});return ls;});},getElementsByTagNameNS:function getElementsByTagNameNS(namespaceURI,localName){return new LiveNodeList(this,function(base){var ls=[];_visitNode(base,function(node){if(node!==base&&node.nodeType===ELEMENT_NODE&&(namespaceURI==='*'||node.namespaceURI===namespaceURI)&&(localName==='*'||node.localName==localName)){ls.push(node);}});return ls;});}};Document.prototype.getElementsByTagName=Element.prototype.getElementsByTagName;Document.prototype.getElementsByTagNameNS=Element.prototype.getElementsByTagNameNS;_extends(Element,Node);function Attr(){}
Attr.prototype.nodeType=ATTRIBUTE_NODE;_extends(Attr,Node);function CharacterData(){}
CharacterData.prototype={data:'',substringData:function substringData(offset,count){return this.data.substring(offset,offset+count);},appendData:function appendData(text){text=this.data+text;this.nodeValue=this.data=text;this.length=text.length;},insertData:function insertData(offset,text){this.replaceData(offset,0,text);},appendChild:function appendChild(newChild){throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]);},deleteData:function deleteData(offset,count){this.replaceData(offset,count,"");},replaceData:function replaceData(offset,count,text){var start=this.data.substring(0,offset);var end=this.data.substring(offset+count);text=start+text+end;this.nodeValue=this.data=text;this.length=text.length;}};_extends(CharacterData,Node);function Text(){}
Text.prototype={nodeName:"#text",nodeType:TEXT_NODE,splitText:function splitText(offset){var text=this.data;var newText=text.substring(offset);text=text.substring(0,offset);this.data=this.nodeValue=text;this.length=text.length;var newNode=this.ownerDocument.createTextNode(newText);if(this.parentNode){this.parentNode.insertBefore(newNode,this.nextSibling);}
return newNode;}};_extends(Text,CharacterData);function Comment(){}
Comment.prototype={nodeName:"#comment",nodeType:COMMENT_NODE};_extends(Comment,CharacterData);function CDATASection(){}
CDATASection.prototype={nodeName:"#cdata-section",nodeType:CDATA_SECTION_NODE};_extends(CDATASection,CharacterData);function DocumentType(){}
DocumentType.prototype.nodeType=DOCUMENT_TYPE_NODE;_extends(DocumentType,Node);function Notation(){}
Notation.prototype.nodeType=NOTATION_NODE;_extends(Notation,Node);function Entity(){}
Entity.prototype.nodeType=ENTITY_NODE;_extends(Entity,Node);function EntityReference(){}
EntityReference.prototype.nodeType=ENTITY_REFERENCE_NODE;_extends(EntityReference,Node);function DocumentFragment(){}
DocumentFragment.prototype.nodeName="#document-fragment";DocumentFragment.prototype.nodeType=DOCUMENT_FRAGMENT_NODE;_extends(DocumentFragment,Node);function ProcessingInstruction(){}
ProcessingInstruction.prototype.nodeType=PROCESSING_INSTRUCTION_NODE;_extends(ProcessingInstruction,Node);function XMLSerializer(){}
XMLSerializer.prototype.serializeToString=function(node,isHtml,nodeFilter){return nodeSerializeToString.call(node,isHtml,nodeFilter);};Node.prototype.toString=nodeSerializeToString;function nodeSerializeToString(isHtml,nodeFilter){var buf=[];var refNode=this.nodeType==9?this.documentElement:this;var prefix=refNode.prefix;var uri=refNode.namespaceURI;if(uri&&prefix==null){var prefix=refNode.lookupPrefix(uri);if(prefix==null){var visibleNamespaces=[{namespace:uri,prefix:null}];}}
serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);return buf.join('');}
function needNamespaceDefine(node,isHTML,visibleNamespaces){var prefix=node.prefix||'';var uri=node.namespaceURI;if(!prefix&&!uri){return false;}
if(prefix==="xml"&&uri==="http://www.w3.org/XML/1998/namespace"||uri=='http://www.w3.org/2000/xmlns/'){return false;}
var i=visibleNamespaces.length;while(i--){var ns=visibleNamespaces[i];if(ns.prefix==prefix){return ns.namespace!=uri;}}
return true;}
function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){if(nodeFilter){node=nodeFilter(node);if(node){if(typeof node=='string'){buf.push(node);return;}}else{return;}}
switch(node.nodeType){case ELEMENT_NODE:if(!visibleNamespaces)visibleNamespaces=[];var startVisibleNamespaces=visibleNamespaces.length;var attrs=node.attributes;var len=attrs.length;var child=node.firstChild;var nodeName=node.tagName;isHTML=htmlns===node.namespaceURI||isHTML;buf.push('<',nodeName);for(var i=0;i<len;i++){var attr=attrs.item(i);if(attr.prefix=='xmlns'){visibleNamespaces.push({prefix:attr.localName,namespace:attr.value});}else if(attr.nodeName=='xmlns'){visibleNamespaces.push({prefix:'',namespace:attr.value});}}
for(var i=0;i<len;i++){var attr=attrs.item(i);if(needNamespaceDefine(attr,isHTML,visibleNamespaces)){var prefix=attr.prefix||'';var uri=attr.namespaceURI;var ns=prefix?' xmlns:'+prefix:" xmlns";buf.push(ns,'="',uri,'"');visibleNamespaces.push({prefix:prefix,namespace:uri});}
serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);}
if(needNamespaceDefine(node,isHTML,visibleNamespaces)){var prefix=node.prefix||'';var uri=node.namespaceURI;var ns=prefix?' xmlns:'+prefix:" xmlns";buf.push(ns,'="',uri,'"');visibleNamespaces.push({prefix:prefix,namespace:uri});}
if(child||isHTML&&!/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){buf.push('>');if(isHTML&&/^script$/i.test(nodeName)){while(child){if(child.data){buf.push(child.data);}else{serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);}
child=child.nextSibling;}}else{while(child){serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);child=child.nextSibling;}}
buf.push('</',nodeName,'>');}else{buf.push('/>');}
return;case DOCUMENT_NODE:case DOCUMENT_FRAGMENT_NODE:var child=node.firstChild;while(child){serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);child=child.nextSibling;}
return;case ATTRIBUTE_NODE:return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"');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("<!--",node.data,"-->");case DOCUMENT_TYPE_NODE:var pubid=node.publicId;var sysid=node.systemId;buf.push('<!DOCTYPE ',node.name);if(pubid){buf.push(' PUBLIC "',pubid);if(sysid&&sysid!='.'){buf.push('" "',sysid);}
buf.push('">');}else if(sysid&&sysid!='.'){buf.push(' SYSTEM "',sysid,'">');}else{var sub=node.internalSubset;if(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(false);node2.ownerDocument=doc;case DOCUMENT_FRAGMENT_NODE:break;case ATTRIBUTE_NODE:deep=true;break;}
if(!node2){node2=node.cloneNode(false);}
node2.ownerDocument=doc;node2.parentNode=null;if(deep){var child=node.firstChild;while(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){var v=node[n];if(typeof v!='object'){if(v!=node2[n]){node2[n]=v;}}}
if(node.childNodes){node2.childNodes=new NodeList();}
node2.ownerDocument=doc;switch(node2.nodeType){case ELEMENT_NODE:var attrs=node.attributes;var attrs2=node2.attributes=new NamedNodeMap();var len=attrs.length;attrs2._ownerElement=node2;for(var i=0;i<len;i++){node2.setAttributeNode(_cloneNode(doc,attrs.item(i),true));}
break;case ATTRIBUTE_NODE:deep=true;}
if(deep){var child=node.firstChild;while(child){node2.appendChild(_cloneNode(doc,child,deep));child=child.nextSibling;}}
return node2;}
function __set__(object,key,value){object[key]=value;}
try{if(Object.defineProperty){var getTextContent=function getTextContent(node){switch(node.nodeType){case ELEMENT_NODE:case DOCUMENT_FRAGMENT_NODE:var buf=[];node=node.firstChild;while(node){if(node.nodeType!==7&&node.nodeType!==8){buf.push(getTextContent(node));}
node=node.nextSibling;}
return buf.join('');default:return node.nodeValue;}};Object.defineProperty(LiveNodeList.prototype,'length',{get:function get(){_updateLiveList(this);return this.$$length;}});Object.defineProperty(Node.prototype,'textContent',{get:function get(){return getTextContent(this);},set:function set(data){switch(this.nodeType){case ELEMENT_NODE:case DOCUMENT_FRAGMENT_NODE:while(this.firstChild){this.removeChild(this.firstChild);}
if(data||String(data)){this.appendChild(this.ownerDocument.createTextNode(data));}
break;default:this.data=data;this.value=data;this.nodeValue=data;}}});__set__=function __set__(object,key,value){object['$$'+key]=value;};}}catch(e){}
var DOMImplementation_1=DOMImplementation;var XMLSerializer_1=XMLSerializer;var dom={DOMImplementation:DOMImplementation_1,XMLSerializer:XMLSerializer_1};var domParser=createCommonjsModule(function(module,exports){function DOMParser(options){this.options=options||{locator:{}};}
DOMParser.prototype.parseFromString=function(source,mimeType){var options=this.options;var sax=new XMLReader();var domBuilder=options.domBuilder||new DOMHandler();var errorHandler=options.errorHandler;var locator=options.locator;var defaultNSMap=options.xmlns||{};var entityMap={'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"};if(locator){domBuilder.setDocumentLocator(locator);}
sax.errorHandler=buildErrorHandler(errorHandler,domBuilder,locator);sax.domBuilder=options.domBuilder||domBuilder;if(/\/x?html?$/.test(mimeType)){entityMap.nbsp='\xa0';entityMap.copy='\xa9';defaultNSMap['']='http://www.w3.org/1999/xhtml';}
defaultNSMap.xml=defaultNSMap.xml||'http://www.w3.org/XML/1998/namespace';if(source){sax.parse(source,defaultNSMap,entityMap);}else{sax.errorHandler.error("invalid doc source");}
return domBuilder.doc;};function buildErrorHandler(errorImpl,domBuilder,locator){if(!errorImpl){if(domBuilder instanceof DOMHandler){return domBuilder;}
errorImpl=domBuilder;}
var errorHandler={};var isCallback=errorImpl instanceof Function;locator=locator||{};function build(key){var fn=errorImpl[key];if(!fn&&isCallback){fn=errorImpl.length==2?function(msg){errorImpl(key,msg);}:errorImpl;}
errorHandler[key]=fn&&function(msg){fn('[xmldom '+key+']\t'+msg+_locator(locator));}||function(){};}
build('warning');build('error');build('fatalError');return errorHandler;}
function DOMHandler(){this.cdata=false;}
function position(locator,node){node.lineNumber=locator.lineNumber;node.columnNumber=locator.columnNumber;}
DOMHandler.prototype={startDocument:function startDocument(){this.doc=new DOMImplementation().createDocument(null,null,null);if(this.locator){this.doc.documentURI=this.locator.systemId;}},startElement:function startElement(namespaceURI,localName,qName,attrs){var doc=this.doc;var el=doc.createElementNS(namespaceURI,qName||localName);var len=attrs.length;appendElement(this,el);this.currentElement=el;this.locator&&position(this.locator,el);for(var i=0;i<len;i++){var namespaceURI=attrs.getURI(i);var value=attrs.getValue(i);var qName=attrs.getQName(i);var attr=doc.createAttributeNS(namespaceURI,qName);this.locator&&position(attrs.getLocator(i),attr);attr.value=attr.nodeValue=value;el.setAttributeNode(attr);}},endElement:function endElement(namespaceURI,localName,qName){var current=this.currentElement;var tagName=current.tagName;this.currentElement=current.parentNode;},startPrefixMapping:function startPrefixMapping(prefix,uri){},endPrefixMapping:function endPrefixMapping(prefix){},processingInstruction:function processingInstruction(target,data){var ins=this.doc.createProcessingInstruction(target,data);this.locator&&position(this.locator,ins);appendElement(this,ins);},ignorableWhitespace:function ignorableWhitespace(ch,start,length){},characters:function characters(chars,start,length){chars=_toString.apply(this,arguments);if(chars){if(this.cdata){var charNode=this.doc.createCDATASection(chars);}else{var charNode=this.doc.createTextNode(chars);}
if(this.currentElement){this.currentElement.appendChild(charNode);}else if(/^\s*$/.test(chars)){this.doc.appendChild(charNode);}
this.locator&&position(this.locator,charNode);}},skippedEntity:function skippedEntity(name){},endDocument:function endDocument(){this.doc.normalize();},setDocumentLocator:function setDocumentLocator(locator){if(this.locator=locator){locator.lineNumber=0;}},comment:function comment(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 startCDATA(){this.cdata=true;},endCDATA:function endCDATA(){this.cdata=false;},startDTD:function startDTD(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);}},warning:function warning(error){console.warn('[xmldom warning]\t'+error,_locator(this.locator));},error:function error(_error){console.error('[xmldom error]\t'+_error,_locator(this.locator));},fatalError:function fatalError(error){console.error('[xmldom fatalError]\t'+error,_locator(this.locator));throw error;}};function _locator(l){if(l){return'\n@'+(l.systemId||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']';}}
function _toString(chars,start,length){if(typeof chars=='string'){return chars.substr(start,length);}else{if(chars.length>=start+length||start){return new java.lang.String(chars,start,length)+'';}
return chars;}}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){DOMHandler.prototype[key]=function(){return null;};});function appendElement(hander,node){if(!hander.currentElement){hander.doc.appendChild(node);}else{hander.currentElement.appendChild(node);}}
var XMLReader=sax.XMLReader;var DOMImplementation=exports.DOMImplementation=dom.DOMImplementation;exports.XMLSerializer=dom.XMLSerializer;exports.DOMParser=DOMParser;});var domParser_1=domParser.DOMImplementation;var domParser_2=domParser.XMLSerializer;var domParser_3=domParser.DOMParser;var isObject$1=function isObject(obj){return!!obj&&typeof obj==='object';};var merge=function merge(){for(var _len=arguments.length,objects=new Array(_len),_key=0;_key<_len;_key++){objects[_key]=arguments[_key];}
return objects.reduce(function(result,source){if(typeof source!=='object'){return result;}
Object.keys(source).forEach(function(key){if(Array.isArray(result[key])&&Array.isArray(source[key])){result[key]=result[key].concat(source[key]);}else if(isObject$1(result[key])&&isObject$1(source[key])){result[key]=merge(result[key],source[key]);}else{result[key]=source[key];}});return result;},{});};var values=function values(o){return Object.keys(o).map(function(k){return o[k];});};var range=function range(start,end){var result=[];for(var i=start;i<end;i++){result.push(i);}
return result;};var flatten=function flatten(lists){return lists.reduce(function(x,y){return x.concat(y);},[]);};var from=function from(list){if(!list.length){return[];}
var result=[];for(var i=0;i<list.length;i++){result.push(list[i]);}
return result;};var findIndexes=function findIndexes(l,key){return l.reduce(function(a,e,i){if(e[key]){a.push(i);}
return a;},[]);};var errors={INVALID_NUMBER_OF_PERIOD:'INVALID_NUMBER_OF_PERIOD',DASH_EMPTY_MANIFEST:'DASH_EMPTY_MANIFEST',DASH_INVALID_XML:'DASH_INVALID_XML',NO_BASE_URL:'NO_BASE_URL',MISSING_SEGMENT_INFORMATION:'MISSING_SEGMENT_INFORMATION',SEGMENT_TIME_UNSPECIFIED:'SEGMENT_TIME_UNSPECIFIED',UNSUPPORTED_UTC_TIMING_SCHEME:'UNSUPPORTED_UTC_TIMING_SCHEME'};var urlTypeToSegment=function urlTypeToSegment(_ref){var _ref$baseUrl=_ref.baseUrl,baseUrl=_ref$baseUrl===void 0?'':_ref$baseUrl,_ref$source=_ref.source,source=_ref$source===void 0?'':_ref$source,_ref$range=_ref.range,range=_ref$range===void 0?'':_ref$range,_ref$indexRange=_ref.indexRange,indexRange=_ref$indexRange===void 0?'':_ref$indexRange;var segment={uri:source,resolvedUri:resolveUrl_1(baseUrl||'',source)};if(range||indexRange){var rangeStr=range?range:indexRange;var ranges=rangeStr.split('-');var startRange=parseInt(ranges[0],10);var endRange=parseInt(ranges[1],10);segment.byterange={length:endRange-startRange+1,offset:startRange};}
return segment;};var byteRangeToString=function byteRangeToString(byterange){var endRange=byterange.offset+byterange.length-1;return byterange.offset+"-"+endRange;};var segmentRange={"static":function _static(attributes){var duration=attributes.duration,_attributes$timescale=attributes.timescale,timescale=_attributes$timescale===void 0?1:_attributes$timescale,sourceDuration=attributes.sourceDuration;return{start:0,end:Math.ceil(sourceDuration/(duration/timescale))};},dynamic:function dynamic(attributes){var NOW=attributes.NOW,clientOffset=attributes.clientOffset,availabilityStartTime=attributes.availabilityStartTime,_attributes$timescale2=attributes.timescale,timescale=_attributes$timescale2===void 0?1:_attributes$timescale2,duration=attributes.duration,_attributes$start=attributes.start,start=_attributes$start===void 0?0:_attributes$start,_attributes$minimumUp=attributes.minimumUpdatePeriod,minimumUpdatePeriod=_attributes$minimumUp===void 0?0:_attributes$minimumUp,_attributes$timeShift=attributes.timeShiftBufferDepth,timeShiftBufferDepth=_attributes$timeShift===void 0?Infinity:_attributes$timeShift;var now=(NOW+clientOffset)/1000;var periodStartWC=availabilityStartTime+start;var periodEndWC=now+minimumUpdatePeriod;var periodDuration=periodEndWC-periodStartWC;var segmentCount=Math.ceil(periodDuration*timescale/duration);var availableStart=Math.floor((now-periodStartWC-timeShiftBufferDepth)*timescale/duration);var availableEnd=Math.floor((now-periodStartWC)*timescale/duration);return{start:Math.max(0,availableStart),end:Math.min(segmentCount,availableEnd)};}};var toSegments=function toSegments(attributes){return function(number,index){var duration=attributes.duration,_attributes$timescale3=attributes.timescale,timescale=_attributes$timescale3===void 0?1:_attributes$timescale3,periodIndex=attributes.periodIndex,_attributes$startNumb=attributes.startNumber,startNumber=_attributes$startNumb===void 0?1:_attributes$startNumb;return{number:startNumber+number,duration:duration/timescale,timeline:periodIndex,time:index*duration};};};var parseByDuration=function parseByDuration(attributes){var _attributes$type=attributes.type,type=_attributes$type===void 0?'static':_attributes$type,duration=attributes.duration,_attributes$timescale4=attributes.timescale,timescale=_attributes$timescale4===void 0?1:_attributes$timescale4,sourceDuration=attributes.sourceDuration;var _segmentRange$type=segmentRange[type](attributes),start=_segmentRange$type.start,end=_segmentRange$type.end;var segments=range(start,end).map(toSegments(attributes));if(type==='static'){var index=segments.length-1;segments[index].duration=sourceDuration-duration/timescale*index;}
return segments;};var segmentsFromBase=function segmentsFromBase(attributes){var baseUrl=attributes.baseUrl,_attributes$initializ=attributes.initialization,initialization=_attributes$initializ===void 0?{}:_attributes$initializ,sourceDuration=attributes.sourceDuration,_attributes$indexRang=attributes.indexRange,indexRange=_attributes$indexRang===void 0?'':_attributes$indexRang,duration=attributes.duration;if(!baseUrl){throw new Error(errors.NO_BASE_URL);}
var initSegment=urlTypeToSegment({baseUrl:baseUrl,source:initialization.sourceURL,range:initialization.range});var segment=urlTypeToSegment({baseUrl:baseUrl,source:baseUrl,indexRange:indexRange});segment.map=initSegment;if(duration){var segmentTimeInfo=parseByDuration(attributes);if(segmentTimeInfo.length){segment.duration=segmentTimeInfo[0].duration;segment.timeline=segmentTimeInfo[0].timeline;}}else if(sourceDuration){segment.duration=sourceDuration;segment.timeline=0;}
segment.number=0;return[segment];};var addSegmentsToPlaylist=function addSegmentsToPlaylist(playlist,sidx,baseUrl){var initSegment=playlist.sidx.map?playlist.sidx.map:null;var sourceDuration=playlist.sidx.duration;var timeline=playlist.timeline||0;var sidxByteRange=playlist.sidx.byterange;var sidxEnd=sidxByteRange.offset+sidxByteRange.length;var timescale=sidx.timescale;var mediaReferences=sidx.references.filter(function(r){return r.referenceType!==1;});var segments=[];var startIndex=sidxEnd+sidx.firstOffset;for(var i=0;i<mediaReferences.length;i++){var reference=sidx.references[i];var size=reference.referencedSize;var duration=reference.subsegmentDuration;var endIndex=startIndex+size-1;var indexRange=startIndex+"-"+endIndex;var attributes={baseUrl:baseUrl,timescale:timescale,timeline:timeline,periodIndex:timeline,duration:duration,sourceDuration:sourceDuration,indexRange:indexRange};var segment=segmentsFromBase(attributes)[0];if(initSegment){segment.map=initSegment;}
segments.push(segment);startIndex+=size;}
playlist.segments=segments;return playlist;};var mergeDiscontiguousPlaylists=function mergeDiscontiguousPlaylists(playlists){var mergedPlaylists=values(playlists.reduce(function(acc,playlist){var name=playlist.attributes.id+(playlist.attributes.lang||'');if(acc[name]){var _acc$name$segments;if(playlist.segments[0]){playlist.segments[0].discontinuity=true;}
(_acc$name$segments=acc[name].segments).push.apply(_acc$name$segments,playlist.segments);if(playlist.attributes.contentProtection){acc[name].attributes.contentProtection=playlist.attributes.contentProtection;}}else{acc[name]=playlist;}
return acc;},{}));return mergedPlaylists.map(function(playlist){playlist.discontinuityStarts=findIndexes(playlist.segments,'discontinuity');return playlist;});};var addSegmentInfoFromSidx=function addSegmentInfoFromSidx(playlists,sidxMapping){if(sidxMapping===void 0){sidxMapping={};}
if(!Object.keys(sidxMapping).length){return playlists;}
for(var i in playlists){var playlist=playlists[i];if(!playlist.sidx){continue;}
var sidxKey=playlist.sidx.uri+'-'+byteRangeToString(playlist.sidx.byterange);var sidxMatch=sidxMapping[sidxKey]&&sidxMapping[sidxKey].sidx;if(playlist.sidx&&sidxMatch){addSegmentsToPlaylist(playlist,sidxMatch,playlist.sidx.resolvedUri);}}
return playlists;};var formatAudioPlaylist=function formatAudioPlaylist(_ref){var _attributes;var attributes=_ref.attributes,segments=_ref.segments,sidx=_ref.sidx;var playlist={attributes:(_attributes={NAME:attributes.id,BANDWIDTH:attributes.bandwidth,CODECS:attributes.codecs},_attributes['PROGRAM-ID']=1,_attributes),uri:'',endList:(attributes.type||'static')==='static',timeline:attributes.periodIndex,resolvedUri:'',targetDuration:attributes.duration,segments:segments,mediaSequence:segments.length?segments[0].number:1};if(attributes.contentProtection){playlist.contentProtection=attributes.contentProtection;}
if(sidx){playlist.sidx=sidx;}
return playlist;};var formatVttPlaylist=function formatVttPlaylist(_ref2){var _m3u8Attributes;var attributes=_ref2.attributes,segments=_ref2.segments;if(typeof segments==='undefined'){segments=[{uri:attributes.baseUrl,timeline:attributes.periodIndex,resolvedUri:attributes.baseUrl||'',duration:attributes.sourceDuration,number:0}];attributes.duration=attributes.sourceDuration;}
var m3u8Attributes=(_m3u8Attributes={NAME:attributes.id,BANDWIDTH:attributes.bandwidth},_m3u8Attributes['PROGRAM-ID']=1,_m3u8Attributes);if(attributes.codecs){m3u8Attributes.CODECS=attributes.codecs;}
return{attributes:m3u8Attributes,uri:'',endList:(attributes.type||'static')==='static',timeline:attributes.periodIndex,resolvedUri:attributes.baseUrl||'',targetDuration:attributes.duration,segments:segments,mediaSequence:segments.length?segments[0].number:1};};var organizeAudioPlaylists=function organizeAudioPlaylists(playlists,sidxMapping){if(sidxMapping===void 0){sidxMapping={};}
var mainPlaylist;var formattedPlaylists=playlists.reduce(function(a,playlist){var role=playlist.attributes.role&&playlist.attributes.role.value||'';var language=playlist.attributes.lang||'';var label='main';if(language){var roleLabel=role?" ("+role+")":'';label=""+playlist.attributes.lang+roleLabel;}
if(a[label]&&a[label].playlists[0].attributes.BANDWIDTH>playlist.attributes.bandwidth){return a;}
a[label]={language:language,autoselect:true,"default":role==='main',playlists:addSegmentInfoFromSidx([formatAudioPlaylist(playlist)],sidxMapping),uri:''};if(typeof mainPlaylist==='undefined'&&role==='main'){mainPlaylist=playlist;mainPlaylist["default"]=true;}
return a;},{});if(!mainPlaylist){var firstLabel=Object.keys(formattedPlaylists)[0];formattedPlaylists[firstLabel]["default"]=true;}
return formattedPlaylists;};var organizeVttPlaylists=function organizeVttPlaylists(playlists,sidxMapping){if(sidxMapping===void 0){sidxMapping={};}
return playlists.reduce(function(a,playlist){var label=playlist.attributes.lang||'text';if(a[label]){return a;}
a[label]={language:label,"default":false,autoselect:false,playlists:addSegmentInfoFromSidx([formatVttPlaylist(playlist)],sidxMapping),uri:''};return a;},{});};var formatVideoPlaylist=function formatVideoPlaylist(_ref3){var _attributes2;var attributes=_ref3.attributes,segments=_ref3.segments,sidx=_ref3.sidx;var playlist={attributes:(_attributes2={NAME:attributes.id,AUDIO:'audio',SUBTITLES:'subs',RESOLUTION:{width:attributes.width,height:attributes.height},CODECS:attributes.codecs,BANDWIDTH:attributes.bandwidth},_attributes2['PROGRAM-ID']=1,_attributes2),uri:'',endList:(attributes.type||'static')==='static',timeline:attributes.periodIndex,resolvedUri:'',targetDuration:attributes.duration,segments:segments,mediaSequence:segments.length?segments[0].number:1};if(attributes.contentProtection){playlist.contentProtection=attributes.contentProtection;}
if(sidx){playlist.sidx=sidx;}
return playlist;};var toM3u8=function toM3u8(dashPlaylists,locations,sidxMapping){var _mediaGroups;if(sidxMapping===void 0){sidxMapping={};}
if(!dashPlaylists.length){return{};}
var _dashPlaylists$0$attr=dashPlaylists[0].attributes,duration=_dashPlaylists$0$attr.sourceDuration,_dashPlaylists$0$attr2=_dashPlaylists$0$attr.type,type=_dashPlaylists$0$attr2===void 0?'static':_dashPlaylists$0$attr2,suggestedPresentationDelay=_dashPlaylists$0$attr.suggestedPresentationDelay,minimumUpdatePeriod=_dashPlaylists$0$attr.minimumUpdatePeriod;var videoOnly=function videoOnly(_ref4){var attributes=_ref4.attributes;return attributes.mimeType==='video/mp4'||attributes.mimeType==='video/webm'||attributes.contentType==='video';};var audioOnly=function audioOnly(_ref5){var attributes=_ref5.attributes;return attributes.mimeType==='audio/mp4'||attributes.mimeType==='audio/webm'||attributes.contentType==='audio';};var vttOnly=function vttOnly(_ref6){var attributes=_ref6.attributes;return attributes.mimeType==='text/vtt'||attributes.contentType==='text';};var videoPlaylists=mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);var audioPlaylists=mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));var vttPlaylists=dashPlaylists.filter(vttOnly);var master={allowCache:true,discontinuityStarts:[],segments:[],endList:true,mediaGroups:(_mediaGroups={AUDIO:{},VIDEO:{}},_mediaGroups['CLOSED-CAPTIONS']={},_mediaGroups.SUBTITLES={},_mediaGroups),uri:'',duration:duration,playlists:addSegmentInfoFromSidx(videoPlaylists,sidxMapping)};if(minimumUpdatePeriod>=0){master.minimumUpdatePeriod=minimumUpdatePeriod*1000;}
if(locations){master.locations=locations;}
if(type==='dynamic'){master.suggestedPresentationDelay=suggestedPresentationDelay;}
if(audioPlaylists.length){master.mediaGroups.AUDIO.audio=organizeAudioPlaylists(audioPlaylists,sidxMapping);}
if(vttPlaylists.length){master.mediaGroups.SUBTITLES.subs=organizeVttPlaylists(vttPlaylists,sidxMapping);}
return master;};var getLiveRValue=function getLiveRValue(attributes,time,duration){var NOW=attributes.NOW,clientOffset=attributes.clientOffset,availabilityStartTime=attributes.availabilityStartTime,_attributes$timescale=attributes.timescale,timescale=_attributes$timescale===void 0?1:_attributes$timescale,_attributes$start=attributes.start,start=_attributes$start===void 0?0:_attributes$start,_attributes$minimumUp=attributes.minimumUpdatePeriod,minimumUpdatePeriod=_attributes$minimumUp===void 0?0:_attributes$minimumUp;var now=(NOW+clientOffset)/1000;var periodStartWC=availabilityStartTime+start;var periodEndWC=now+minimumUpdatePeriod;var periodDuration=periodEndWC-periodStartWC;return Math.ceil((periodDuration*timescale-time)/duration);};var parseByTimeline=function parseByTimeline(attributes,segmentTimeline){var _attributes$type=attributes.type,type=_attributes$type===void 0?'static':_attributes$type,_attributes$minimumUp2=attributes.minimumUpdatePeriod,minimumUpdatePeriod=_attributes$minimumUp2===void 0?0:_attributes$minimumUp2,_attributes$media=attributes.media,media=_attributes$media===void 0?'':_attributes$media,sourceDuration=attributes.sourceDuration,_attributes$timescale2=attributes.timescale,timescale=_attributes$timescale2===void 0?1:_attributes$timescale2,_attributes$startNumb=attributes.startNumber,startNumber=_attributes$startNumb===void 0?1:_attributes$startNumb,timeline=attributes.periodIndex;var segments=[];var time=-1;for(var sIndex=0;sIndex<segmentTimeline.length;sIndex++){var S=segmentTimeline[sIndex];var duration=S.d;var repeat=S.r||0;var segmentTime=S.t||0;if(time<0){time=segmentTime;}
if(segmentTime&&segmentTime>time){time=segmentTime;}
var count=void 0;if(repeat<0){var nextS=sIndex+1;if(nextS===segmentTimeline.length){if(type==='dynamic'&&minimumUpdatePeriod>0&&media.indexOf('$Number$')>0){count=getLiveRValue(attributes,time,duration);}else{count=(sourceDuration*timescale-time)/duration;}}else{count=(segmentTimeline[nextS].t-time)/duration;}}else{count=repeat+1;}
var end=startNumber+segments.length+count;var number=startNumber+segments.length;while(number<end){segments.push({number:number,duration:duration/timescale,time:time,timeline:timeline});time+=duration;number++;}}
return segments;};var identifierPattern=/\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g;var identifierReplacement=function identifierReplacement(values){return function(match,identifier,format,width){if(match==='$$'){return'$';}
if(typeof values[identifier]==='undefined'){return match;}
var value=''+values[identifier];if(identifier==='RepresentationID'){return value;}
if(!format){width=1;}else{width=parseInt(width,10);}
if(value.length>=width){return value;}
return""+new Array(width-value.length+1).join('0')+value;};};var constructTemplateUrl=function constructTemplateUrl(url,values){return url.replace(identifierPattern,identifierReplacement(values));};var parseTemplateInfo=function parseTemplateInfo(attributes,segmentTimeline){if(!attributes.duration&&!segmentTimeline){return[{number:attributes.startNumber||1,duration:attributes.sourceDuration,time:0,timeline:attributes.periodIndex}];}
if(attributes.duration){return parseByDuration(attributes);}
return parseByTimeline(attributes,segmentTimeline);};var segmentsFromTemplate=function segmentsFromTemplate(attributes,segmentTimeline){var templateValues={RepresentationID:attributes.id,Bandwidth:attributes.bandwidth||0};var _attributes$initializ=attributes.initialization,initialization=_attributes$initializ===void 0?{sourceURL:'',range:''}:_attributes$initializ;var mapSegment=urlTypeToSegment({baseUrl:attributes.baseUrl,source:constructTemplateUrl(initialization.sourceURL,templateValues),range:initialization.range});var segments=parseTemplateInfo(attributes,segmentTimeline);return segments.map(function(segment){templateValues.Number=segment.number;templateValues.Time=segment.time;var uri=constructTemplateUrl(attributes.media||'',templateValues);return{uri:uri,timeline:segment.timeline,duration:segment.duration,resolvedUri:resolveUrl_1(attributes.baseUrl||'',uri),map:mapSegment,number:segment.number};});};var SegmentURLToSegmentObject=function SegmentURLToSegmentObject(attributes,segmentUrl){var baseUrl=attributes.baseUrl,_attributes$initializ=attributes.initialization,initialization=_attributes$initializ===void 0?{}:_attributes$initializ;var initSegment=urlTypeToSegment({baseUrl:baseUrl,source:initialization.sourceURL,range:initialization.range});var segment=urlTypeToSegment({baseUrl:baseUrl,source:segmentUrl.media,range:segmentUrl.mediaRange});segment.map=initSegment;return segment;};var segmentsFromList=function segmentsFromList(attributes,segmentTimeline){var duration=attributes.duration,_attributes$segmentUr=attributes.segmentUrls,segmentUrls=_attributes$segmentUr===void 0?[]:_attributes$segmentUr;if(!duration&&!segmentTimeline||duration&&segmentTimeline){throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);}
var segmentUrlMap=segmentUrls.map(function(segmentUrlObject){return SegmentURLToSegmentObject(attributes,segmentUrlObject);});var segmentTimeInfo;if(duration){segmentTimeInfo=parseByDuration(attributes);}
if(segmentTimeline){segmentTimeInfo=parseByTimeline(attributes,segmentTimeline);}
var segments=segmentTimeInfo.map(function(segmentTime,index){if(segmentUrlMap[index]){var segment=segmentUrlMap[index];segment.timeline=segmentTime.timeline;segment.duration=segmentTime.duration;segment.number=segmentTime.number;return segment;}}).filter(function(segment){return segment;});return segments;};var generateSegments=function generateSegments(_ref){var attributes=_ref.attributes,segmentInfo=_ref.segmentInfo;var segmentAttributes;var segmentsFn;if(segmentInfo.template){segmentsFn=segmentsFromTemplate;segmentAttributes=merge(attributes,segmentInfo.template);}else if(segmentInfo.base){segmentsFn=segmentsFromBase;segmentAttributes=merge(attributes,segmentInfo.base);}else if(segmentInfo.list){segmentsFn=segmentsFromList;segmentAttributes=merge(attributes,segmentInfo.list);}
var segmentsInfo={attributes:attributes};if(!segmentsFn){return segmentsInfo;}
var segments=segmentsFn(segmentAttributes,segmentInfo.timeline);if(segmentAttributes.duration){var _segmentAttributes=segmentAttributes,duration=_segmentAttributes.duration,_segmentAttributes$ti=_segmentAttributes.timescale,timescale=_segmentAttributes$ti===void 0?1:_segmentAttributes$ti;segmentAttributes.duration=duration/timescale;}else if(segments.length){segmentAttributes.duration=segments.reduce(function(max,segment){return Math.max(max,Math.ceil(segment.duration));},0);}else{segmentAttributes.duration=0;}
segmentsInfo.attributes=segmentAttributes;segmentsInfo.segments=segments;if(segmentInfo.base&&segmentAttributes.indexRange){segmentsInfo.sidx=segments[0];segmentsInfo.segments=[];}
return segmentsInfo;};var toPlaylists=function toPlaylists(representations){return representations.map(generateSegments);};var findChildren=function findChildren(element,name){return from(element.childNodes).filter(function(_ref){var tagName=_ref.tagName;return tagName===name;});};var getContent=function getContent(element){return element.textContent.trim();};var parseDuration=function parseDuration(str){var SECONDS_IN_YEAR=365*24*60*60;var SECONDS_IN_MONTH=30*24*60*60;var SECONDS_IN_DAY=24*60*60;var SECONDS_IN_HOUR=60*60;var SECONDS_IN_MIN=60;var durationRegex=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/;var match=durationRegex.exec(str);if(!match){return 0;}
var _match$slice=match.slice(1),year=_match$slice[0],month=_match$slice[1],day=_match$slice[2],hour=_match$slice[3],minute=_match$slice[4],second=_match$slice[5];return parseFloat(year||0)*SECONDS_IN_YEAR+parseFloat(month||0)*SECONDS_IN_MONTH+parseFloat(day||0)*SECONDS_IN_DAY+parseFloat(hour||0)*SECONDS_IN_HOUR+parseFloat(minute||0)*SECONDS_IN_MIN+parseFloat(second||0);};var parseDate=function parseDate(str){var dateRegex=/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/;if(dateRegex.test(str)){str+='Z';}
return Date.parse(str);};var parsers={mediaPresentationDuration:function mediaPresentationDuration(value){return parseDuration(value);},availabilityStartTime:function availabilityStartTime(value){return parseDate(value)/1000;},minimumUpdatePeriod:function minimumUpdatePeriod(value){return parseDuration(value);},suggestedPresentationDelay:function suggestedPresentationDelay(value){return parseDuration(value);},type:function type(value){return value;},timeShiftBufferDepth:function timeShiftBufferDepth(value){return parseDuration(value);},start:function start(value){return parseDuration(value);},width:function width(value){return parseInt(value,10);},height:function height(value){return parseInt(value,10);},bandwidth:function bandwidth(value){return parseInt(value,10);},startNumber:function startNumber(value){return parseInt(value,10);},timescale:function timescale(value){return parseInt(value,10);},duration:function duration(value){var parsedValue=parseInt(value,10);if(isNaN(parsedValue)){return parseDuration(value);}
return parsedValue;},d:function d(value){return parseInt(value,10);},t:function t(value){return parseInt(value,10);},r:function r(value){return parseInt(value,10);},DEFAULT:function DEFAULT(value){return value;}};var parseAttributes$1=function parseAttributes(el){if(!(el&&el.attributes)){return{};}
return from(el.attributes).reduce(function(a,e){var parseFn=parsers[e.name]||parsers.DEFAULT;a[e.name]=parseFn(e.value);return a;},{});};var keySystemsMap={'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b':'org.w3.clearkey','urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed':'com.widevine.alpha','urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95':'com.microsoft.playready','urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb':'com.adobe.primetime'};var buildBaseUrls=function buildBaseUrls(referenceUrls,baseUrlElements){if(!baseUrlElements.length){return referenceUrls;}
return flatten(referenceUrls.map(function(reference){return baseUrlElements.map(function(baseUrlElement){return resolveUrl_1(reference,getContent(baseUrlElement));});}));};var getSegmentInformation=function getSegmentInformation(adaptationSet){var segmentTemplate=findChildren(adaptationSet,'SegmentTemplate')[0];var segmentList=findChildren(adaptationSet,'SegmentList')[0];var segmentUrls=segmentList&&findChildren(segmentList,'SegmentURL').map(function(s){return merge({tag:'SegmentURL'},parseAttributes$1(s));});var segmentBase=findChildren(adaptationSet,'SegmentBase')[0];var segmentTimelineParentNode=segmentList||segmentTemplate;var segmentTimeline=segmentTimelineParentNode&&findChildren(segmentTimelineParentNode,'SegmentTimeline')[0];var segmentInitializationParentNode=segmentList||segmentBase||segmentTemplate;var segmentInitialization=segmentInitializationParentNode&&findChildren(segmentInitializationParentNode,'Initialization')[0];var template=segmentTemplate&&parseAttributes$1(segmentTemplate);if(template&&segmentInitialization){template.initialization=segmentInitialization&&parseAttributes$1(segmentInitialization);}else if(template&&template.initialization){template.initialization={sourceURL:template.initialization};}
var segmentInfo={template:template,timeline:segmentTimeline&&findChildren(segmentTimeline,'S').map(function(s){return parseAttributes$1(s);}),list:segmentList&&merge(parseAttributes$1(segmentList),{segmentUrls:segmentUrls,initialization:parseAttributes$1(segmentInitialization)}),base:segmentBase&&merge(parseAttributes$1(segmentBase),{initialization:parseAttributes$1(segmentInitialization)})};Object.keys(segmentInfo).forEach(function(key){if(!segmentInfo[key]){delete segmentInfo[key];}});return segmentInfo;};var inheritBaseUrls=function inheritBaseUrls(adaptationSetAttributes,adaptationSetBaseUrls,adaptationSetSegmentInfo){return function(representation){var repBaseUrlElements=findChildren(representation,'BaseURL');var repBaseUrls=buildBaseUrls(adaptationSetBaseUrls,repBaseUrlElements);var attributes=merge(adaptationSetAttributes,parseAttributes$1(representation));var representationSegmentInfo=getSegmentInformation(representation);return repBaseUrls.map(function(baseUrl){return{segmentInfo:merge(adaptationSetSegmentInfo,representationSegmentInfo),attributes:merge(attributes,{baseUrl:baseUrl})};});};};var generateKeySystemInformation=function generateKeySystemInformation(contentProtectionNodes){return contentProtectionNodes.reduce(function(acc,node){var attributes=parseAttributes$1(node);var keySystem=keySystemsMap[attributes.schemeIdUri];if(keySystem){acc[keySystem]={attributes:attributes};var psshNode=findChildren(node,'cenc:pssh')[0];if(psshNode){var pssh=getContent(psshNode);var psshBuffer=pssh&&decodeB64ToUint8Array_1(pssh);acc[keySystem].pssh=psshBuffer;}}
return acc;},{});};var toRepresentations=function toRepresentations(periodAttributes,periodBaseUrls,periodSegmentInfo){return function(adaptationSet){var adaptationSetAttributes=parseAttributes$1(adaptationSet);var adaptationSetBaseUrls=buildBaseUrls(periodBaseUrls,findChildren(adaptationSet,'BaseURL'));var role=findChildren(adaptationSet,'Role')[0];var roleAttributes={role:parseAttributes$1(role)};var attrs=merge(periodAttributes,adaptationSetAttributes,roleAttributes);var contentProtection=generateKeySystemInformation(findChildren(adaptationSet,'ContentProtection'));if(Object.keys(contentProtection).length){attrs=merge(attrs,{contentProtection:contentProtection});}
var segmentInfo=getSegmentInformation(adaptationSet);var representations=findChildren(adaptationSet,'Representation');var adaptationSetSegmentInfo=merge(periodSegmentInfo,segmentInfo);return flatten(representations.map(inheritBaseUrls(attrs,adaptationSetBaseUrls,adaptationSetSegmentInfo)));};};var toAdaptationSets=function toAdaptationSets(mpdAttributes,mpdBaseUrls){return function(period,index){var periodBaseUrls=buildBaseUrls(mpdBaseUrls,findChildren(period,'BaseURL'));var periodAtt=parseAttributes$1(period);var parsedPeriodId=parseInt(periodAtt.id,10);var periodIndex=window_1.isNaN(parsedPeriodId)?index:parsedPeriodId;var periodAttributes=merge(mpdAttributes,{periodIndex:periodIndex});var adaptationSets=findChildren(period,'AdaptationSet');var periodSegmentInfo=getSegmentInformation(period);return flatten(adaptationSets.map(toRepresentations(periodAttributes,periodBaseUrls,periodSegmentInfo)));};};var inheritAttributes=function inheritAttributes(mpd,options){if(options===void 0){options={};}
var _options=options,_options$manifestUri=_options.manifestUri,manifestUri=_options$manifestUri===void 0?'':_options$manifestUri,_options$NOW=_options.NOW,NOW=_options$NOW===void 0?Date.now():_options$NOW,_options$clientOffset=_options.clientOffset,clientOffset=_options$clientOffset===void 0?0:_options$clientOffset;var periods=findChildren(mpd,'Period');if(!periods.length){throw new Error(errors.INVALID_NUMBER_OF_PERIOD);}
var locations=findChildren(mpd,'Location');var mpdAttributes=parseAttributes$1(mpd);var mpdBaseUrls=buildBaseUrls([manifestUri],findChildren(mpd,'BaseURL'));mpdAttributes.sourceDuration=mpdAttributes.mediaPresentationDuration||0;mpdAttributes.NOW=NOW;mpdAttributes.clientOffset=clientOffset;if(locations.length){mpdAttributes.locations=locations.map(getContent);}
return{locations:mpdAttributes.locations,representationInfo:flatten(periods.map(toAdaptationSets(mpdAttributes,mpdBaseUrls)))};};var stringToMpdXml=function stringToMpdXml(manifestString){if(manifestString===''){throw new Error(errors.DASH_EMPTY_MANIFEST);}
var parser=new domParser_3();var xml;var mpd;try{xml=parser.parseFromString(manifestString,'application/xml');mpd=xml&&xml.documentElement.tagName==='MPD'?xml.documentElement:null;}catch(e){}
if(!mpd||mpd&&mpd.getElementsByTagName('parsererror').length>0){throw new Error(errors.DASH_INVALID_XML);}
return mpd;};var parseUTCTimingScheme=function parseUTCTimingScheme(mpd){var UTCTimingNode=findChildren(mpd,'UTCTiming')[0];if(!UTCTimingNode){return null;}
var attributes=parseAttributes$1(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;case'urn:mpeg:dash:utc:http-ntp:2014':case'urn:mpeg:dash:utc:ntp:2014':case'urn:mpeg:dash:utc:sntp:2014':default:throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);}
return attributes;};var parse=function parse(manifestString,options){if(options===void 0){options={};}
var parsedManifestInfo=inheritAttributes(stringToMpdXml(manifestString),options);var playlists=toPlaylists(parsedManifestInfo.representationInfo);return toM3u8(playlists,parsedManifestInfo.locations,options.sidxMapping);};var parseUTCTiming=function parseUTCTiming(manifestString){return parseUTCTimingScheme(stringToMpdXml(manifestString));};var addSidxSegmentsToPlaylist=addSegmentsToPlaylist;var MAX_UINT32=Math.pow(2,32);var parseSidx=function parseSidx(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;if(result.version===0){result.earliestPresentationTime=view.getUint32(i);result.firstOffset=view.getUint32(i+4);i+=8;}else{result.earliestPresentationTime=view.getUint32(i)*MAX_UINT32+view.getUint32(i+4);result.firstOffset=view.getUint32(i+8)*MAX_UINT32+view.getUint32(i+12);i+=16;}
i+=2;var referenceCount=view.getUint16(i);i+=2;for(;referenceCount>0;i+=12,referenceCount--){result.references.push({referenceType:(data[i]&0x80)>>>7,referencedSize:view.getUint32(i)&0x7FFFFFFF,subsegmentDuration:view.getUint32(i+4),startsWithSap:!!(data[i+8]&0x80),sapType:(data[i+8]&0x70)>>>4,sapDeltaTime:view.getUint32(i+8)&0x0FFFFFFF});}
return result;};var parseSidx_1=parseSidx;var containers=createCommonjsModule(function(module,exports){Object.defineProperty(exports,'__esModule',{value:true});var toUint8=function toUint8(bytes){return bytes instanceof Uint8Array?bytes:new Uint8Array(bytes&&bytes.buffer||bytes,bytes&&bytes.byteOffset||0,bytes&&bytes.byteLength||0);};var bytesToString=function bytesToString(bytes){if(!bytes){return'';}
bytes=Array.prototype.slice.call(bytes);var string=String.fromCharCode.apply(null,toUint8(bytes));try{return decodeURIComponent(escape(string));}catch(e){}
return string;};var id3Size=function id3Size(bytes,offset){if(offset===void 0){offset=0;}
bytes=toUint8(bytes);var returnSize=bytes[offset+6]<<21|bytes[offset+7]<<14|bytes[offset+8]<<7|bytes[offset+9];var flags=bytes[offset+5];var footerPresent=(flags&16)>>4;if(footerPresent){return returnSize+20;}
return returnSize+10;};var getId3Offset=function getId3Offset(bytes,offset){if(offset===void 0){offset=0;}
bytes=toUint8(bytes);if(bytes.length-offset<10||bytesToString(bytes.subarray(offset,offset+3))!=='ID3'){return offset;}
offset+=id3Size(bytes,offset);return getId3Offset(bytes,offset);};var isLikely={aac:function aac(bytes){var offset=getId3Offset(bytes);return bytes.length>=offset+2&&(bytes[offset]&0xFF)===0xFF&&(bytes[offset+1]&0xE0)===0xE0&&(bytes[offset+1]&0x16)===0x10;},mp3:function mp3(bytes){var offset=getId3Offset(bytes);return bytes.length>=offset+2&&(bytes[offset]&0xFF)===0xFF&&(bytes[offset+1]&0xE0)===0xE0&&(bytes[offset+1]&0x06)===0x02;},webm:function webm(bytes){return bytes.length>=4&&(bytes[0]&0xFF)===0x1A&&(bytes[1]&0xFF)===0x45&&(bytes[2]&0xFF)===0xDF&&(bytes[3]&0xFF)===0xA3;},mp4:function mp4(bytes){return bytes.length>=8&&/^(f|s)typ$/.test(bytesToString(bytes.subarray(4,8)))&&!/^ftyp3g$/.test(bytesToString(bytes.subarray(4,10)));},'3gp':function gp(bytes){return bytes.length>=10&&/^ftyp3g$/.test(bytesToString(bytes.subarray(4,10)));},ts:function ts(bytes){if(bytes.length<189&&bytes.length>=1){return bytes[0]===0x47;}
var i=0;while(i+188<bytes.length&&i<188){if(bytes[i]===0x47&&bytes[i+188]===0x47){return true;}
i+=1;}
return false;},flac:function flac(bytes){return bytes.length>=4&&/^fLaC$/.test(bytesToString(bytes.subarray(0,4)));},ogg:function ogg(bytes){return bytes.length>=4&&/^OggS$/.test(bytesToString(bytes.subarray(0,4)));}};var isLikelyTypes=Object.keys(isLikely).filter(function(t){return t!=='ts';}).concat('ts');isLikelyTypes.forEach(function(type){var isLikelyFn=isLikely[type];isLikely[type]=function(bytes){return isLikelyFn(toUint8(bytes));};});var detectContainerForBytes=function detectContainerForBytes(bytes){bytes=toUint8(bytes);for(var i=0;i<isLikelyTypes.length;i++){var type=isLikelyTypes[i];if(isLikely[type](bytes)){return type;}}
return'';};var isLikelyFmp4MediaSegment=function isLikelyFmp4MediaSegment(bytes){bytes=toUint8(bytes);var i=0;while(i<bytes.length){var size=(bytes[i]<<24|bytes[i+1]<<16|bytes[i+2]<<8|bytes[i+3])>>>0;var type=bytesToString(bytes.subarray(i+4,i+8));if(type==='moof'){return true;}
if(size===0||size+i>bytes.length){i=bytes.length;}else{i+=size;}}
return false;};exports.detectContainerForBytes=detectContainerForBytes;exports.getId3Offset=getId3Offset;exports.id3Size=id3Size;exports.isLikely=isLikely;exports.isLikelyFmp4MediaSegment=isLikelyFmp4MediaSegment;});unwrapExports(containers);var containers_1=containers.detectContainerForBytes;var containers_2=containers.getId3Offset;var containers_3=containers.id3Size;var containers_4=containers.isLikely;var containers_5=containers.isLikelyFmp4MediaSegment;var byteHelpers=createCommonjsModule(function(module,exports){Object.defineProperty(exports,'__esModule',{value:true});var isTypedArray=function isTypedArray(obj){return ArrayBuffer.isView(obj);};var toUint8=function toUint8(bytes){return bytes instanceof Uint8Array?bytes:new Uint8Array(bytes&&bytes.buffer||bytes,bytes&&bytes.byteOffset||0,bytes&&bytes.byteLength||0);};var bytesToString=function bytesToString(bytes){if(!bytes){return'';}
bytes=Array.prototype.slice.call(bytes);var string=String.fromCharCode.apply(null,toUint8(bytes));try{return decodeURIComponent(escape(string));}catch(e){}
return string;};var stringToBytes=function stringToBytes(string,stringIsBytes){if(stringIsBytes===void 0){stringIsBytes=false;}
var bytes=[];if(typeof string!=='string'&&string&&typeof string.toString==='function'){string=string.toString();}
if(typeof string!=='string'){return bytes;}
if(!stringIsBytes){string=unescape(encodeURIComponent(string));}
return string.split('').map(function(s){return s.charCodeAt(0)&0xFF;});};var concatTypedArrays=function concatTypedArrays(){for(var _len=arguments.length,buffers=new Array(_len),_key=0;_key<_len;_key++){buffers[_key]=arguments[_key];}
var totalLength=buffers.reduce(function(total,buf){var len=buf&&(buf.byteLength||buf.length);total+=len||0;return total;},0);var tempBuffer=new Uint8Array(totalLength);var offset=0;buffers.forEach(function(buf){buf=toUint8(buf);tempBuffer.set(buf,offset);offset+=buf.byteLength;});return tempBuffer;};exports.bytesToString=bytesToString;exports.concatTypedArrays=concatTypedArrays;exports.isTypedArray=isTypedArray;exports.stringToBytes=stringToBytes;exports.toUint8=toUint8;});unwrapExports(byteHelpers);var byteHelpers_1=byteHelpers.bytesToString;var byteHelpers_2=byteHelpers.concatTypedArrays;var byteHelpers_3=byteHelpers.isTypedArray;var byteHelpers_4=byteHelpers.stringToBytes;var byteHelpers_5=byteHelpers.toUint8;var streamTypes={H264_STREAM_TYPE:0x1B,ADTS_STREAM_TYPE:0x0F,METADATA_STREAM_TYPE:0x15};var Stream$1=function Stream(){this.init=function(){var listeners={};this.on=function(type,listener){if(!listeners[type]){listeners[type]=[];}
listeners[type]=listeners[type].concat(listener);};this.off=function(type,listener){var index;if(!listeners[type]){return false;}
index=listeners[type].indexOf(listener);listeners[type]=listeners[type].slice();listeners[type].splice(index,1);return index>-1;};this.trigger=function(type){var callbacks,i,length,args;callbacks=listeners[type];if(!callbacks){return;}
if(arguments.length===2){length=callbacks.length;for(i=0;i<length;++i){callbacks[i].call(this,arguments[1]);}}else{args=[];i=arguments.length;for(i=1;i<arguments.length;++i){args.push(arguments[i]);}
length=callbacks.length;for(i=0;i<length;++i){callbacks[i].apply(this,args);}}};this.dispose=function(){listeners={};};};};Stream$1.prototype.pipe=function(destination){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);});return destination;};Stream$1.prototype.push=function(data){this.trigger('data',data);};Stream$1.prototype.flush=function(flushSource){this.trigger('done',flushSource);};Stream$1.prototype.partialFlush=function(flushSource){this.trigger('partialdone',flushSource);};Stream$1.prototype.endTimeline=function(flushSource){this.trigger('endedtimeline',flushSource);};Stream$1.prototype.reset=function(flushSource){this.trigger('reset',flushSource);};var stream$1=Stream$1;var MAX_TS=8589934592;var RO_THRESH=4294967296;var TYPE_SHARED='shared';var handleRollover=function handleRollover(value,reference){var direction=1;if(value>reference){direction=-1;}
while(Math.abs(reference-value)>RO_THRESH){value+=direction*MAX_TS;}
return value;};var TimestampRolloverStream=function TimestampRolloverStream(type){var lastDTS,referenceDTS;TimestampRolloverStream.prototype.init.call(this);this.type_=type||TYPE_SHARED;this.push=function(data){if(this.type_!==TYPE_SHARED&&data.type!==this.type_){return;}
if(referenceDTS===undefined){referenceDTS=data.dts;}
data.dts=handleRollover(data.dts,referenceDTS);data.pts=handleRollover(data.pts,referenceDTS);lastDTS=data.dts;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.prototype=new stream$1();var timestampRolloverStream={TimestampRolloverStream:TimestampRolloverStream,handleRollover:handleRollover};var parsePid=function parsePid(packet){var pid=packet[1]&0x1f;pid<<=8;pid|=packet[2];return pid;};var parsePayloadUnitStartIndicator=function parsePayloadUnitStartIndicator(packet){return!!(packet[1]&0x40);};var parseAdaptionField=function parseAdaptionField(packet){var offset=0;if((packet[3]&0x30)>>>4>0x01){offset+=packet[4]+1;}
return offset;};var parseType=function parseType(packet,pmtPid){var pid=parsePid(packet);if(pid===0){return'pat';}else if(pid===pmtPid){return'pmt';}else if(pmtPid){return'pes';}
return null;};var parsePat=function parsePat(packet){var pusi=parsePayloadUnitStartIndicator(packet);var offset=4+parseAdaptionField(packet);if(pusi){offset+=packet[offset]+1;}
return(packet[offset+10]&0x1f)<<8|packet[offset+11];};var parsePmt=function parsePmt(packet){var programMapTable={};var pusi=parsePayloadUnitStartIndicator(packet);var payloadOffset=4+parseAdaptionField(packet);if(pusi){payloadOffset+=packet[payloadOffset]+1;}
if(!(packet[payloadOffset+5]&0x01)){return;}
var sectionLength,tableEnd,programInfoLength;sectionLength=(packet[payloadOffset+1]&0x0f)<<8|packet[payloadOffset+2];tableEnd=3+sectionLength-4;programInfoLength=(packet[payloadOffset+10]&0x0f)<<8|packet[payloadOffset+11];var offset=12+programInfoLength;while(offset<tableEnd){var i=payloadOffset+offset;programMapTable[(packet[i+1]&0x1F)<<8|packet[i+2]]=packet[i];offset+=((packet[i+3]&0x0F)<<8|packet[i+4])+5;}
return programMapTable;};var parsePesType=function parsePesType(packet,programMapTable){var pid=parsePid(packet);var type=programMapTable[pid];switch(type){case streamTypes.H264_STREAM_TYPE:return'video';case streamTypes.ADTS_STREAM_TYPE:return'audio';case streamTypes.METADATA_STREAM_TYPE:return'timed-metadata';default:return null;}};var parsePesTime=function parsePesTime(packet){var pusi=parsePayloadUnitStartIndicator(packet);if(!pusi){return null;}
var offset=4+parseAdaptionField(packet);if(offset>=packet.byteLength){return null;}
var pes=null;var ptsDtsFlags;ptsDtsFlags=packet[offset+7];if(ptsDtsFlags&0xC0){pes={};pes.pts=(packet[offset+9]&0x0E)<<27|(packet[offset+10]&0xFF)<<20|(packet[offset+11]&0xFE)<<12|(packet[offset+12]&0xFF)<<5|(packet[offset+13]&0xFE)>>>3;pes.pts*=4;pes.pts+=(packet[offset+13]&0x06)>>>1;pes.dts=pes.pts;if(ptsDtsFlags&0x40){pes.dts=(packet[offset+14]&0x0E)<<27|(packet[offset+15]&0xFF)<<20|(packet[offset+16]&0xFE)<<12|(packet[offset+17]&0xFF)<<5|(packet[offset+18]&0xFE)>>>3;pes.dts*=4;pes.dts+=(packet[offset+18]&0x06)>>>1;}}
return pes;};var parseNalUnitType=function parseNalUnitType(type){switch(type){case 0x05:return'slice_layer_without_partitioning_rbsp_idr';case 0x06:return'sei_rbsp';case 0x07:return'seq_parameter_set_rbsp';case 0x08:return'pic_parameter_set_rbsp';case 0x09:return'access_unit_delimiter_rbsp';default:return null;}};var videoPacketContainsKeyFrame=function videoPacketContainsKeyFrame(packet){var offset=4+parseAdaptionField(packet);var frameBuffer=packet.subarray(offset);var frameI=0;var frameSyncPoint=0;var foundKeyFrame=false;var nalType;for(;frameSyncPoint<frameBuffer.byteLength-3;frameSyncPoint++){if(frameBuffer[frameSyncPoint+2]===1){frameI=frameSyncPoint+5;break;}}
while(frameI<frameBuffer.byteLength){switch(frameBuffer[frameI]){case 0:if(frameBuffer[frameI-1]!==0){frameI+=2;break;}else if(frameBuffer[frameI-2]!==0){frameI++;break;}
if(frameSyncPoint+3!==frameI-2){nalType=parseNalUnitType(frameBuffer[frameSyncPoint+3]&0x1f);if(nalType==='slice_layer_without_partitioning_rbsp_idr'){foundKeyFrame=true;}}
do{frameI++;}while(frameBuffer[frameI]!==1&&frameI<frameBuffer.length);frameSyncPoint=frameI-2;frameI+=3;break;case 1:if(frameBuffer[frameI-1]!==0||frameBuffer[frameI-2]!==0){frameI+=3;break;}
nalType=parseNalUnitType(frameBuffer[frameSyncPoint+3]&0x1f);if(nalType==='slice_layer_without_partitioning_rbsp_idr'){foundKeyFrame=true;}
frameSyncPoint=frameI-2;frameI+=3;break;default:frameI+=3;break;}}
frameBuffer=frameBuffer.subarray(frameSyncPoint);frameI-=frameSyncPoint;frameSyncPoint=0;if(frameBuffer&&frameBuffer.byteLength>3){nalType=parseNalUnitType(frameBuffer[frameSyncPoint+3]&0x1f);if(nalType==='slice_layer_without_partitioning_rbsp_idr'){foundKeyFrame=true;}}
return foundKeyFrame;};var probe={parseType:parseType,parsePat:parsePat,parsePmt:parsePmt,parsePayloadUnitStartIndicator:parsePayloadUnitStartIndicator,parsePesType:parsePesType,parsePesTime:parsePesTime,videoPacketContainsKeyFrame:videoPacketContainsKeyFrame};var ADTS_SAMPLING_FREQUENCIES=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350];var parseId3TagSize=function parseId3TagSize(header,byteIndex){var returnSize=header[byteIndex+6]<<21|header[byteIndex+7]<<14|header[byteIndex+8]<<7|header[byteIndex+9],flags=header[byteIndex+5],footerPresent=(flags&16)>>4;returnSize=returnSize>=0?returnSize:0;if(footerPresent){return returnSize+20;}
return returnSize+10;};var getId3Offset=function getId3Offset(data,offset){if(data.length-offset<10||data[offset]!=='I'.charCodeAt(0)||data[offset+1]!=='D'.charCodeAt(0)||data[offset+2]!=='3'.charCodeAt(0)){return offset;}
offset+=parseId3TagSize(data,offset);return getId3Offset(data,offset);};var isLikelyAacData=function isLikelyAacData(data){var offset=getId3Offset(data,0);return data.length>=offset+2&&(data[offset]&0xFF)===0xFF&&(data[offset+1]&0xF0)===0xF0&&(data[offset+1]&0x16)===0x10;};var parseSyncSafeInteger=function parseSyncSafeInteger(data){return data[0]<<21|data[1]<<14|data[2]<<7|data[3];};var percentEncode=function percentEncode(bytes,start,end){var i,result='';for(i=start;i<end;i++){result+='%'+('00'+bytes[i].toString(16)).slice(-2);}
return result;};var parseIso88591=function parseIso88591(bytes,start,end){return unescape(percentEncode(bytes,start,end));};var parseAdtsSize=function parseAdtsSize(header,byteIndex){var lowThree=(header[byteIndex+5]&0xE0)>>5,middle=header[byteIndex+4]<<3,highTwo=header[byteIndex+3]&0x3<<11;return highTwo|middle|lowThree;};var parseType$1=function parseType(header,byteIndex){if(header[byteIndex]==='I'.charCodeAt(0)&&header[byteIndex+1]==='D'.charCodeAt(0)&&header[byteIndex+2]==='3'.charCodeAt(0)){return'timed-metadata';}else if(header[byteIndex]&0xff===0xff&&(header[byteIndex+1]&0xf0)===0xf0){return'audio';}
return null;};var parseSampleRate=function parseSampleRate(packet){var i=0;while(i+5<packet.length){if(packet[i]!==0xFF||(packet[i+1]&0xF6)!==0xF0){i++;continue;}
return ADTS_SAMPLING_FREQUENCIES[(packet[i+2]&0x3c)>>>2];}
return null;};var parseAacTimestamp=function parseAacTimestamp(packet){var frameStart,frameSize,frame,frameHeader;frameStart=10;if(packet[5]&0x40){frameStart+=4;frameStart+=parseSyncSafeInteger(packet.subarray(10,14));}
do{frameSize=parseSyncSafeInteger(packet.subarray(frameStart+4,frameStart+8));if(frameSize<1){return null;}
frameHeader=String.fromCharCode(packet[frameStart],packet[frameStart+1],packet[frameStart+2],packet[frameStart+3]);if(frameHeader==='PRIV'){frame=packet.subarray(frameStart+10,frameStart+frameSize+10);for(var i=0;i<frame.byteLength;i++){if(frame[i]===0){var owner=parseIso88591(frame,0,i);if(owner==='com.apple.streaming.transportStreamTimestamp'){var d=frame.subarray(i+1);var size=(d[3]&0x01)<<30|d[4]<<22|d[5]<<14|d[6]<<6|d[7]>>>2;size*=4;size+=d[7]&0x03;return size;}
break;}}}
frameStart+=10;frameStart+=frameSize;}while(frameStart<packet.byteLength);return null;};var utils={isLikelyAacData:isLikelyAacData,parseId3TagSize:parseId3TagSize,parseAdtsSize:parseAdtsSize,parseType:parseType$1,parseSampleRate:parseSampleRate,parseAacTimestamp:parseAacTimestamp};var ONE_SECOND_IN_TS=90000,secondsToVideoTs,secondsToAudioTs,videoTsToSeconds,audioTsToSeconds,audioTsToVideoTs,videoTsToAudioTs,metadataTsToSeconds;secondsToVideoTs=function secondsToVideoTs(seconds){return seconds*ONE_SECOND_IN_TS;};secondsToAudioTs=function secondsToAudioTs(seconds,sampleRate){return seconds*sampleRate;};videoTsToSeconds=function videoTsToSeconds(timestamp){return timestamp/ONE_SECOND_IN_TS;};audioTsToSeconds=function audioTsToSeconds(timestamp,sampleRate){return timestamp/sampleRate;};audioTsToVideoTs=function audioTsToVideoTs(timestamp,sampleRate){return secondsToVideoTs(audioTsToSeconds(timestamp,sampleRate));};videoTsToAudioTs=function videoTsToAudioTs(timestamp,sampleRate){return secondsToAudioTs(videoTsToSeconds(timestamp),sampleRate);};metadataTsToSeconds=function metadataTsToSeconds(timestamp,timelineStartPts,keepOriginalTimestamps){return videoTsToSeconds(keepOriginalTimestamps?timestamp:timestamp-timelineStartPts);};var clock={ONE_SECOND_IN_TS:ONE_SECOND_IN_TS,secondsToVideoTs:secondsToVideoTs,secondsToAudioTs:secondsToAudioTs,videoTsToSeconds:videoTsToSeconds,audioTsToSeconds:audioTsToSeconds,audioTsToVideoTs:audioTsToVideoTs,videoTsToAudioTs:videoTsToAudioTs,metadataTsToSeconds:metadataTsToSeconds};var clock_1=clock.ONE_SECOND_IN_TS;var handleRollover$1=timestampRolloverStream.handleRollover;var probe$1={};probe$1.ts=probe;probe$1.aac=utils;var ONE_SECOND_IN_TS$1=clock.ONE_SECOND_IN_TS;var MP2T_PACKET_LENGTH=188,SYNC_BYTE=0x47;var parsePsi_=function parsePsi_(bytes,pmt){var startIndex=0,endIndex=MP2T_PACKET_LENGTH,packet,type;while(endIndex<bytes.byteLength){if(bytes[startIndex]===SYNC_BYTE&&bytes[endIndex]===SYNC_BYTE){packet=bytes.subarray(startIndex,endIndex);type=probe$1.ts.parseType(packet,pmt.pid);switch(type){case'pat':if(!pmt.pid){pmt.pid=probe$1.ts.parsePat(packet);}
break;case'pmt':if(!pmt.table){pmt.table=probe$1.ts.parsePmt(packet);}
break;}
if(pmt.pid&&pmt.table){return;}
startIndex+=MP2T_PACKET_LENGTH;endIndex+=MP2T_PACKET_LENGTH;continue;}
startIndex++;endIndex++;}};var parseAudioPes_=function parseAudioPes_(bytes,pmt,result){var startIndex=0,endIndex=MP2T_PACKET_LENGTH,packet,type,pesType,pusi,parsed;var endLoop=false;while(endIndex<=bytes.byteLength){if(bytes[startIndex]===SYNC_BYTE&&(bytes[endIndex]===SYNC_BYTE||endIndex===bytes.byteLength)){packet=bytes.subarray(startIndex,endIndex);type=probe$1.ts.parseType(packet,pmt.pid);switch(type){case'pes':pesType=probe$1.ts.parsePesType(packet,pmt.table);pusi=probe$1.ts.parsePayloadUnitStartIndicator(packet);if(pesType==='audio'&&pusi){parsed=probe$1.ts.parsePesTime(packet);if(parsed){parsed.type='audio';result.audio.push(parsed);endLoop=true;}}
break;}
if(endLoop){break;}
startIndex+=MP2T_PACKET_LENGTH;endIndex+=MP2T_PACKET_LENGTH;continue;}
startIndex++;endIndex++;}
endIndex=bytes.byteLength;startIndex=endIndex-MP2T_PACKET_LENGTH;endLoop=false;while(startIndex>=0){if(bytes[startIndex]===SYNC_BYTE&&(bytes[endIndex]===SYNC_BYTE||endIndex===bytes.byteLength)){packet=bytes.subarray(startIndex,endIndex);type=probe$1.ts.parseType(packet,pmt.pid);switch(type){case'pes':pesType=probe$1.ts.parsePesType(packet,pmt.table);pusi=probe$1.ts.parsePayloadUnitStartIndicator(packet);if(pesType==='audio'&&pusi){parsed=probe$1.ts.parsePesTime(packet);if(parsed){parsed.type='audio';result.audio.push(parsed);endLoop=true;}}
break;}
if(endLoop){break;}
startIndex-=MP2T_PACKET_LENGTH;endIndex-=MP2T_PACKET_LENGTH;continue;}
startIndex--;endIndex--;}};var parseVideoPes_=function parseVideoPes_(bytes,pmt,result){var startIndex=0,endIndex=MP2T_PACKET_LENGTH,packet,type,pesType,pusi,parsed,frame,i,pes;var endLoop=false;var currentFrame={data:[],size:0};while(endIndex<bytes.byteLength){if(bytes[startIndex]===SYNC_BYTE&&bytes[endIndex]===SYNC_BYTE){packet=bytes.subarray(startIndex,endIndex);type=probe$1.ts.parseType(packet,pmt.pid);switch(type){case'pes':pesType=probe$1.ts.parsePesType(packet,pmt.table);pusi=probe$1.ts.parsePayloadUnitStartIndicator(packet);if(pesType==='video'){if(pusi&&!endLoop){parsed=probe$1.ts.parsePesTime(packet);if(parsed){parsed.type='video';result.video.push(parsed);endLoop=true;}}
if(!result.firstKeyFrame){if(pusi){if(currentFrame.size!==0){frame=new Uint8Array(currentFrame.size);i=0;while(currentFrame.data.length){pes=currentFrame.data.shift();frame.set(pes,i);i+=pes.byteLength;}
if(probe$1.ts.videoPacketContainsKeyFrame(frame)){var firstKeyFrame=probe$1.ts.parsePesTime(frame);if(firstKeyFrame){result.firstKeyFrame=firstKeyFrame;result.firstKeyFrame.type='video';}else{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;}}
break;}
if(endLoop&&result.firstKeyFrame){break;}
startIndex+=MP2T_PACKET_LENGTH;endIndex+=MP2T_PACKET_LENGTH;continue;}
startIndex++;endIndex++;}
endIndex=bytes.byteLength;startIndex=endIndex-MP2T_PACKET_LENGTH;endLoop=false;while(startIndex>=0){if(bytes[startIndex]===SYNC_BYTE&&bytes[endIndex]===SYNC_BYTE){packet=bytes.subarray(startIndex,endIndex);type=probe$1.ts.parseType(packet,pmt.pid);switch(type){case'pes':pesType=probe$1.ts.parsePesType(packet,pmt.table);pusi=probe$1.ts.parsePayloadUnitStartIndicator(packet);if(pesType==='video'&&pusi){parsed=probe$1.ts.parsePesTime(packet);if(parsed){parsed.type='video';result.video.push(parsed);endLoop=true;}}
break;}
if(endLoop){break;}
startIndex-=MP2T_PACKET_LENGTH;endIndex-=MP2T_PACKET_LENGTH;continue;}
startIndex--;endIndex--;}};var adjustTimestamp_=function adjustTimestamp_(segmentInfo,baseTimestamp){if(segmentInfo.audio&&segmentInfo.audio.length){var audioBaseTimestamp=baseTimestamp;if(typeof audioBaseTimestamp==='undefined'){audioBaseTimestamp=segmentInfo.audio[0].dts;}
segmentInfo.audio.forEach(function(info){info.dts=handleRollover$1(info.dts,audioBaseTimestamp);info.pts=handleRollover$1(info.pts,audioBaseTimestamp);info.dtsTime=info.dts/ONE_SECOND_IN_TS$1;info.ptsTime=info.pts/ONE_SECOND_IN_TS$1;});}
if(segmentInfo.video&&segmentInfo.video.length){var videoBaseTimestamp=baseTimestamp;if(typeof videoBaseTimestamp==='undefined'){videoBaseTimestamp=segmentInfo.video[0].dts;}
segmentInfo.video.forEach(function(info){info.dts=handleRollover$1(info.dts,videoBaseTimestamp);info.pts=handleRollover$1(info.pts,videoBaseTimestamp);info.dtsTime=info.dts/ONE_SECOND_IN_TS$1;info.ptsTime=info.pts/ONE_SECOND_IN_TS$1;});if(segmentInfo.firstKeyFrame){var frame=segmentInfo.firstKeyFrame;frame.dts=handleRollover$1(frame.dts,videoBaseTimestamp);frame.pts=handleRollover$1(frame.pts,videoBaseTimestamp);frame.dtsTime=frame.dts/ONE_SECOND_IN_TS$1;frame.ptsTime=frame.dts/ONE_SECOND_IN_TS$1;}}};var inspectAac_=function inspectAac_(bytes){var endLoop=false,audioCount=0,sampleRate=null,timestamp=null,frameSize=0,byteIndex=0,packet;while(bytes.length-byteIndex>=3){var type=probe$1.aac.parseType(bytes,byteIndex);switch(type){case'timed-metadata':if(bytes.length-byteIndex<10){endLoop=true;break;}
frameSize=probe$1.aac.parseId3TagSize(bytes,byteIndex);if(frameSize>bytes.length){endLoop=true;break;}
if(timestamp===null){packet=bytes.subarray(byteIndex,byteIndex+frameSize);timestamp=probe$1.aac.parseAacTimestamp(packet);}
byteIndex+=frameSize;break;case'audio':if(bytes.length-byteIndex<7){endLoop=true;break;}
frameSize=probe$1.aac.parseAdtsSize(bytes,byteIndex);if(frameSize>bytes.length){endLoop=true;break;}
if(sampleRate===null){packet=bytes.subarray(byteIndex,byteIndex+frameSize);sampleRate=probe$1.aac.parseSampleRate(packet);}
audioCount++;byteIndex+=frameSize;break;default:byteIndex++;break;}
if(endLoop){return null;}}
if(sampleRate===null||timestamp===null){return null;}
var audioTimescale=ONE_SECOND_IN_TS$1/sampleRate;var result={audio:[{type:'audio',dts:timestamp,pts:timestamp},{type:'audio',dts:timestamp+audioCount*1024*audioTimescale,pts:timestamp+audioCount*1024*audioTimescale}]};return result;};var inspectTs_=function inspectTs_(bytes){var pmt={pid:null,table:null};var result={};parsePsi_(bytes,pmt);for(var pid in pmt.table){if(pmt.table.hasOwnProperty(pid)){var type=pmt.table[pid];switch(type){case streamTypes.H264_STREAM_TYPE:result.video=[];parseVideoPes_(bytes,pmt,result);if(result.video.length===0){delete result.video;}
break;case streamTypes.ADTS_STREAM_TYPE:result.audio=[];parseAudioPes_(bytes,pmt,result);if(result.audio.length===0){delete result.audio;}
break;}}}
return result;};var inspect=function inspect(bytes,baseTimestamp){var isAacData=probe$1.aac.isLikelyAacData(bytes);var result;if(isAacData){result=inspectAac_(bytes);}else{result=inspectTs_(bytes);}
if(!result||!result.audio&&!result.video){return null;}
adjustTimestamp_(result,baseTimestamp);return result;};var tsInspector={inspect:inspect,parseAudioPes_:parseAudioPes_};var toUnsigned=function toUnsigned(value){return value>>>0;};var toHexString=function toHexString(value){return('00'+value.toString(16)).slice(-2);};var bin={toUnsigned:toUnsigned,toHexString:toHexString};var parseType$2=function parseType(buffer){var result='';result+=String.fromCharCode(buffer[0]);result+=String.fromCharCode(buffer[1]);result+=String.fromCharCode(buffer[2]);result+=String.fromCharCode(buffer[3]);return result;};var parseType_1=parseType$2;var toUnsigned$1=bin.toUnsigned;var findBox=function findBox(data,path){var results=[],i,size,type,end,subresults;if(!path.length){return null;}
for(i=0;i<data.byteLength;){size=toUnsigned$1(data[i]<<24|data[i+1]<<16|data[i+2]<<8|data[i+3]);type=parseType_1(data.subarray(i+4,i+8));end=size>1?i+size:data.byteLength;if(type===path[0]){if(path.length===1){results.push(data.subarray(i+8,end));}else{subresults=findBox(data.subarray(i+8,end),path.slice(1));if(subresults.length){results=results.concat(subresults);}}}
i=end;}
return results;};var findBox_1=findBox;var tfhd=function tfhd(data){var 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=result.flags[2]&0x01,sampleDescriptionIndexPresent=result.flags[2]&0x02,defaultSampleDurationPresent=result.flags[2]&0x08,defaultSampleSizePresent=result.flags[2]&0x10,defaultSampleFlagsPresent=result.flags[2]&0x20,durationIsEmpty=result.flags[0]&0x010000,defaultBaseIsMoof=result.flags[0]&0x020000,i;i=8;if(baseDataOffsetPresent){i+=4;result.baseDataOffset=view.getUint32(12);i+=4;}
if(sampleDescriptionIndexPresent){result.sampleDescriptionIndex=view.getUint32(i);i+=4;}
if(defaultSampleDurationPresent){result.defaultSampleDuration=view.getUint32(i);i+=4;}
if(defaultSampleSizePresent){result.defaultSampleSize=view.getUint32(i);i+=4;}
if(defaultSampleFlagsPresent){result.defaultSampleFlags=view.getUint32(i);}
if(durationIsEmpty){result.durationIsEmpty=true;}
if(!baseDataOffsetPresent&&defaultBaseIsMoof){result.baseDataOffsetIsMoof=true;}
return result;};var parseTfhd=tfhd;var parseSampleFlags=function parseSampleFlags(flags){return{isLeading:(flags[0]&0x0c)>>>2,dependsOn:flags[0]&0x03,isDependedOn:(flags[1]&0xc0)>>>6,hasRedundancy:(flags[1]&0x30)>>>4,paddingValue:(flags[1]&0x0e)>>>1,isNonSyncSample:flags[1]&0x01,degradationPriority:flags[2]<<8|flags[3]};};var parseSampleFlags_1=parseSampleFlags;var trun=function trun(data){var result={version:data[0],flags:new Uint8Array(data.subarray(1,4)),samples:[]},view=new DataView(data.buffer,data.byteOffset,data.byteLength),dataOffsetPresent=result.flags[2]&0x01,firstSampleFlagsPresent=result.flags[2]&0x04,sampleDurationPresent=result.flags[1]&0x01,sampleSizePresent=result.flags[1]&0x02,sampleFlagsPresent=result.flags[1]&0x04,sampleCompositionTimeOffsetPresent=result.flags[1]&0x08,sampleCount=view.getUint32(4),offset=8,sample;if(dataOffsetPresent){result.dataOffset=view.getInt32(offset);offset+=4;}
if(firstSampleFlagsPresent&&sampleCount){sample={flags:parseSampleFlags_1(data.subarray(offset,offset+4))};offset+=4;if(sampleDurationPresent){sample.duration=view.getUint32(offset);offset+=4;}
if(sampleSizePresent){sample.size=view.getUint32(offset);offset+=4;}
if(sampleCompositionTimeOffsetPresent){if(result.version===1){sample.compositionTimeOffset=view.getInt32(offset);}else{sample.compositionTimeOffset=view.getUint32(offset);}
offset+=4;}
result.samples.push(sample);sampleCount--;}
while(sampleCount--){sample={};if(sampleDurationPresent){sample.duration=view.getUint32(offset);offset+=4;}
if(sampleSizePresent){sample.size=view.getUint32(offset);offset+=4;}
if(sampleFlagsPresent){sample.flags=parseSampleFlags_1(data.subarray(offset,offset+4));offset+=4;}
if(sampleCompositionTimeOffsetPresent){if(result.version===1){sample.compositionTimeOffset=view.getInt32(offset);}else{sample.compositionTimeOffset=view.getUint32(offset);}
offset+=4;}
result.samples.push(sample);}
return result;};var parseTrun=trun;var toUnsigned$2=bin.toUnsigned;var tfdt=function tfdt(data){var result={version:data[0],flags:new Uint8Array(data.subarray(1,4)),baseMediaDecodeTime:toUnsigned$2(data[4]<<24|data[5]<<16|data[6]<<8|data[7])};if(result.version===1){result.baseMediaDecodeTime*=Math.pow(2,32);result.baseMediaDecodeTime+=toUnsigned$2(data[8]<<24|data[9]<<16|data[10]<<8|data[11]);}
return result;};var parseTfdt=tfdt;var toUnsigned$3=bin.toUnsigned;var toHexString$1=bin.toHexString;var timescale,startTime,compositionStartTime,getVideoTrackIds,getTracks,getTimescaleFromMediaHeader;timescale=function timescale(init){var result={},traks=findBox_1(init,['moov','trak']);return traks.reduce(function(result,trak){var tkhd,version,index,id,mdhd;tkhd=findBox_1(trak,['tkhd'])[0];if(!tkhd){return null;}
version=tkhd[0];index=version===0?12:20;id=toUnsigned$3(tkhd[index]<<24|tkhd[index+1]<<16|tkhd[index+2]<<8|tkhd[index+3]);mdhd=findBox_1(trak,['mdia','mdhd'])[0];if(!mdhd){return null;}
version=mdhd[0];index=version===0?12:20;result[id]=toUnsigned$3(mdhd[index]<<24|mdhd[index+1]<<16|mdhd[index+2]<<8|mdhd[index+3]);return result;},result);};startTime=function startTime(timescale,fragment){var trafs,baseTimes,result;trafs=findBox_1(fragment,['moof','traf']);baseTimes=[].concat.apply([],trafs.map(function(traf){return findBox_1(traf,['tfhd']).map(function(tfhd){var id,scale,baseTime;id=toUnsigned$3(tfhd[4]<<24|tfhd[5]<<16|tfhd[6]<<8|tfhd[7]);scale=timescale[id]||90e3;baseTime=findBox_1(traf,['tfdt']).map(function(tfdt){var version,result;version=tfdt[0];result=toUnsigned$3(tfdt[4]<<24|tfdt[5]<<16|tfdt[6]<<8|tfdt[7]);if(version===1){result*=Math.pow(2,32);result+=toUnsigned$3(tfdt[8]<<24|tfdt[9]<<16|tfdt[10]<<8|tfdt[11]);}
return result;})[0];baseTime=typeof baseTime==='number'&&!isNaN(baseTime)?baseTime:Infinity;return baseTime/scale;});}));result=Math.min.apply(null,baseTimes);return isFinite(result)?result:0;};compositionStartTime=function compositionStartTime(timescales,fragment){var trafBoxes=findBox_1(fragment,['moof','traf']);var baseMediaDecodeTime=0;var compositionTimeOffset=0;var trackId;if(trafBoxes&&trafBoxes.length){var tfhd=findBox_1(trafBoxes[0],['tfhd'])[0];var trun=findBox_1(trafBoxes[0],['trun'])[0];var tfdt=findBox_1(trafBoxes[0],['tfdt'])[0];if(tfhd){var parsedTfhd=parseTfhd(tfhd);trackId=parsedTfhd.trackId;}
if(tfdt){var parsedTfdt=parseTfdt(tfdt);baseMediaDecodeTime=parsedTfdt.baseMediaDecodeTime;}
if(trun){var parsedTrun=parseTrun(trun);if(parsedTrun.samples&&parsedTrun.samples.length){compositionTimeOffset=parsedTrun.samples[0].compositionTimeOffset||0;}}}
var timescale=timescales[trackId]||90e3;return(baseMediaDecodeTime+compositionTimeOffset)/timescale;};getVideoTrackIds=function getVideoTrackIds(init){var traks=findBox_1(init,['moov','trak']);var videoTrackIds=[];traks.forEach(function(trak){var hdlrs=findBox_1(trak,['mdia','hdlr']);var tkhds=findBox_1(trak,['tkhd']);hdlrs.forEach(function(hdlr,index){var handlerType=parseType_1(hdlr.subarray(8,12));var tkhd=tkhds[index];var view;var version;var trackId;if(handlerType==='vide'){view=new DataView(tkhd.buffer,tkhd.byteOffset,tkhd.byteLength);version=view.getUint8(0);trackId=version===0?view.getUint32(12):view.getUint32(20);videoTrackIds.push(trackId);}});});return videoTrackIds;};getTimescaleFromMediaHeader=function getTimescaleFromMediaHeader(mdhd){var version=mdhd[0];var index=version===0?12:20;return toUnsigned$3(mdhd[index]<<24|mdhd[index+1]<<16|mdhd[index+2]<<8|mdhd[index+3]);};getTracks=function getTracks(init){var traks=findBox_1(init,['moov','trak']);var tracks=[];traks.forEach(function(trak){var track={};var tkhd=findBox_1(trak,['tkhd'])[0];var view,tkhdVersion;if(tkhd){view=new DataView(tkhd.buffer,tkhd.byteOffset,tkhd.byteLength);tkhdVersion=view.getUint8(0);track.id=tkhdVersion===0?view.getUint32(12):view.getUint32(20);}
var hdlr=findBox_1(trak,['mdia','hdlr'])[0];if(hdlr){var type=parseType_1(hdlr.subarray(8,12));if(type==='vide'){track.type='video';}else if(type==='soun'){track.type='audio';}else{track.type=type;}}
var stsd=findBox_1(trak,['mdia','minf','stbl','stsd'])[0];if(stsd){var sampleDescriptions=stsd.subarray(8);track.codec=parseType_1(sampleDescriptions.subarray(4,8));var codecBox=findBox_1(sampleDescriptions,[track.codec])[0];var codecConfig,codecConfigType;if(codecBox){if(/^[a-z]vc[1-9]$/i.test(track.codec)){codecConfig=codecBox.subarray(78);codecConfigType=parseType_1(codecConfig.subarray(4,8));if(codecConfigType==='avcC'&&codecConfig.length>11){track.codec+='.';track.codec+=toHexString$1(codecConfig[9]);track.codec+=toHexString$1(codecConfig[10]);track.codec+=toHexString$1(codecConfig[11]);}else{track.codec='avc1.4d400d';}}else if(/^mp4[a,v]$/i.test(track.codec)){codecConfig=codecBox.subarray(28);codecConfigType=parseType_1(codecConfig.subarray(4,8));if(codecConfigType==='esds'&&codecConfig.length>20&&codecConfig[19]!==0){track.codec+='.'+toHexString$1(codecConfig[19]);track.codec+='.'+toHexString$1(codecConfig[20]>>>2&0x3f).replace(/^0/,'');}else{track.codec='mp4a.40.2';}}else{track.codec=track.codec.toLowerCase();}}}
var mdhd=findBox_1(trak,['mdia','mdhd'])[0];if(mdhd){track.timescale=getTimescaleFromMediaHeader(mdhd);}
tracks.push(track);});return tracks;};var probe$2={findBox:findBox_1,parseType:parseType_1,timescale:timescale,startTime:startTime,compositionStartTime:compositionStartTime,videoTrackIds:getVideoTrackIds,tracks:getTracks,getTimescaleFromMediaHeader:getTimescaleFromMediaHeader};var codecs=createCommonjsModule(function(module,exports){Object.defineProperty(exports,'__esModule',{value:true});function _interopDefault(ex){return ex&&typeof ex==='object'&&'default'in ex?ex['default']:ex;}
var window=_interopDefault(window_1);var 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)/,text:/^(stpp.ttml.im1t)/,muxerVideo:/^(avc0?1)/,muxerAudio:/^(mp4a)/,muxerText:/a^/};var mediaTypes=['video','audio','text'];var upperMediaTypes=['Video','Audio','Text'];var translateLegacyCodec=function translateLegacyCodec(codec){if(!codec){return codec;}
return codec.replace(/avc1\.(\d+)\.(\d+)/i,function(orig,profile,avcLevel){var profileHex=('00'+Number(profile).toString(16)).slice(-2);var avcLevelHex=('00'+Number(avcLevel).toString(16)).slice(-2);return'avc1.'+profileHex+'00'+avcLevelHex;});};var translateLegacyCodecs=function translateLegacyCodecs(codecs){return codecs.map(translateLegacyCodec);};var mapLegacyAvcCodecs=function mapLegacyAvcCodecs(codecString){return codecString.replace(/avc1\.(\d+)\.(\d+)/i,function(match){return translateLegacyCodecs([match])[0];});};var parseCodecs=function parseCodecs(codecString){if(codecString===void 0){codecString='';}
var codecs=codecString.split(',');var result={};var unknown=[];codecs.forEach(function(codec){codec=codec.trim();var codecType;mediaTypes.forEach(function(name){var match=regexs[name].exec(codec.toLowerCase());if(!match||match.length<=1){return;}
codecType=name;var type=codec.substring(0,match[1].length);var details=codec.replace(type,'');result[name]={type:type,details:details};});if(!codecType){unknown.push(codec);}});if(unknown.length){result.unknown=unknown;}
return result;};var codecsFromDefault=function codecsFromDefault(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;};var isVideoCodec=function isVideoCodec(codec){if(codec===void 0){codec='';}
return regexs.video.test(codec.trim().toLowerCase());};var isAudioCodec=function isAudioCodec(codec){if(codec===void 0){codec='';}
return regexs.audio.test(codec.trim().toLowerCase());};var isTextCodec=function isTextCodec(codec){if(codec===void 0){codec='';}
return regexs.text.test(codec.trim().toLowerCase());};var getMimeForCodec=function getMimeForCodec(codecString){if(!codecString||typeof codecString!=='string'){return;}
var codecs=codecString.toLowerCase().split(',').map(function(c){return translateLegacyCodec(c.trim());});var type='video';if(codecs.length===1&&isAudioCodec(codecs[0])){type='audio';}else if(codecs.length===1&&isTextCodec(codecs[0])){type='application';}
var container='mp4';if(codecs.every(function(c){return regexs.mp4.test(c);})){container='mp4';}else if(codecs.every(function(c){return regexs.webm.test(c);})){container='webm';}else if(codecs.every(function(c){return regexs.ogg.test(c);})){container='ogg';}
return type+"/"+container+";codecs=\""+codecString+"\"";};var browserSupportsCodec=function browserSupportsCodec(codecString){if(codecString===void 0){codecString='';}
return window.MediaSource&&window.MediaSource.isTypeSupported&&window.MediaSource.isTypeSupported(getMimeForCodec(codecString))||false;};var muxerSupportsCodec=function muxerSupportsCodec(codecString){if(codecString===void 0){codecString='';}
return codecString.toLowerCase().split(',').every(function(codec){codec=codec.trim();for(var i=0;i<upperMediaTypes.length;i++){var type=upperMediaTypes[i];if(regexs["muxer"+type].test(codec)){return true;}}
return false;});};var DEFAULT_AUDIO_CODEC='mp4a.40.2';var DEFAULT_VIDEO_CODEC='avc1.4d400d';exports.DEFAULT_AUDIO_CODEC=DEFAULT_AUDIO_CODEC;exports.DEFAULT_VIDEO_CODEC=DEFAULT_VIDEO_CODEC;exports.browserSupportsCodec=browserSupportsCodec;exports.codecsFromDefault=codecsFromDefault;exports.getMimeForCodec=getMimeForCodec;exports.isAudioCodec=isAudioCodec;exports.isTextCodec=isTextCodec;exports.isVideoCodec=isVideoCodec;exports.mapLegacyAvcCodecs=mapLegacyAvcCodecs;exports.muxerSupportsCodec=muxerSupportsCodec;exports.parseCodecs=parseCodecs;exports.translateLegacyCodec=translateLegacyCodec;exports.translateLegacyCodecs=translateLegacyCodecs;});unwrapExports(codecs);var codecs_1=codecs.DEFAULT_AUDIO_CODEC;var codecs_2=codecs.DEFAULT_VIDEO_CODEC;var codecs_3=codecs.browserSupportsCodec;var codecs_4=codecs.codecsFromDefault;var codecs_5=codecs.getMimeForCodec;var codecs_6=codecs.isAudioCodec;var codecs_7=codecs.isTextCodec;var codecs_8=codecs.isVideoCodec;var codecs_9=codecs.mapLegacyAvcCodecs;var codecs_10=codecs.muxerSupportsCodec;var codecs_11=codecs.parseCodecs;var codecs_12=codecs.translateLegacyCodec;var codecs_13=codecs.translateLegacyCodecs;var resolveUrl$1=resolveUrl_1;var resolveManifestRedirect=function resolveManifestRedirect(handleManifestRedirect,url,req){if(handleManifestRedirect&&req&&req.responseURL&&url!==req.responseURL){return req.responseURL;}
return url;};var log$1=videojs$1.log;var createPlaylistID=function createPlaylistID(index,uri){return index+"-"+uri;};var parseManifest=function parseManifest(_ref){var manifestString=_ref.manifestString,_ref$customTagParsers=_ref.customTagParsers,customTagParsers=_ref$customTagParsers===void 0?[]:_ref$customTagParsers,_ref$customTagMappers=_ref.customTagMappers,customTagMappers=_ref$customTagMappers===void 0?[]:_ref$customTagMappers;var parser=new Parser();customTagParsers.forEach(function(customParser){return parser.addParser(customParser);});customTagMappers.forEach(function(mapper){return parser.addTagMapper(mapper);});parser.push(manifestString);parser.end();return parser.manifest;};var forEachMediaGroup=function forEachMediaGroup(master,callback){['AUDIO','SUBTITLES'].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);}}});};var setupMediaPlaylist=function setupMediaPlaylist(_ref2){var playlist=_ref2.playlist,uri=_ref2.uri,id=_ref2.id;playlist.id=id;if(uri){playlist.uri=uri;}
playlist.attributes=playlist.attributes||{};};var setupMediaPlaylists=function setupMediaPlaylists(master){var i=master.playlists.length;while(i--){var playlist=master.playlists[i];setupMediaPlaylist({playlist:playlist,id:createPlaylistID(i,playlist.uri)});playlist.resolvedUri=resolveUrl$1(master.uri,playlist.uri);master.playlists[playlist.id]=playlist;master.playlists[playlist.uri]=playlist;if(!playlist.attributes.BANDWIDTH){log$1.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');}}};var resolveMediaGroupUris=function resolveMediaGroupUris(master){forEachMediaGroup(master,function(properties){if(properties.uri){properties.resolvedUri=resolveUrl$1(master.uri,properties.uri);}});};var masterForMedia=function masterForMedia(media,uri){var id=createPlaylistID(0,uri);var master={mediaGroups:{'AUDIO':{},'VIDEO':{},'CLOSED-CAPTIONS':{},'SUBTITLES':{}},uri:window_1$2.location.href,resolvedUri:window_1$2.location.href,playlists:[{uri:uri,id:id,resolvedUri:uri,attributes:{}}]};master.playlists[id]=master.playlists[0];master.playlists[uri]=master.playlists[0];return master;};var addPropertiesToMaster=function addPropertiesToMaster(master,uri){master.uri=uri;for(var i=0;i<master.playlists.length;i++){if(!master.playlists[i].uri){var phonyUri="placeholder-uri-"+i;master.playlists[i].uri=phonyUri;}}
forEachMediaGroup(master,function(properties,mediaType,groupKey,labelKey){if(!properties.playlists||!properties.playlists.length||properties.playlists[0].uri){return;}
var phonyUri="placeholder-uri-"+mediaType+"-"+groupKey+"-"+labelKey;var id=createPlaylistID(0,phonyUri);properties.playlists[0].uri=phonyUri;properties.playlists[0].id=id;master.playlists[id]=properties.playlists[0];master.playlists[phonyUri]=properties.playlists[0];});setupMediaPlaylists(master);resolveMediaGroupUris(master);};var mergeOptions$1=videojs$1.mergeOptions,EventTarget$1=videojs$1.EventTarget;var updateSegments=function updateSegments(original,update,offset){var result=update.slice();offset=offset||0;var length=Math.min(original.length,update.length+offset);for(var i=offset;i<length;i++){result[i-offset]=mergeOptions$1(original[i],result[i-offset]);}
return result;};var resolveSegmentUris=function resolveSegmentUris(segment,baseUri){if(!segment.resolvedUri){segment.resolvedUri=resolveUrl$1(baseUri,segment.uri);}
if(segment.key&&!segment.key.resolvedUri){segment.key.resolvedUri=resolveUrl$1(baseUri,segment.key.uri);}
if(segment.map&&!segment.map.resolvedUri){segment.map.resolvedUri=resolveUrl$1(baseUri,segment.map.uri);}};var updateMaster=function updateMaster(master,media){var result=mergeOptions$1(master,{});var playlist=result.playlists[media.id];if(!playlist){return null;}
if(playlist.segments&&media.segments&&playlist.segments.length===media.segments.length&&playlist.endList===media.endList&&playlist.mediaSequence===media.mediaSequence){return null;}
var mergedPlaylist=mergeOptions$1(playlist,media);if(playlist.segments){mergedPlaylist.segments=updateSegments(playlist.segments,media.segments,media.mediaSequence-playlist.mediaSequence);}
mergedPlaylist.segments.forEach(function(segment){resolveSegmentUris(segment,mergedPlaylist.resolvedUri);});for(var i=0;i<result.playlists.length;i++){if(result.playlists[i].id===media.id){result.playlists[i]=mergedPlaylist;}}
result.playlists[media.id]=mergedPlaylist;result.playlists[media.uri]=mergedPlaylist;return result;};var refreshDelay=function refreshDelay(media,update){var lastSegment=media.segments[media.segments.length-1];var delay;if(update&&lastSegment&&lastSegment.duration){delay=lastSegment.duration*1000;}else{delay=(media.targetDuration||10)*500;}
return delay;};var PlaylistLoader=function(_EventTarget){inheritsLoose$1(PlaylistLoader,_EventTarget);function PlaylistLoader(src,vhs,options){var _this;if(options===void 0){options={};}
_this=_EventTarget.call(this)||this;if(!src){throw new Error('A non-empty playlist URL or object is required');}
var _options=options,_options$withCredenti=_options.withCredentials,withCredentials=_options$withCredenti===void 0?false:_options$withCredenti,_options$handleManife=_options.handleManifestRedirects,handleManifestRedirects=_options$handleManife===void 0?false:_options$handleManife;_this.src=src;_this.vhs_=vhs;_this.withCredentials=withCredentials;_this.handleManifestRedirects=handleManifestRedirects;var vhsOptions=vhs.options_;_this.customTagParsers=vhsOptions&&vhsOptions.customTagParsers||[];_this.customTagMappers=vhsOptions&&vhsOptions.customTagMappers||[];_this.state='HAVE_NOTHING';_this.on('mediaupdatetimeout',function(){if(_this.state!=='HAVE_METADATA'){return;}
_this.state='HAVE_CURRENT_METADATA';_this.request=_this.vhs_.xhr({uri:resolveUrl$1(_this.master.uri,_this.media().uri),withCredentials:_this.withCredentials},function(error,req){if(!_this.request){return;}
if(error){return _this.playlistRequestError(_this.request,_this.media(),'HAVE_METADATA');}
_this.haveMetadata({playlistString:_this.request.responseText,url:_this.media().uri,id:_this.media().id});});});return _this;}
var _proto=PlaylistLoader.prototype;_proto.playlistRequestError=function playlistRequestError(xhr,playlist,startingState){var uri=playlist.uri,id=playlist.id;this.request=null;if(startingState){this.state=startingState;}
this.error={playlist:this.master.playlists[id],status:xhr.status,message:"HLS playlist request error at URL: "+uri+".",responseText:xhr.responseText,code:xhr.status>=500?4:2};this.trigger('error');};_proto.haveMetadata=function haveMetadata(_ref){var _this2=this;var playlistString=_ref.playlistString,playlistObject=_ref.playlistObject,url=_ref.url,id=_ref.id;this.request=null;this.state='HAVE_METADATA';var playlist=playlistObject||parseManifest({manifestString:playlistString,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers});playlist.lastRequest=Date.now();setupMediaPlaylist({playlist:playlist,uri:url,id:id});var update=updateMaster(this.master,playlist);this.targetDuration=playlist.targetDuration;if(update){this.master=update;this.media_=this.master.playlists[id];}else{this.trigger('playlistunchanged');}
if(!this.media().endList){window_1$2.clearTimeout(this.mediaUpdateTimeout);this.mediaUpdateTimeout=window_1$2.setTimeout(function(){_this2.trigger('mediaupdatetimeout');},refreshDelay(this.media(),!!update));}
this.trigger('loadedplaylist');};_proto.dispose=function dispose(){this.trigger('dispose');this.stopRequest();window_1$2.clearTimeout(this.mediaUpdateTimeout);window_1$2.clearTimeout(this.finalRenditionTimeout);this.off();};_proto.stopRequest=function stopRequest(){if(this.request){var oldRequest=this.request;this.request=null;oldRequest.onreadystatechange=null;oldRequest.abort();}};_proto.media=function media(playlist,shouldDelay){var _this3=this;if(!playlist){return this.media_;}
if(this.state==='HAVE_NOTHING'){throw new Error('Cannot switch media playlist from '+this.state);}
if(typeof playlist==='string'){if(!this.master.playlists[playlist]){throw new Error('Unknown playlist URI: '+playlist);}
playlist=this.master.playlists[playlist];}
window_1$2.clearTimeout(this.finalRenditionTimeout);if(shouldDelay){var delay=playlist.targetDuration/2*1000||5*1000;this.finalRenditionTimeout=window_1$2.setTimeout(this.media.bind(this,playlist,false),delay);return;}
var startingState=this.state;var mediaChange=!this.media_||playlist.id!==this.media_.id;if(this.master.playlists[playlist.id].endList||playlist.endList&&playlist.segments.length){if(this.request){this.request.onreadystatechange=null;this.request.abort();this.request=null;}
this.state='HAVE_METADATA';this.media_=playlist;if(mediaChange){this.trigger('mediachanging');if(startingState==='HAVE_MASTER'){this.trigger('loadedmetadata');}else{this.trigger('mediachange');}}
return;}
if(!mediaChange){return;}
this.state='SWITCHING_MEDIA';if(this.request){if(playlist.resolvedUri===this.request.url){return;}
this.request.onreadystatechange=null;this.request.abort();this.request=null;}
if(this.media_){this.trigger('mediachanging');}
this.request=this.vhs_.xhr({uri:playlist.resolvedUri,withCredentials:this.withCredentials},function(error,req){if(!_this3.request){return;}
playlist.lastRequest=Date.now();playlist.resolvedUri=resolveManifestRedirect(_this3.handleManifestRedirects,playlist.resolvedUri,req);if(error){return _this3.playlistRequestError(_this3.request,playlist,startingState);}
_this3.haveMetadata({playlistString:req.responseText,url:playlist.uri,id:playlist.id});if(startingState==='HAVE_MASTER'){_this3.trigger('loadedmetadata');}else{_this3.trigger('mediachange');}});};_proto.pause=function pause(){this.stopRequest();window_1$2.clearTimeout(this.mediaUpdateTimeout);if(this.state==='HAVE_NOTHING'){this.started=false;}
if(this.state==='SWITCHING_MEDIA'){if(this.media_){this.state='HAVE_METADATA';}else{this.state='HAVE_MASTER';}}else if(this.state==='HAVE_CURRENT_METADATA'){this.state='HAVE_METADATA';}};_proto.load=function load(shouldDelay){var _this4=this;window_1$2.clearTimeout(this.mediaUpdateTimeout);var media=this.media();if(shouldDelay){var delay=media?media.targetDuration/2*1000:5*1000;this.mediaUpdateTimeout=window_1$2.setTimeout(function(){return _this4.load();},delay);return;}
if(!this.started){this.start();return;}
if(media&&!media.endList){this.trigger('mediaupdatetimeout');}else{this.trigger('loadedplaylist');}};_proto.start=function start(){var _this5=this;this.started=true;if(typeof this.src==='object'){if(!this.src.uri){this.src.uri=window_1$2.location.href;}
this.src.resolvedUri=this.src.uri;setTimeout(function(){_this5.setupInitialPlaylist(_this5.src);},0);return;}
this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials},function(error,req){if(!_this5.request){return;}
_this5.request=null;if(error){_this5.error={status:req.status,message:"HLS playlist request error at URL: "+_this5.src+".",responseText:req.responseText,code:2};if(_this5.state==='HAVE_NOTHING'){_this5.started=false;}
return _this5.trigger('error');}
_this5.src=resolveManifestRedirect(_this5.handleManifestRedirects,_this5.src,req);var manifest=parseManifest({manifestString:req.responseText,customTagParsers:_this5.customTagParsers,customTagMappers:_this5.customTagMappers});_this5.setupInitialPlaylist(manifest);});};_proto.srcUri=function srcUri(){return typeof this.src==='string'?this.src:this.src.uri;};_proto.setupInitialPlaylist=function setupInitialPlaylist(manifest){this.state='HAVE_MASTER';if(manifest.playlists){this.master=manifest;addPropertiesToMaster(this.master,this.srcUri());manifest.playlists.forEach(function(playlist){if(playlist.segments){playlist.segments.forEach(function(segment){resolveSegmentUris(segment,playlist.resolvedUri);});}});this.trigger('loadedplaylist');if(!this.request){this.media(this.master.playlists[0]);}
return;}
var uri=this.srcUri()||window_1$2.location.href;this.master=masterForMedia(manifest,uri);this.haveMetadata({playlistObject:manifest,url:uri,id:this.master.playlists[0].id});this.trigger('loadedmetadata');};return PlaylistLoader;}(EventTarget$1);var TIME_FUDGE_FACTOR=1/30;var SAFE_TIME_DELTA=TIME_FUDGE_FACTOR*3;var filterRanges=function filterRanges(timeRanges,predicate){var results=[];var i;if(timeRanges&&timeRanges.length){for(i=0;i<timeRanges.length;i++){if(predicate(timeRanges.start(i),timeRanges.end(i))){results.push([timeRanges.start(i),timeRanges.end(i)]);}}}
return videojs$1.createTimeRanges(results);};var findRange=function findRange(buffered,time){return filterRanges(buffered,function(start,end){return start-SAFE_TIME_DELTA<=time&&end+SAFE_TIME_DELTA>=time;});};var findNextRange=function findNextRange(timeRanges,time){return filterRanges(timeRanges,function(start){return start-TIME_FUDGE_FACTOR>=time;});};var findGaps=function findGaps(buffered){if(buffered.length<2){return videojs$1.createTimeRanges();}
var ranges=[];for(var i=1;i<buffered.length;i++){var start=buffered.end(i-1);var end=buffered.start(i);ranges.push([start,end]);}
return videojs$1.createTimeRanges(ranges);};var bufferIntersection=function bufferIntersection(bufferA,bufferB){var start=null;var end=null;var arity=0;var extents=[];var ranges=[];if(!bufferA||!bufferA.length||!bufferB||!bufferB.length){return videojs$1.createTimeRange();}
var count=bufferA.length;while(count--){extents.push({time:bufferA.start(count),type:'start'});extents.push({time:bufferA.end(count),type:'end'});}
count=bufferB.length;while(count--){extents.push({time:bufferB.start(count),type:'start'});extents.push({time:bufferB.end(count),type:'end'});}
extents.sort(function(a,b){return a.time-b.time;});for(count=0;count<extents.length;count++){if(extents[count].type==='start'){arity++;if(arity===2){start=extents[count].time;}}else if(extents[count].type==='end'){arity--;if(arity===1){end=extents[count].time;}}
if(start!==null&&end!==null){ranges.push([start,end]);start=null;end=null;}}
return videojs$1.createTimeRanges(ranges);};var printableRange=function printableRange(range){var strArr=[];if(!range||!range.length){return'';}
for(var i=0;i<range.length;i++){strArr.push(range.start(i)+' => '+range.end(i));}
return strArr.join(', ');};var timeUntilRebuffer=function timeUntilRebuffer(buffered,currentTime,playbackRate){if(playbackRate===void 0){playbackRate=1;}
var bufferedEnd=buffered.length?buffered.end(buffered.length-1):0;return(bufferedEnd-currentTime)/playbackRate;};var timeRangesToArray=function timeRangesToArray(timeRanges){var timeRangesList=[];for(var i=0;i<timeRanges.length;i++){timeRangesList.push({start:timeRanges.start(i),end:timeRanges.end(i)});}
return timeRangesList;};var isRangeDifferent=function isRangeDifferent(a,b){if(a===b){return false;}
if(!a&&b||!b&&a){return true;}
if(a.length!==b.length){return true;}
for(var i=0;i<a.length;i++){if(a.start(i)!==b.start(i)||a.end(i)!==b.end(i)){return true;}}
return false;};var createTimeRange=videojs$1.createTimeRange;var backwardDuration=function backwardDuration(playlist,endSequence){var result=0;var i=endSequence-playlist.mediaSequence;var segment=playlist.segments[i];if(segment){if(typeof segment.start!=='undefined'){return{result:segment.start,precise:true};}
if(typeof segment.end!=='undefined'){return{result:segment.end-segment.duration,precise:true};}}
while(i--){segment=playlist.segments[i];if(typeof segment.end!=='undefined'){return{result:result+segment.end,precise:true};}
result+=segment.duration;if(typeof segment.start!=='undefined'){return{result:result+segment.start,precise:true};}}
return{result:result,precise:false};};var forwardDuration=function forwardDuration(playlist,endSequence){var result=0;var segment;var i=endSequence-playlist.mediaSequence;for(;i<playlist.segments.length;i++){segment=playlist.segments[i];if(typeof segment.start!=='undefined'){return{result:segment.start-result,precise:true};}
result+=segment.duration;if(typeof segment.end!=='undefined'){return{result:segment.end-result,precise:true};}}
return{result:-1,precise:false};};var intervalDuration=function intervalDuration(playlist,endSequence,expired){if(typeof endSequence==='undefined'){endSequence=playlist.mediaSequence+playlist.segments.length;}
if(endSequence<playlist.mediaSequence){return 0;}
var backward=backwardDuration(playlist,endSequence);if(backward.precise){return backward.result;}
var forward=forwardDuration(playlist,endSequence);if(forward.precise){return forward.result;}
return backward.result+expired;};var duration=function duration(playlist,endSequence,expired){if(!playlist){return 0;}
if(typeof expired!=='number'){expired=0;}
if(typeof endSequence==='undefined'){if(playlist.totalDuration){return playlist.totalDuration;}
if(!playlist.endList){return window_1$2.Infinity;}}
return intervalDuration(playlist,endSequence,expired);};var sumDurations=function sumDurations(playlist,startIndex,endIndex){var durations=0;if(startIndex>endIndex){var _ref=[endIndex,startIndex];startIndex=_ref[0];endIndex=_ref[1];}
if(startIndex<0){for(var i=startIndex;i<Math.min(0,endIndex);i++){durations+=playlist.targetDuration;}
startIndex=0;}
for(var _i=startIndex;_i<endIndex;_i++){durations+=playlist.segments[_i].duration;}
return durations;};var safeLiveIndex=function safeLiveIndex(playlist,liveEdgePadding){if(!playlist.segments.length){return 0;}
var i=playlist.segments.length;var lastSegmentDuration=playlist.segments[i-1].duration||playlist.targetDuration;var safeDistance=typeof liveEdgePadding==='number'?liveEdgePadding:lastSegmentDuration+playlist.targetDuration*2;if(safeDistance===0){return i;}
var distanceFromEnd=0;while(i--){distanceFromEnd+=playlist.segments[i].duration;if(distanceFromEnd>=safeDistance){break;}}
return Math.max(0,i);};var playlistEnd=function playlistEnd(playlist,expired,useSafeLiveEnd,liveEdgePadding){if(!playlist||!playlist.segments){return null;}
if(playlist.endList){return duration(playlist);}
if(expired===null){return null;}
expired=expired||0;var endSequence=useSafeLiveEnd?safeLiveIndex(playlist,liveEdgePadding):playlist.segments.length;return intervalDuration(playlist,playlist.mediaSequence+endSequence,expired);};var seekable=function seekable(playlist,expired,liveEdgePadding){var useSafeLiveEnd=true;var seekableStart=expired||0;var seekableEnd=playlistEnd(playlist,expired,useSafeLiveEnd,liveEdgePadding);if(seekableEnd===null){return createTimeRange();}
return createTimeRange(seekableStart,seekableEnd);};var getMediaInfoForTime=function getMediaInfoForTime(playlist,currentTime,startIndex,startTime){var i;var segment;var numSegments=playlist.segments.length;var time=currentTime-startTime;if(time<0){if(startIndex>0){for(i=startIndex-1;i>=0;i--){segment=playlist.segments[i];time+=segment.duration+TIME_FUDGE_FACTOR;if(time>0){return{mediaIndex:i,startTime:startTime-sumDurations(playlist,startIndex,i)};}}}
return{mediaIndex:0,startTime:currentTime};}
if(startIndex<0){for(i=startIndex;i<0;i++){time-=playlist.targetDuration;if(time<0){return{mediaIndex:0,startTime:currentTime};}}
startIndex=0;}
for(i=startIndex;i<numSegments;i++){segment=playlist.segments[i];time-=segment.duration+TIME_FUDGE_FACTOR;if(time<0){return{mediaIndex:i,startTime:startTime+sumDurations(playlist,startIndex,i)};}}
return{mediaIndex:numSegments-1,startTime:currentTime};};var isBlacklisted=function isBlacklisted(playlist){return playlist.excludeUntil&&playlist.excludeUntil>Date.now();};var isIncompatible=function isIncompatible(playlist){return playlist.excludeUntil&&playlist.excludeUntil===Infinity;};var isEnabled=function isEnabled(playlist){var blacklisted=isBlacklisted(playlist);return!playlist.disabled&&!blacklisted;};var isDisabled=function isDisabled(playlist){return playlist.disabled;};var isAes=function isAes(media){for(var i=0;i<media.segments.length;i++){if(media.segments[i].key){return true;}}
return false;};var hasAttribute=function hasAttribute(attr,playlist){return playlist.attributes&&playlist.attributes[attr];};var estimateSegmentRequestTime=function estimateSegmentRequestTime(segmentDuration,bandwidth,playlist,bytesReceived){if(bytesReceived===void 0){bytesReceived=0;}
if(!hasAttribute('BANDWIDTH',playlist)){return NaN;}
var size=segmentDuration*playlist.attributes.BANDWIDTH;return(size-bytesReceived*8)/bandwidth;};var isLowestEnabledRendition=function isLowestEnabledRendition(master,media){if(master.playlists.length===1){return true;}
var currentBandwidth=media.attributes.BANDWIDTH||Number.MAX_VALUE;return master.playlists.filter(function(playlist){if(!isEnabled(playlist)){return false;}
return(playlist.attributes.BANDWIDTH||0)<currentBandwidth;}).length===0;};var Playlist={duration:duration,seekable:seekable,safeLiveIndex:safeLiveIndex,getMediaInfoForTime:getMediaInfoForTime,isEnabled:isEnabled,isDisabled:isDisabled,isBlacklisted:isBlacklisted,isIncompatible:isIncompatible,playlistEnd:playlistEnd,isAes:isAes,hasAttribute:hasAttribute,estimateSegmentRequestTime:estimateSegmentRequestTime,isLowestEnabledRendition:isLowestEnabledRendition};var videojsXHR=videojs$1.xhr,mergeOptions$1$1=videojs$1.mergeOptions;var callbackWrapper=function callbackWrapper(request,error,response,callback){var reqResponse=request.responseType==='arraybuffer'?request.response:request.responseText;if(!error&&reqResponse){request.responseTime=Date.now();request.roundTripTime=request.responseTime-request.requestTime;request.bytesReceived=reqResponse.byteLength||reqResponse.length;if(!request.bandwidth){request.bandwidth=Math.floor(request.bytesReceived/request.roundTripTime*8*1000);}}
if(response.headers){request.responseHeaders=response.headers;}
if(error&&error.code==='ETIMEDOUT'){request.timedout=true;}
if(!error&&!request.aborted&&response.statusCode!==200&&response.statusCode!==206&&response.statusCode!==0){error=new Error('XHR Failed with a response of: '+(request&&(reqResponse||request.responseText)));}
callback(error,request);};var xhrFactory=function xhrFactory(){var xhr=function XhrFunction(options,callback){options=mergeOptions$1$1({timeout:45e3},options);var beforeRequest=XhrFunction.beforeRequest||videojs$1.Vhs.xhr.beforeRequest;if(beforeRequest&&typeof beforeRequest==='function'){var newOptions=beforeRequest(options);if(newOptions){options=newOptions;}}
var request=videojsXHR(options,function(error,response){return callbackWrapper(request,error,response,callback);});var originalAbort=request.abort;request.abort=function(){request.aborted=true;return originalAbort.apply(request,arguments);};request.uri=options.uri;request.requestTime=Date.now();return request;};return xhr;};var byterangeStr=function byterangeStr(byterange){var byterangeEnd=byterange.offset+byterange.length-1;var byterangeStart=byterange.offset;return'bytes='+byterangeStart+'-'+byterangeEnd;};var segmentXhrHeaders=function segmentXhrHeaders(segment){var headers={};if(segment.byterange){headers.Range=byterangeStr(segment.byterange);}
return headers;};var textRange=function textRange(range,i){return range.start(i)+'-'+range.end(i);};var formatHexString=function formatHexString(e,i){var value=e.toString(16);return'00'.substring(0,2-value.length)+value+(i%2?' ':'');};var formatAsciiString=function formatAsciiString(e){if(e>=0x20&&e<0x7e){return String.fromCharCode(e);}
return'.';};var createTransferableMessage=function createTransferableMessage(message){var transferable={};Object.keys(message).forEach(function(key){var value=message[key];if(ArrayBuffer.isView(value)){transferable[key]={bytes:value.buffer,byteOffset:value.byteOffset,byteLength:value.byteLength};}else{transferable[key]=value;}});return transferable;};var initSegmentId=function initSegmentId(initSegment){var byterange=initSegment.byterange||{length:Infinity,offset:0};return[byterange.length,byterange.offset,initSegment.resolvedUri].join(',');};var segmentKeyId=function segmentKeyId(key){return key.resolvedUri;};var hexDump=function hexDump(data){var bytes=Array.prototype.slice.call(data);var step=16;var result='';var hex;var ascii;for(var j=0;j<bytes.length/step;j++){hex=bytes.slice(j*step,j*step+step).map(formatHexString).join('');ascii=bytes.slice(j*step,j*step+step).map(formatAsciiString).join('');result+=hex+' '+ascii+'\n';}
return result;};var tagDump=function tagDump(_ref){var bytes=_ref.bytes;return hexDump(bytes);};var textRanges=function textRanges(ranges){var result='';var i;for(i=0;i<ranges.length;i++){result+=textRange(ranges,i)+' ';}
return result;};var utils$1=Object.freeze({__proto__:null,createTransferableMessage:createTransferableMessage,initSegmentId:initSegmentId,segmentKeyId:segmentKeyId,hexDump:hexDump,tagDump:tagDump,textRanges:textRanges});var SEGMENT_END_FUDGE_PERCENT=0.25;var playerTimeToProgramTime=function playerTimeToProgramTime(playerTime,segment){if(!segment.dateTimeObject){return null;}
var transmuxerPrependedSeconds=segment.videoTimingInfo.transmuxerPrependedSeconds;var transmuxedStart=segment.videoTimingInfo.transmuxedPresentationStart;var startOfSegment=transmuxedStart+transmuxerPrependedSeconds;var offsetFromSegmentStart=playerTime-startOfSegment;return new Date(segment.dateTimeObject.getTime()+offsetFromSegmentStart*1000);};var originalSegmentVideoDuration=function originalSegmentVideoDuration(videoTimingInfo){return videoTimingInfo.transmuxedPresentationEnd-videoTimingInfo.transmuxedPresentationStart-videoTimingInfo.transmuxerPrependedSeconds;};var findSegmentForProgramTime=function findSegmentForProgramTime(programTime,playlist){var dateTimeObject;try{dateTimeObject=new Date(programTime);}catch(e){return null;}
if(!playlist||!playlist.segments||playlist.segments.length===0){return null;}
var segment=playlist.segments[0];if(dateTimeObject<segment.dateTimeObject){return null;}
for(var i=0;i<playlist.segments.length-1;i++){segment=playlist.segments[i];var nextSegmentStart=playlist.segments[i+1].dateTimeObject;if(dateTimeObject<nextSegmentStart){break;}}
var lastSegment=playlist.segments[playlist.segments.length-1];var lastSegmentStart=lastSegment.dateTimeObject;var lastSegmentDuration=lastSegment.videoTimingInfo?originalSegmentVideoDuration(lastSegment.videoTimingInfo):lastSegment.duration+lastSegment.duration*SEGMENT_END_FUDGE_PERCENT;var lastSegmentEnd=new Date(lastSegmentStart.getTime()+lastSegmentDuration*1000);if(dateTimeObject>lastSegmentEnd){return null;}
if(dateTimeObject>lastSegmentStart){segment=lastSegment;}
return{segment:segment,estimatedStart:segment.videoTimingInfo?segment.videoTimingInfo.transmuxedPresentationStart:Playlist.duration(playlist,playlist.mediaSequence+playlist.segments.indexOf(segment)),type:segment.videoTimingInfo?'accurate':'estimate'};};var findSegmentForPlayerTime=function findSegmentForPlayerTime(time,playlist){if(!playlist||!playlist.segments||playlist.segments.length===0){return null;}
var segmentEnd=0;var segment;for(var i=0;i<playlist.segments.length;i++){segment=playlist.segments[i];segmentEnd=segment.videoTimingInfo?segment.videoTimingInfo.transmuxedPresentationEnd:segmentEnd+segment.duration;if(time<=segmentEnd){break;}}
var lastSegment=playlist.segments[playlist.segments.length-1];if(lastSegment.videoTimingInfo&&lastSegment.videoTimingInfo.transmuxedPresentationEnd<time){return null;}
if(time>segmentEnd){if(time>segmentEnd+lastSegment.duration*SEGMENT_END_FUDGE_PERCENT){return null;}
segment=lastSegment;}
return{segment:segment,estimatedStart:segment.videoTimingInfo?segment.videoTimingInfo.transmuxedPresentationStart:segmentEnd-segment.duration,type:segment.videoTimingInfo?'accurate':'estimate'};};var getOffsetFromTimestamp=function getOffsetFromTimestamp(comparisonTimeStamp,programTime){var segmentDateTime;var programDateTime;try{segmentDateTime=new Date(comparisonTimeStamp);programDateTime=new Date(programTime);}catch(e){}
var segmentTimeEpoch=segmentDateTime.getTime();var programTimeEpoch=programDateTime.getTime();return(programTimeEpoch-segmentTimeEpoch)/1000;};var verifyProgramDateTimeTags=function verifyProgramDateTimeTags(playlist){if(!playlist.segments||playlist.segments.length===0){return false;}
for(var i=0;i<playlist.segments.length;i++){var segment=playlist.segments[i];if(!segment.dateTimeObject){return false;}}
return true;};var getProgramTime=function getProgramTime(_ref){var playlist=_ref.playlist,_ref$time=_ref.time,time=_ref$time===void 0?undefined:_ref$time,callback=_ref.callback;if(!callback){throw new Error('getProgramTime: callback must be provided');}
if(!playlist||time===undefined){return callback({message:'getProgramTime: playlist and time must be provided'});}
var matchedSegment=findSegmentForPlayerTime(time,playlist);if(!matchedSegment){return callback({message:'valid programTime was not found'});}
if(matchedSegment.type==='estimate'){return callback({message:'Accurate programTime could not be determined.'+' Please seek to e.seekTime and try again',seekTime:matchedSegment.estimatedStart});}
var programTimeObject={mediaSeconds:time};var programTime=playerTimeToProgramTime(time,matchedSegment.segment);if(programTime){programTimeObject.programDateTime=programTime.toISOString();}
return callback(null,programTimeObject);};var seekToProgramTime=function seekToProgramTime(_ref2){var programTime=_ref2.programTime,playlist=_ref2.playlist,_ref2$retryCount=_ref2.retryCount,retryCount=_ref2$retryCount===void 0?2:_ref2$retryCount,seekTo=_ref2.seekTo,_ref2$pauseAfterSeek=_ref2.pauseAfterSeek,pauseAfterSeek=_ref2$pauseAfterSeek===void 0?true:_ref2$pauseAfterSeek,tech=_ref2.tech,callback=_ref2.callback;if(!callback){throw new Error('seekToProgramTime: callback must be provided');}
if(typeof programTime==='undefined'||!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(!verifyProgramDateTimeTags(playlist)){return callback({message:'programDateTime tags must be provided in the manifest '+playlist.resolvedUri});}
var matchedSegment=findSegmentForProgramTime(programTime,playlist);if(!matchedSegment){return callback({message:programTime+" was not found in the stream"});}
var segment=matchedSegment.segment;var mediaOffset=getOffsetFromTimestamp(segment.dateTimeObject,programTime);if(matchedSegment.type==='estimate'){if(retryCount===0){return callback({message:programTime+" is not buffered yet. Try again"});}
seekTo(matchedSegment.estimatedStart+mediaOffset);tech.one('seeked',function(){seekToProgramTime({programTime:programTime,playlist:playlist,retryCount:retryCount-1,seekTo:seekTo,pauseAfterSeek:pauseAfterSeek,tech:tech,callback:callback});});return;}
var seekToTime=segment.start+mediaOffset;var seekedCallback=function seekedCallback(){return callback(null,tech.currentTime());};tech.one('seeked',seekedCallback);if(pauseAfterSeek){tech.pause();}
seekTo(seekToTime);};var callbackOnCompleted=function callbackOnCompleted(request,cb){if(request.readyState===4){return cb();}
return;};var containerRequest=function containerRequest(uri,xhr,cb){var bytes=[];var id3Offset;var finished=false;var endRequestAndCallback=function endRequestAndCallback(err,req,type,_bytes){req.abort();finished=true;return cb(err,req,type,_bytes);};var progressListener=function progressListener(error,request){if(finished){return;}
if(error){return endRequestAndCallback(error,request,'',bytes);}
var newPart=request.responseText.substring(bytes&&bytes.byteLength||0,request.responseText.length);bytes=byteHelpers_2(bytes,byteHelpers_4(newPart,true));id3Offset=id3Offset||containers_2(bytes);if(bytes.length<10||id3Offset&&bytes.length<id3Offset+2){return callbackOnCompleted(request,function(){return endRequestAndCallback(error,request,'',bytes);});}
var type=containers_1(bytes);if(type==='ts'&&bytes.length<188){return callbackOnCompleted(request,function(){return endRequestAndCallback(error,request,'',bytes);});}
if(!type&&bytes.length<376){return callbackOnCompleted(request,function(){return endRequestAndCallback(error,request,'',bytes);});}
return endRequestAndCallback(null,request,type,bytes);};var options={uri:uri,beforeSend:function beforeSend(request){request.overrideMimeType('text/plain; charset=x-user-defined');request.addEventListener('progress',function(_ref){var total=_ref.total,loaded=_ref.loaded;return callbackWrapper(request,null,{statusCode:request.status},progressListener);});}};var request=xhr(options,function(error,response){return callbackWrapper(request,error,response,progressListener);});return request;};var EventTarget$1$1=videojs$1.EventTarget,mergeOptions$2=videojs$1.mergeOptions;var parseMasterXml=function parseMasterXml(_ref){var masterXml=_ref.masterXml,srcUrl=_ref.srcUrl,clientOffset=_ref.clientOffset,sidxMapping=_ref.sidxMapping;var master=parse(masterXml,{manifestUri:srcUrl,clientOffset:clientOffset,sidxMapping:sidxMapping});addPropertiesToMaster(master,srcUrl);return master;};var generateSidxKey=function generateSidxKey(sidxInfo){var sidxByteRangeEnd=sidxInfo.byterange.offset+sidxInfo.byterange.length-1;return sidxInfo.uri+'-'+sidxInfo.byterange.offset+'-'+sidxByteRangeEnd;};var updateMaster$1=function updateMaster$1(oldMaster,newMaster,sidxMapping){var noChanges=true;var update=mergeOptions$2(oldMaster,{duration:newMaster.duration,minimumUpdatePeriod:newMaster.minimumUpdatePeriod});for(var i=0;i<newMaster.playlists.length;i++){var playlist=newMaster.playlists[i];if(playlist.sidx){var sidxKey=generateSidxKey(playlist.sidx);if(sidxMapping&&sidxMapping[sidxKey]){addSidxSegmentsToPlaylist(playlist,sidxMapping[sidxKey].sidx,playlist.sidx.resolvedUri);}}
var playlistUpdate=updateMaster(update,playlist);if(playlistUpdate){update=playlistUpdate;noChanges=false;}}
forEachMediaGroup(newMaster,function(properties,type,group,label){if(properties.playlists&&properties.playlists.length){var id=properties.playlists[0].id;var _playlistUpdate=updateMaster(update,properties.playlists[0]);if(_playlistUpdate){update=_playlistUpdate;update.mediaGroups[type][group][label].playlists[0]=update.playlists[id];noChanges=false;}}});if(newMaster.minimumUpdatePeriod!==oldMaster.minimumUpdatePeriod){noChanges=false;}
if(noChanges){return null;}
return update;};var equivalentSidx=function equivalentSidx(a,b){var neitherMap=Boolean(!a.map&&!b.map);var equivalentMap=neitherMap||Boolean(a.map&&b.map&&a.map.byterange.offset===b.map.byterange.offset&&a.map.byterange.length===b.map.byterange.length);return equivalentMap&&a.uri===b.uri&&a.byterange.offset===b.byterange.offset&&a.byterange.length===b.byterange.length;};var compareSidxEntry=function compareSidxEntry(playlists,oldSidxMapping){var newSidxMapping={};for(var id in playlists){var playlist=playlists[id];var currentSidxInfo=playlist.sidx;if(currentSidxInfo){var key=generateSidxKey(currentSidxInfo);if(!oldSidxMapping[key]){break;}
var savedSidxInfo=oldSidxMapping[key].sidxInfo;if(equivalentSidx(savedSidxInfo,currentSidxInfo)){newSidxMapping[key]=oldSidxMapping[key];}}}
return newSidxMapping;};var filterChangedSidxMappings=function filterChangedSidxMappings(master,oldSidxMapping){var videoSidx=compareSidxEntry(master.playlists,oldSidxMapping);var mediaGroupSidx=videoSidx;forEachMediaGroup(master,function(properties,mediaType,groupKey,labelKey){if(properties.playlists&&properties.playlists.length){var playlists=properties.playlists;mediaGroupSidx=mergeOptions$2(mediaGroupSidx,compareSidxEntry(playlists,oldSidxMapping));}});return mediaGroupSidx;};var DashPlaylistLoader=function(_EventTarget){inheritsLoose$1(DashPlaylistLoader,_EventTarget);function DashPlaylistLoader(srcUrlOrPlaylist,vhs,options,masterPlaylistLoader){var _this;if(options===void 0){options={};}
_this=_EventTarget.call(this)||this;_this.masterPlaylistLoader_=masterPlaylistLoader||assertThisInitialized$1(_this);if(!masterPlaylistLoader){_this.isMaster_=true;}
var _options=options,_options$withCredenti=_options.withCredentials,withCredentials=_options$withCredenti===void 0?false:_options$withCredenti,_options$handleManife=_options.handleManifestRedirects,handleManifestRedirects=_options$handleManife===void 0?false:_options$handleManife;_this.vhs_=vhs;_this.withCredentials=withCredentials;_this.handleManifestRedirects=handleManifestRedirects;if(!srcUrlOrPlaylist){throw new Error('A non-empty playlist URL or object is required');}
_this.on('minimumUpdatePeriod',function(){_this.refreshXml_();});_this.on('mediaupdatetimeout',function(){_this.refreshMedia_(_this.media().id);});_this.state='HAVE_NOTHING';_this.loadedPlaylists_={};if(_this.isMaster_){_this.masterPlaylistLoader_.srcUrl=srcUrlOrPlaylist;_this.masterPlaylistLoader_.sidxMapping_={};}else{_this.childPlaylist_=srcUrlOrPlaylist;}
return _this;}
var _proto=DashPlaylistLoader.prototype;_proto.requestErrored_=function requestErrored_(err,request,startingState){if(!this.request){return true;}
this.request=null;if(err){this.error=typeof err==='object'&&!(err instanceof Error)?err:{status:request.status,message:'DASH request error at URL: '+request.uri,response:request.response,code:2};if(startingState){this.state=startingState;}
this.trigger('error');return true;}};_proto.addSidxSegments_=function addSidxSegments_(playlist,startingState,cb){var _this2=this;var sidxKey=playlist.sidx&&generateSidxKey(playlist.sidx);if(!playlist.sidx||!sidxKey||this.masterPlaylistLoader_.sidxMapping_[sidxKey]){this.mediaRequest_=window_1$2.setTimeout(function(){return cb(false);},0);return;}
var uri=resolveManifestRedirect(this.handleManifestRedirects,playlist.sidx.resolvedUri);var sidxMapping=this.masterPlaylistLoader_.sidxMapping_;sidxMapping[sidxKey]={sidxInfo:playlist.sidx};var fin=function fin(err,request){if(_this2.requestErrored_(err,request,startingState)){return;}
var sidx=parseSidx_1(byteHelpers_5(request.response).subarray(8));sidxMapping[sidxKey].sidx=sidx;addSidxSegmentsToPlaylist(playlist,sidx,playlist.sidx.resolvedUri);return cb(true);};this.request=containerRequest(uri,this.vhs_.xhr,function(err,request,container,bytes){if(err){return fin(err,request);}
if(!container||container!=='mp4'){return fin({status:request.status,message:"Unsupported "+(container||'unknown')+" container type for sidx segment at URL: "+uri,response:'',playlist:playlist,internal:true,blacklistDuration:Infinity,code:2},request);}
var _playlist$sidx$bytera=playlist.sidx.byterange,offset=_playlist$sidx$bytera.offset,length=_playlist$sidx$bytera.length;if(bytes.length>=length+offset){return fin(err,{response:bytes.subarray(offset,offset+length),status:request.status,uri:request.uri});}
_this2.request=_this2.vhs_.xhr({uri:uri,responseType:'arraybuffer',headers:segmentXhrHeaders({byterange:playlist.sidx.byterange})},fin);});};_proto.dispose=function dispose(){this.trigger('dispose');this.stopRequest();this.loadedPlaylists_={};window_1$2.clearTimeout(this.minimumUpdatePeriodTimeout_);window_1$2.clearTimeout(this.mediaRequest_);window_1$2.clearTimeout(this.mediaUpdateTimeout);this.off();};_proto.hasPendingRequest=function hasPendingRequest(){return this.request||this.mediaRequest_;};_proto.stopRequest=function stopRequest(){if(this.request){var oldRequest=this.request;this.request=null;oldRequest.onreadystatechange=null;oldRequest.abort();}};_proto.media=function media(playlist){var _this3=this;if(!playlist){return this.media_;}
if(this.state==='HAVE_NOTHING'){throw new Error('Cannot switch media playlist from '+this.state);}
var startingState=this.state;if(typeof playlist==='string'){if(!this.masterPlaylistLoader_.master.playlists[playlist]){throw new Error('Unknown playlist URI: '+playlist);}
playlist=this.masterPlaylistLoader_.master.playlists[playlist];}
var mediaChange=!this.media_||playlist.id!==this.media_.id;if(mediaChange&&this.loadedPlaylists_[playlist.id]&&this.loadedPlaylists_[playlist.id].endList){this.state='HAVE_METADATA';this.media_=playlist;if(mediaChange){this.trigger('mediachanging');this.trigger('mediachange');}
return;}
if(!mediaChange){return;}
if(this.media_){this.trigger('mediachanging');}
this.addSidxSegments_(playlist,startingState,function(sidxChanged){_this3.haveMetadata({startingState:startingState,playlist:playlist});});};_proto.haveMetadata=function haveMetadata(_ref2){var startingState=_ref2.startingState,playlist=_ref2.playlist;this.state='HAVE_METADATA';this.loadedPlaylists_[playlist.id]=playlist;this.mediaRequest_=null;this.refreshMedia_(playlist.id);if(startingState==='HAVE_MASTER'){this.trigger('loadedmetadata');}else{this.trigger('mediachange');}};_proto.pause=function pause(){this.stopRequest();window_1$2.clearTimeout(this.mediaUpdateTimeout);window_1$2.clearTimeout(this.minimumUpdatePeriodTimeout_);if(this.state==='HAVE_NOTHING'){this.started=false;}};_proto.load=function load(isFinalRendition){var _this4=this;window_1$2.clearTimeout(this.mediaUpdateTimeout);window_1$2.clearTimeout(this.minimumUpdatePeriodTimeout_);var media=this.media();if(isFinalRendition){var delay=media?media.targetDuration/2*1000:5*1000;this.mediaUpdateTimeout=window_1$2.setTimeout(function(){return _this4.load();},delay);return;}
if(!this.started){this.start();return;}
if(media&&!media.endList){this.trigger('mediaupdatetimeout');}else{this.trigger('loadedplaylist');}};_proto.start=function start(){var _this5=this;this.started=true;if(!this.isMaster_){this.mediaRequest_=window_1$2.setTimeout(function(){return _this5.haveMaster_();},0);return;}
this.requestMaster_(function(req,masterChanged){_this5.haveMaster_();if(!_this5.hasPendingRequest()&&!_this5.media_){_this5.media(_this5.masterPlaylistLoader_.master.playlists[0]);}});};_proto.requestMaster_=function requestMaster_(cb){var _this6=this;this.request=this.vhs_.xhr({uri:this.masterPlaylistLoader_.srcUrl,withCredentials:this.withCredentials},function(error,req){if(_this6.requestErrored_(error,req)){if(_this6.state==='HAVE_NOTHING'){_this6.started=false;}
return;}
var masterChanged=req.responseText!==_this6.masterPlaylistLoader_.masterXml_;_this6.masterPlaylistLoader_.masterXml_=req.responseText;if(req.responseHeaders&&req.responseHeaders.date){_this6.masterLoaded_=Date.parse(req.responseHeaders.date);}else{_this6.masterLoaded_=Date.now();}
_this6.masterPlaylistLoader_.srcUrl=resolveManifestRedirect(_this6.handleManifestRedirects,_this6.masterPlaylistLoader_.srcUrl,req);if(masterChanged){_this6.handleMaster_();_this6.syncClientServerClock_(function(){return cb(req,masterChanged);});return;}
return cb(req,masterChanged);});};_proto.syncClientServerClock_=function syncClientServerClock_(done){var _this7=this;var utcTiming=parseUTCTiming(this.masterPlaylistLoader_.masterXml_);if(utcTiming===null){this.masterPlaylistLoader_.clientOffset_=this.masterLoaded_-Date.now();return done();}
if(utcTiming.method==='DIRECT'){this.masterPlaylistLoader_.clientOffset_=utcTiming.value-Date.now();return done();}
this.request=this.vhs_.xhr({uri:resolveUrl$1(this.masterPlaylistLoader_.srcUrl,utcTiming.value),method:utcTiming.method,withCredentials:this.withCredentials},function(error,req){if(!_this7.request){return;}
if(error){_this7.masterPlaylistLoader_.clientOffset_=_this7.masterLoaded_-Date.now();return done();}
var serverTime;if(utcTiming.method==='HEAD'){if(!req.responseHeaders||!req.responseHeaders.date){serverTime=_this7.masterLoaded_;}else{serverTime=Date.parse(req.responseHeaders.date);}}else{serverTime=Date.parse(req.responseText);}
_this7.masterPlaylistLoader_.clientOffset_=serverTime-Date.now();done();});};_proto.haveMaster_=function haveMaster_(){this.state='HAVE_MASTER';if(this.isMaster_){this.trigger('loadedplaylist');}else if(!this.media_){this.media(this.childPlaylist_);}};_proto.handleMaster_=function handleMaster_(){this.mediaRequest_=null;var newMaster=parseMasterXml({masterXml:this.masterPlaylistLoader_.masterXml_,srcUrl:this.masterPlaylistLoader_.srcUrl,clientOffset:this.masterPlaylistLoader_.clientOffset_,sidxMapping:this.masterPlaylistLoader_.sidxMapping_});var oldMaster=this.masterPlaylistLoader_.master;if(oldMaster){newMaster=updateMaster$1(oldMaster,newMaster,this.masterPlaylistLoader_.sidxMapping_);}
this.masterPlaylistLoader_.master=newMaster?newMaster:oldMaster;var location=this.masterPlaylistLoader_.master.locations&&this.masterPlaylistLoader_.master.locations[0];if(location&&location!==this.masterPlaylistLoader_.srcUrl){this.masterPlaylistLoader_.srcUrl=location;}
if(!oldMaster||newMaster&&oldMaster.minimumUpdatePeriod!==newMaster.minimumUpdatePeriod){this.updateMinimumUpdatePeriodTimeout_();}
return Boolean(newMaster);};_proto.updateMinimumUpdatePeriodTimeout_=function updateMinimumUpdatePeriodTimeout_(){var _this8=this;window_1$2.clearTimeout(this.minimumUpdatePeriodTimeout_);var createMUPTimeout=function createMUPTimeout(mup){_this8.minimumUpdatePeriodTimeout_=window_1$2.setTimeout(function(){_this8.trigger('minimumUpdatePeriod');createMUPTimeout(mup);},mup);};var minimumUpdatePeriod=this.masterPlaylistLoader_.master&&this.masterPlaylistLoader_.master.minimumUpdatePeriod;if(minimumUpdatePeriod>0){createMUPTimeout(minimumUpdatePeriod);}else if(minimumUpdatePeriod===0){if(!this.media()){this.one('loadedplaylist',function(){createMUPTimeout(_this8.media().targetDuration*1000);});}else{createMUPTimeout(this.media().targetDuration*1000);}}};_proto.refreshXml_=function refreshXml_(){var _this9=this;this.requestMaster_(function(req,masterChanged){if(!masterChanged){return;}
if(_this9.media_){_this9.media_=_this9.masterPlaylistLoader_.master.playlists[_this9.media_.id];}
_this9.masterPlaylistLoader_.sidxMapping_=filterChangedSidxMappings(_this9.masterPlaylistLoader_.master,_this9.masterPlaylistLoader_.sidxMapping_);_this9.addSidxSegments_(_this9.media(),_this9.state,function(sidxChanged){_this9.refreshMedia_(_this9.media().id);});});};_proto.refreshMedia_=function refreshMedia_(mediaID){var _this10=this;if(!mediaID){throw new Error('refreshMedia_ must take a media id');}
if(this.media_&&this.isMaster_){this.handleMaster_();}
var playlists=this.masterPlaylistLoader_.master.playlists;var mediaChanged=!this.media_||this.media_!==playlists[mediaID];if(mediaChanged){this.media_=playlists[mediaID];}else{this.trigger('playlistunchanged');}
if(!this.media().endList){this.mediaUpdateTimeout=window_1$2.setTimeout(function(){_this10.trigger('mediaupdatetimeout');},refreshDelay(this.media(),Boolean(mediaChanged)));}
this.trigger('loadedplaylist');};return DashPlaylistLoader;}(EventTarget$1$1);var Config={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,BACK_BUFFER_LENGTH:30,GOAL_BUFFER_LENGTH_RATE:1,INITIAL_BANDWIDTH:4194304,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};var stringToArrayBuffer=function stringToArrayBuffer(string){var view=new Uint8Array(new ArrayBuffer(string.length));for(var i=0;i<string.length;i++){view[i]=string.charCodeAt(i);}
return view.buffer;};var transmuxQueue=[];var currentTransmux;var handleData_=function handleData_(event,transmuxedData,callback){var _event$data$segment=event.data.segment,type=_event$data$segment.type,initSegment=_event$data$segment.initSegment,captions=_event$data$segment.captions,captionStreams=_event$data$segment.captionStreams,metadata=_event$data$segment.metadata,videoFrameDtsTime=_event$data$segment.videoFrameDtsTime,videoFramePtsTime=_event$data$segment.videoFramePtsTime;transmuxedData.buffer.push({captions:captions,captionStreams:captionStreams,metadata:metadata});var boxes=event.data.segment.boxes||{data:event.data.segment.data};var result={type:type,data:new Uint8Array(boxes.data,boxes.data.byteOffset,boxes.data.byteLength),initSegment:new Uint8Array(initSegment.data,initSegment.byteOffset,initSegment.byteLength)};if(typeof videoFrameDtsTime!=='undefined'){result.videoFrameDtsTime=videoFrameDtsTime;}
if(typeof videoFramePtsTime!=='undefined'){result.videoFramePtsTime=videoFramePtsTime;}
callback(result);};var handleDone_=function handleDone_(_ref){var transmuxedData=_ref.transmuxedData,callback=_ref.callback;transmuxedData.buffer=[];callback(transmuxedData);};var handleGopInfo_=function handleGopInfo_(event,transmuxedData){transmuxedData.gopInfo=event.data.gopInfo;};var processTransmux=function processTransmux(_ref2){var transmuxer=_ref2.transmuxer,bytes=_ref2.bytes,audioAppendStart=_ref2.audioAppendStart,gopsToAlignWith=_ref2.gopsToAlignWith,isPartial=_ref2.isPartial,remux=_ref2.remux,onData=_ref2.onData,onTrackInfo=_ref2.onTrackInfo,onAudioTimingInfo=_ref2.onAudioTimingInfo,onVideoTimingInfo=_ref2.onVideoTimingInfo,onVideoSegmentTimingInfo=_ref2.onVideoSegmentTimingInfo,onAudioSegmentTimingInfo=_ref2.onAudioSegmentTimingInfo,onId3=_ref2.onId3,onCaptions=_ref2.onCaptions,onDone=_ref2.onDone;var transmuxedData={isPartial:isPartial,buffer:[]};var handleMessage=function handleMessage(event){if(!currentTransmux){return;}
if(event.data.action==='data'){handleData_(event,transmuxedData,onData);}
if(event.data.action==='trackinfo'){onTrackInfo(event.data.trackInfo);}
if(event.data.action==='gopInfo'){handleGopInfo_(event,transmuxedData);}
if(event.data.action==='audioTimingInfo'){onAudioTimingInfo(event.data.audioTimingInfo);}
if(event.data.action==='videoTimingInfo'){onVideoTimingInfo(event.data.videoTimingInfo);}
if(event.data.action==='videoSegmentTimingInfo'){onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);}
if(event.data.action==='audioSegmentTimingInfo'){onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);}
if(event.data.action==='id3Frame'){onId3([event.data.id3Frame],event.data.id3Frame.dispatchType);}
if(event.data.action==='caption'){onCaptions(event.data.caption);}
if(event.data.type!=='transmuxed'){return;}
transmuxer.onmessage=null;handleDone_({transmuxedData:transmuxedData,callback:onDone});dequeue();};transmuxer.onmessage=handleMessage;if(audioAppendStart){transmuxer.postMessage({action:'setAudioAppendStart',appendStart:audioAppendStart});}
if(Array.isArray(gopsToAlignWith)){transmuxer.postMessage({action:'alignGopsWith',gopsToAlignWith:gopsToAlignWith});}
if(typeof remux!=='undefined'){transmuxer.postMessage({action:'setRemux',remux:remux});}
if(bytes.byteLength){var buffer=bytes instanceof ArrayBuffer?bytes:bytes.buffer;var byteOffset=bytes instanceof ArrayBuffer?0:bytes.byteOffset;transmuxer.postMessage({action:'push',data:buffer,byteOffset:byteOffset,byteLength:bytes.byteLength},[buffer]);}
transmuxer.postMessage({action:isPartial?'partialFlush':'flush'});};var dequeue=function dequeue(){currentTransmux=null;if(transmuxQueue.length){currentTransmux=transmuxQueue.shift();if(typeof currentTransmux==='function'){currentTransmux();}else{processTransmux(currentTransmux);}}};var processAction=function processAction(transmuxer,action){transmuxer.postMessage({action:action});dequeue();};var enqueueAction=function enqueueAction(action,transmuxer){if(!currentTransmux){currentTransmux=action;processAction(transmuxer,action);return;}
transmuxQueue.push(processAction.bind(null,transmuxer,action));};var reset=function reset(transmuxer){enqueueAction('reset',transmuxer);};var endTimeline=function endTimeline(transmuxer){enqueueAction('endTimeline',transmuxer);};var transmux=function transmux(options){if(!currentTransmux){currentTransmux=options;processTransmux(options);return;}
transmuxQueue.push(options);};var dispose=function dispose(){currentTransmux=null;transmuxQueue.length=0;};var segmentTransmuxer={reset:reset,dispose:dispose,endTimeline:endTimeline,transmux:transmux};var probeTsSegment=function probeTsSegment(bytes,baseStartTime){var timeInfo=tsInspector.inspect(bytes,baseStartTime*clock_1);if(!timeInfo){return null;}
var result={hasVideo:timeInfo.video&&timeInfo.video.length===2||false,hasAudio:timeInfo.audio&&timeInfo.audio.length===2||false};if(result.hasVideo){result.videoStart=timeInfo.video[0].ptsTime;}
if(result.hasAudio){result.audioStart=timeInfo.audio[0].ptsTime;}
return result;};var concatSegments=function concatSegments(segmentObj){var offset=0;var tempBuffer;if(segmentObj.bytes){tempBuffer=new Uint8Array(segmentObj.bytes);segmentObj.segments.forEach(function(segment){tempBuffer.set(segment,offset);offset+=segment.byteLength;});}
return tempBuffer;};var REQUEST_ERRORS={FAILURE:2,TIMEOUT:-101,ABORTED:-102};var abortAll=function abortAll(activeXhrs){activeXhrs.forEach(function(xhr){xhr.abort();});};var getRequestStats=function getRequestStats(request){return{bandwidth:request.bandwidth,bytesReceived:request.bytesReceived||0,roundTripTime:request.roundTripTime||0};};var getProgressStats=function getProgressStats(progressEvent){var request=progressEvent.target;var roundTripTime=Date.now()-request.requestTime;var stats={bandwidth:Infinity,bytesReceived:0,roundTripTime:roundTripTime||0};stats.bytesReceived=progressEvent.loaded;stats.bandwidth=Math.floor(stats.bytesReceived/stats.roundTripTime*8*1000);return stats;};var handleErrors=function handleErrors(error,request){if(request.timedout){return{status:request.status,message:'HLS request timed-out at URL: '+request.uri,code:REQUEST_ERRORS.TIMEOUT,xhr:request};}
if(request.aborted){return{status:request.status,message:'HLS request aborted at URL: '+request.uri,code:REQUEST_ERRORS.ABORTED,xhr:request};}
if(error){return{status:request.status,message:'HLS request errored at URL: '+request.uri,code:REQUEST_ERRORS.FAILURE,xhr:request};}
return null;};var handleKeyResponse=function handleKeyResponse(segment,finishProcessingFn){return function(error,request){var response=request.response;var errorObj=handleErrors(error,request);if(errorObj){return finishProcessingFn(errorObj,segment);}
if(response.byteLength!==16){return finishProcessingFn({status:request.status,message:'Invalid HLS key at URL: '+request.uri,code:REQUEST_ERRORS.FAILURE,xhr:request},segment);}
var view=new DataView(response);segment.key.bytes=new Uint32Array([view.getUint32(0),view.getUint32(4),view.getUint32(8),view.getUint32(12)]);return finishProcessingFn(null,segment);};};var handleInitSegmentResponse=function handleInitSegmentResponse(_ref){var segment=_ref.segment,finishProcessingFn=_ref.finishProcessingFn;return function(error,request){var response=request.response;var errorObj=handleErrors(error,request);if(errorObj){return finishProcessingFn(errorObj,segment);}
if(response.byteLength===0){return finishProcessingFn({status:request.status,message:'Empty HLS segment content at URL: '+request.uri,code:REQUEST_ERRORS.FAILURE,xhr:request},segment);}
segment.map.bytes=new Uint8Array(request.response);var type=containers_1(segment.map.bytes);if(type!=='mp4'){return finishProcessingFn({status:request.status,message:"Found unsupported "+(type||'unknown')+" container for initialization segment at URL: "+request.uri,code:REQUEST_ERRORS.FAILURE,internal:true,xhr:request},segment);}
var tracks=probe$2.tracks(segment.map.bytes);tracks.forEach(function(track){segment.map.tracks=segment.map.tracks||{};if(segment.map.tracks[track.type]){return;}
segment.map.tracks[track.type]=track;if(typeof track.id==='number'&&track.timescale){segment.map.timescales=segment.map.timescales||{};segment.map.timescales[track.id]=track.timescale;}});return finishProcessingFn(null,segment);};};var handleSegmentResponse=function handleSegmentResponse(_ref2){var segment=_ref2.segment,finishProcessingFn=_ref2.finishProcessingFn,responseType=_ref2.responseType;return function(error,request){var response=request.response;var errorObj=handleErrors(error,request);if(errorObj){return finishProcessingFn(errorObj,segment);}
var newBytes=responseType==='arraybuffer'||!request.responseText?request.response:stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar||0));if(response.byteLength===0){return finishProcessingFn({status:request.status,message:'Empty HLS segment content at URL: '+request.uri,code:REQUEST_ERRORS.FAILURE,xhr:request},segment);}
segment.stats=getRequestStats(request);if(segment.key){segment.encryptedBytes=new Uint8Array(newBytes);}else{segment.bytes=new Uint8Array(newBytes);}
return finishProcessingFn(null,segment);};};var transmuxAndNotify=function transmuxAndNotify(_ref3){var segment=_ref3.segment,bytes=_ref3.bytes,isPartial=_ref3.isPartial,trackInfoFn=_ref3.trackInfoFn,timingInfoFn=_ref3.timingInfoFn,videoSegmentTimingInfoFn=_ref3.videoSegmentTimingInfoFn,audioSegmentTimingInfoFn=_ref3.audioSegmentTimingInfoFn,id3Fn=_ref3.id3Fn,captionsFn=_ref3.captionsFn,dataFn=_ref3.dataFn,doneFn=_ref3.doneFn;var fmp4Tracks=segment.map&&segment.map.tracks||{};var isMuxed=Boolean(fmp4Tracks.audio&&fmp4Tracks.video);var audioStartFn=timingInfoFn.bind(null,segment,'audio','start');var audioEndFn=timingInfoFn.bind(null,segment,'audio','end');var videoStartFn=timingInfoFn.bind(null,segment,'video','start');var videoEndFn=timingInfoFn.bind(null,segment,'video','end');if(!isPartial&&!segment.lastReachedChar){var probeResult=probeTsSegment(bytes,segment.baseStartTime);if(probeResult){trackInfoFn(segment,{hasAudio:probeResult.hasAudio,hasVideo:probeResult.hasVideo,isMuxed:isMuxed});trackInfoFn=null;if(probeResult.hasAudio&&!isMuxed){audioStartFn(probeResult.audioStart);}
if(probeResult.hasVideo){videoStartFn(probeResult.videoStart);}
audioStartFn=null;videoStartFn=null;}}
transmux({bytes:bytes,transmuxer:segment.transmuxer,audioAppendStart:segment.audioAppendStart,gopsToAlignWith:segment.gopsToAlignWith,isPartial:isPartial,remux:isMuxed,onData:function onData(result){result.type=result.type==='combined'?'video':result.type;dataFn(segment,result);},onTrackInfo:function onTrackInfo(trackInfo){if(trackInfoFn){if(isMuxed){trackInfo.isMuxed=true;}
trackInfoFn(segment,trackInfo);}},onAudioTimingInfo:function onAudioTimingInfo(audioTimingInfo){if(audioStartFn&&typeof audioTimingInfo.start!=='undefined'){audioStartFn(audioTimingInfo.start);audioStartFn=null;}
if(audioEndFn&&typeof audioTimingInfo.end!=='undefined'){audioEndFn(audioTimingInfo.end);}},onVideoTimingInfo:function onVideoTimingInfo(videoTimingInfo){if(videoStartFn&&typeof videoTimingInfo.start!=='undefined'){videoStartFn(videoTimingInfo.start);videoStartFn=null;}
if(videoEndFn&&typeof videoTimingInfo.end!=='undefined'){videoEndFn(videoTimingInfo.end);}},onVideoSegmentTimingInfo:function onVideoSegmentTimingInfo(videoSegmentTimingInfo){videoSegmentTimingInfoFn(videoSegmentTimingInfo);},onAudioSegmentTimingInfo:function onAudioSegmentTimingInfo(audioSegmentTimingInfo){audioSegmentTimingInfoFn(audioSegmentTimingInfo);},onId3:function onId3(id3Frames,dispatchType){id3Fn(segment,id3Frames,dispatchType);},onCaptions:function onCaptions(captions){captionsFn(segment,[captions]);},onDone:function onDone(result){if(!doneFn||isPartial){return;}
result.type=result.type==='combined'?'video':result.type;doneFn(null,segment,result);}});};var handleSegmentBytes=function handleSegmentBytes(_ref4){var segment=_ref4.segment,bytes=_ref4.bytes,isPartial=_ref4.isPartial,trackInfoFn=_ref4.trackInfoFn,timingInfoFn=_ref4.timingInfoFn,videoSegmentTimingInfoFn=_ref4.videoSegmentTimingInfoFn,audioSegmentTimingInfoFn=_ref4.audioSegmentTimingInfoFn,id3Fn=_ref4.id3Fn,captionsFn=_ref4.captionsFn,dataFn=_ref4.dataFn,doneFn=_ref4.doneFn;var bytesAsUint8Array=new Uint8Array(bytes);if(containers_5(bytesAsUint8Array)){segment.isFmp4=true;var tracks=segment.map.tracks;var trackInfo={isFmp4:true,hasVideo:!!tracks.video,hasAudio:!!tracks.audio};if(tracks.audio&&tracks.audio.codec&&tracks.audio.codec!=='enca'){trackInfo.audioCodec=tracks.audio.codec;}
if(tracks.video&&tracks.video.codec&&tracks.video.codec!=='encv'){trackInfo.videoCodec=tracks.video.codec;}
if(tracks.video&&tracks.audio){trackInfo.isMuxed=true;}
trackInfoFn(segment,trackInfo);var timingInfo=probe$2.startTime(segment.map.timescales,bytesAsUint8Array);if(trackInfo.hasAudio&&!trackInfo.isMuxed){timingInfoFn(segment,'audio','start',timingInfo);}
if(trackInfo.hasVideo){timingInfoFn(segment,'video','start',timingInfo);}
var finishLoading=function finishLoading(captions){dataFn(segment,{data:bytes,type:trackInfo.hasAudio&&!trackInfo.isMuxed?'audio':'video'});if(captions&&captions.length){captionsFn(segment,captions);}
doneFn(null,segment,{});};if(!tracks.video||!bytes.byteLength||!segment.transmuxer){finishLoading();return;}
var buffer=bytes instanceof ArrayBuffer?bytes:bytes.buffer;var byteOffset=bytes instanceof ArrayBuffer?0:bytes.byteOffset;var listenForCaptions=function listenForCaptions(event){if(event.data.action!=='mp4Captions'){return;}
segment.transmuxer.removeEventListener('message',listenForCaptions);var data=event.data.data;segment.bytes=bytes=new Uint8Array(data,data.byteOffset||0,data.byteLength);finishLoading(event.data.captions);};segment.transmuxer.addEventListener('message',listenForCaptions);segment.transmuxer.postMessage({action:'pushMp4Captions',timescales:segment.map.timescales,trackIds:[tracks.video.id],data:buffer,byteOffset:byteOffset,byteLength:bytes.byteLength},[buffer]);return;}
if(!segment.transmuxer){doneFn(null,segment,{});return;}
if(typeof segment.container==='undefined'){segment.container=containers_1(bytesAsUint8Array);}
if(segment.container!=='ts'&&segment.container!=='aac'){trackInfoFn(segment,{hasAudio:false,hasVideo:false});doneFn(null,segment,{});return;}
transmuxAndNotify({segment:segment,bytes:bytes,isPartial:isPartial,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,dataFn:dataFn,doneFn:doneFn});};var decryptSegment=function decryptSegment(_ref5){var decryptionWorker=_ref5.decryptionWorker,segment=_ref5.segment,trackInfoFn=_ref5.trackInfoFn,timingInfoFn=_ref5.timingInfoFn,videoSegmentTimingInfoFn=_ref5.videoSegmentTimingInfoFn,audioSegmentTimingInfoFn=_ref5.audioSegmentTimingInfoFn,id3Fn=_ref5.id3Fn,captionsFn=_ref5.captionsFn,dataFn=_ref5.dataFn,doneFn=_ref5.doneFn;var decryptionHandler=function decryptionHandler(event){if(event.data.source===segment.requestId){decryptionWorker.removeEventListener('message',decryptionHandler);var decrypted=event.data.decrypted;segment.bytes=new Uint8Array(decrypted.bytes,decrypted.byteOffset,decrypted.byteLength);handleSegmentBytes({segment:segment,bytes:segment.bytes,isPartial:false,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,dataFn:dataFn,doneFn:doneFn});}};decryptionWorker.addEventListener('message',decryptionHandler);var keyBytes;if(segment.key.bytes.slice){keyBytes=segment.key.bytes.slice();}else{keyBytes=new Uint32Array(Array.prototype.slice.call(segment.key.bytes));}
decryptionWorker.postMessage(createTransferableMessage({source:segment.requestId,encrypted:segment.encryptedBytes,key:keyBytes,iv:segment.key.iv}),[segment.encryptedBytes.buffer,keyBytes.buffer]);};var waitForCompletion=function waitForCompletion(_ref6){var activeXhrs=_ref6.activeXhrs,decryptionWorker=_ref6.decryptionWorker,trackInfoFn=_ref6.trackInfoFn,timingInfoFn=_ref6.timingInfoFn,videoSegmentTimingInfoFn=_ref6.videoSegmentTimingInfoFn,audioSegmentTimingInfoFn=_ref6.audioSegmentTimingInfoFn,id3Fn=_ref6.id3Fn,captionsFn=_ref6.captionsFn,dataFn=_ref6.dataFn,doneFn=_ref6.doneFn;var count=0;var didError=false;return function(error,segment){if(didError){return;}
if(error){didError=true;abortAll(activeXhrs);return doneFn(error,segment);}
count+=1;if(count===activeXhrs.length){segment.endOfAllRequests=Date.now();if(segment.encryptedBytes){return decryptSegment({decryptionWorker:decryptionWorker,segment:segment,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,dataFn:dataFn,doneFn:doneFn});}
handleSegmentBytes({segment:segment,bytes:segment.bytes,isPartial:false,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,dataFn:dataFn,doneFn:doneFn});}};};var handleLoadEnd=function handleLoadEnd(_ref7){var loadendState=_ref7.loadendState,abortFn=_ref7.abortFn;return function(event){var request=event.target;if(request.aborted&&abortFn&&!loadendState.calledAbortFn){abortFn();loadendState.calledAbortFn=true;}};};var handleProgress=function handleProgress(_ref8){var segment=_ref8.segment,progressFn=_ref8.progressFn,trackInfoFn=_ref8.trackInfoFn,timingInfoFn=_ref8.timingInfoFn,videoSegmentTimingInfoFn=_ref8.videoSegmentTimingInfoFn,audioSegmentTimingInfoFn=_ref8.audioSegmentTimingInfoFn,id3Fn=_ref8.id3Fn,captionsFn=_ref8.captionsFn,dataFn=_ref8.dataFn,handlePartialData=_ref8.handlePartialData;return function(event){var request=event.target;if(request.aborted){return;}
if(handlePartialData&&!segment.key&&request.responseText&&request.responseText.length>=8){var newBytes=stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar||0));if(segment.lastReachedChar||!containers_5(new Uint8Array(newBytes))){segment.lastReachedChar=request.responseText.length;handleSegmentBytes({segment:segment,bytes:newBytes,isPartial:true,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,dataFn:dataFn});}}
segment.stats=videojs$1.mergeOptions(segment.stats,getProgressStats(event));if(!segment.stats.firstBytesReceivedAt&&segment.stats.bytesReceived){segment.stats.firstBytesReceivedAt=Date.now();}
return progressFn(event,segment);};};var mediaSegmentRequest=function mediaSegmentRequest(_ref9){var xhr=_ref9.xhr,xhrOptions=_ref9.xhrOptions,decryptionWorker=_ref9.decryptionWorker,segment=_ref9.segment,abortFn=_ref9.abortFn,progressFn=_ref9.progressFn,trackInfoFn=_ref9.trackInfoFn,timingInfoFn=_ref9.timingInfoFn,videoSegmentTimingInfoFn=_ref9.videoSegmentTimingInfoFn,audioSegmentTimingInfoFn=_ref9.audioSegmentTimingInfoFn,id3Fn=_ref9.id3Fn,captionsFn=_ref9.captionsFn,dataFn=_ref9.dataFn,doneFn=_ref9.doneFn,handlePartialData=_ref9.handlePartialData;var activeXhrs=[];var finishProcessingFn=waitForCompletion({activeXhrs:activeXhrs,decryptionWorker:decryptionWorker,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,dataFn:dataFn,doneFn:doneFn});if(segment.key&&!segment.key.bytes){var keyRequestOptions=videojs$1.mergeOptions(xhrOptions,{uri:segment.key.resolvedUri,responseType:'arraybuffer'});var keyRequestCallback=handleKeyResponse(segment,finishProcessingFn);var keyXhr=xhr(keyRequestOptions,keyRequestCallback);activeXhrs.push(keyXhr);}
if(segment.map&&!segment.map.bytes){var initSegmentOptions=videojs$1.mergeOptions(xhrOptions,{uri:segment.map.resolvedUri,responseType:'arraybuffer',headers:segmentXhrHeaders(segment.map)});var initSegmentRequestCallback=handleInitSegmentResponse({segment:segment,finishProcessingFn:finishProcessingFn});var initSegmentXhr=xhr(initSegmentOptions,initSegmentRequestCallback);activeXhrs.push(initSegmentXhr);}
var segmentRequestOptions=videojs$1.mergeOptions(xhrOptions,{uri:segment.resolvedUri,responseType:'arraybuffer',headers:segmentXhrHeaders(segment)});if(handlePartialData){segmentRequestOptions.responseType='text';segmentRequestOptions.beforeSend=function(xhrObject){xhrObject.overrideMimeType('text/plain; charset=x-user-defined');};}
var segmentRequestCallback=handleSegmentResponse({segment:segment,finishProcessingFn:finishProcessingFn,responseType:segmentRequestOptions.responseType});var segmentXhr=xhr(segmentRequestOptions,segmentRequestCallback);segmentXhr.addEventListener('progress',handleProgress({segment:segment,progressFn:progressFn,trackInfoFn:trackInfoFn,timingInfoFn:timingInfoFn,videoSegmentTimingInfoFn:videoSegmentTimingInfoFn,audioSegmentTimingInfoFn:audioSegmentTimingInfoFn,id3Fn:id3Fn,captionsFn:captionsFn,dataFn:dataFn,handlePartialData:handlePartialData}));activeXhrs.push(segmentXhr);var loadendState={};activeXhrs.forEach(function(activeXhr){activeXhr.addEventListener('loadend',handleLoadEnd({loadendState:loadendState,abortFn:abortFn}));});return function(){return abortAll(activeXhrs);};};var win$3=typeof window!=='undefined'?window:{},TARGET=typeof Symbol==='undefined'?'__target':Symbol(),SCRIPT_TYPE='application/javascript',BlobBuilder=win$3.BlobBuilder||win$3.WebKitBlobBuilder||win$3.MozBlobBuilder||win$3.MSBlobBuilder,URL=win$3.URL||win$3.webkitURL||URL&&URL.msURL,Worker=win$3.Worker;function shimWorker(filename,fn){return function ShimWorker(forceFallback){var o=this;if(!fn){return new Worker(filename);}else if(Worker&&!forceFallback){var source=fn.toString().replace(/^function.+?{/,'').slice(0,-1),objURL=createSourceObject(source);this[TARGET]=new Worker(objURL);wrapTerminate(this[TARGET],objURL);return this[TARGET];}else{var selfShim={postMessage:function postMessage(m){if(o.onmessage){setTimeout(function(){o.onmessage({data:m,target:selfShim});});}}};fn.call(selfShim);this.postMessage=function(m){setTimeout(function(){selfShim.onmessage({data:m,target:o});});};this.isThisThread=true;}};}
if(Worker){var testWorker,objURL=createSourceObject('self.onmessage = function () {}'),testArray=new Uint8Array(1);try{testWorker=new Worker(objURL);testWorker.postMessage(testArray,[testArray.buffer]);}catch(e){Worker=null;}finally{URL.revokeObjectURL(objURL);if(testWorker){testWorker.terminate();}}}
function createSourceObject(str){try{return URL.createObjectURL(new Blob([str],{type:SCRIPT_TYPE}));}catch(e){var blob=new BlobBuilder();blob.append(str);return URL.createObjectURL(blob.getBlob(type));}}
function wrapTerminate(worker,objURL){if(!worker||!objURL)return;var term=worker.terminate;worker.objURL=objURL;worker.terminate=function(){if(worker.objURL)URL.revokeObjectURL(worker.objURL);term.call(worker);};}
var TransmuxWorker=new shimWorker("./transmuxer-worker.worker.js",function(window,document){var self=this;var transmuxerWorker=function(){var Stream=function Stream(){this.init=function(){var listeners={};this.on=function(type,listener){if(!listeners[type]){listeners[type]=[];}
listeners[type]=listeners[type].concat(listener);};this.off=function(type,listener){var index;if(!listeners[type]){return false;}
index=listeners[type].indexOf(listener);listeners[type]=listeners[type].slice();listeners[type].splice(index,1);return index>-1;};this.trigger=function(type){var callbacks,i,length,args;callbacks=listeners[type];if(!callbacks){return;}
if(arguments.length===2){length=callbacks.length;for(i=0;i<length;++i){callbacks[i].call(this,arguments[1]);}}else{args=[];i=arguments.length;for(i=1;i<arguments.length;++i){args.push(arguments[i]);}
length=callbacks.length;for(i=0;i<length;++i){callbacks[i].apply(this,args);}}};this.dispose=function(){listeners={};};};};Stream.prototype.pipe=function(destination){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);});return destination;};Stream.prototype.push=function(data){this.trigger('data',data);};Stream.prototype.flush=function(flushSource){this.trigger('done',flushSource);};Stream.prototype.partialFlush=function(flushSource){this.trigger('partialdone',flushSource);};Stream.prototype.endTimeline=function(flushSource){this.trigger('endedtimeline',flushSource);};Stream.prototype.reset=function(flushSource){this.trigger('reset',flushSource);};var stream=Stream;var UINT32_MAX=Math.pow(2,32)-1;var box,dinf,esds,ftyp,mdat,mfhd,minf,moof,moov,mvex,mvhd,trak,tkhd,mdia,mdhd,hdlr,sdtp,stbl,stsd,traf,trex,trun,types,MAJOR_BRAND,MINOR_VERSION,AVC1_BRAND,VIDEO_HDLR,AUDIO_HDLR,HDLR_TYPES,VMHD,SMHD,DREF,STCO,STSC,STSZ,STTS;(function(){var i;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:[]};if(typeof Uint8Array==='undefined'){return;}
for(i in types){if(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'.charCodeAt(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([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x76,0x69,0x64,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x56,0x69,0x64,0x65,0x6f,0x48,0x61,0x6e,0x64,0x6c,0x65,0x72,0x00]);AUDIO_HDLR=new Uint8Array([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x73,0x6f,0x75,0x6e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x53,0x6f,0x75,0x6e,0x64,0x48,0x61,0x6e,0x64,0x6c,0x65,0x72,0x00]);HDLR_TYPES={video:VIDEO_HDLR,audio:AUDIO_HDLR};DREF=new Uint8Array([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0c,0x75,0x72,0x6c,0x20,0x00,0x00,0x00,0x01]);SMHD=new Uint8Array([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]);STCO=new Uint8Array([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]);STSC=STCO;STSZ=new Uint8Array([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]);STTS=STCO;VMHD=new Uint8Array([0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]);})();box=function box(type){var payload=[],size=0,i,result,view;for(i=1;i<arguments.length;i++){payload.push(arguments[i]);}
i=payload.length;while(i--){size+=payload[i].byteLength;}
result=new Uint8Array(size+8);view=new DataView(result.buffer,result.byteOffset,result.byteLength);view.setUint32(0,result.byteLength);result.set(type,4);for(i=0,size=8;i<payload.length;i++){result.set(payload[i],size);size+=payload[i].byteLength;}
return result;};dinf=function dinf(){return box(types.dinf,box(types.dref,DREF));};esds=function esds(track){return box(types.esds,new Uint8Array([0x00,0x00,0x00,0x00,0x03,0x19,0x00,0x00,0x00,0x04,0x11,0x40,0x15,0x00,0x06,0x00,0x00,0x00,0xda,0xc0,0x00,0x00,0xda,0xc0,0x05,0x02,track.audioobjecttype<<3|track.samplingfrequencyindex>>>1,track.samplingfrequencyindex<<7|track.channelcount<<3,0x06,0x01,0x02]));};ftyp=function ftyp(){return box(types.ftyp,MAJOR_BRAND,MINOR_VERSION,MAJOR_BRAND,AVC1_BRAND);};hdlr=function hdlr(type){return box(types.hdlr,HDLR_TYPES[type]);};mdat=function mdat(data){return box(types.mdat,data);};mdhd=function mdhd(track){var result=new Uint8Array([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x03,0x00,0x01,0x5f,0x90,track.duration>>>24&0xFF,track.duration>>>16&0xFF,track.duration>>>8&0xFF,track.duration&0xFF,0x55,0xc4,0x00,0x00]);if(track.samplerate){result[12]=track.samplerate>>>24&0xFF;result[13]=track.samplerate>>>16&0xFF;result[14]=track.samplerate>>>8&0xFF;result[15]=track.samplerate&0xFF;}
return box(types.mdhd,result);};mdia=function mdia(track){return box(types.mdia,mdhd(track),hdlr(track.type),minf(track));};mfhd=function mfhd(sequenceNumber){return box(types.mfhd,new Uint8Array([0x00,0x00,0x00,0x00,(sequenceNumber&0xFF000000)>>24,(sequenceNumber&0xFF0000)>>16,(sequenceNumber&0xFF00)>>8,sequenceNumber&0xFF]));};minf=function minf(track){return box(types.minf,track.type==='video'?box(types.vmhd,VMHD):box(types.smhd,SMHD),dinf(),stbl(track));};moof=function moof(sequenceNumber,tracks){var trackFragments=[],i=tracks.length;while(i--){trackFragments[i]=traf(tracks[i]);}
return box.apply(null,[types.moof,mfhd(sequenceNumber)].concat(trackFragments));};moov=function moov(tracks){var i=tracks.length,boxes=[];while(i--){boxes[i]=trak(tracks[i]);}
return box.apply(null,[types.moov,mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));};mvex=function mvex(tracks){var i=tracks.length,boxes=[];while(i--){boxes[i]=trex(tracks[i]);}
return box.apply(null,[types.mvex].concat(boxes));};mvhd=function mvhd(duration){var bytes=new Uint8Array([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x01,0x5f,0x90,(duration&0xFF000000)>>24,(duration&0xFF0000)>>16,(duration&0xFF00)>>8,duration&0xFF,0x00,0x01,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff]);return box(types.mvhd,bytes);};sdtp=function sdtp(track){var samples=track.samples||[],bytes=new Uint8Array(4+samples.length),flags,i;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 stbl(track){return box(types.stbl,stsd(track),box(types.stts,STTS),box(types.stsc,STSC),box(types.stsz,STSZ),box(types.stco,STCO));};(function(){var videoSample,audioSample;stsd=function stsd(track){return box(types.stsd,new Uint8Array([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01]),track.type==='video'?videoSample(track):audioSample(track));};videoSample=function videoSample(track){var sps=track.sps||[],pps=track.pps||[],sequenceParameterSets=[],pictureParameterSets=[],i,avc1Box;for(i=0;i<sps.length;i++){sequenceParameterSets.push((sps[i].byteLength&0xFF00)>>>8);sequenceParameterSets.push(sps[i].byteLength&0xFF);sequenceParameterSets=sequenceParameterSets.concat(Array.prototype.slice.call(sps[i]));}
for(i=0;i<pps.length;i++){pictureParameterSets.push((pps[i].byteLength&0xFF00)>>>8);pictureParameterSets.push(pps[i].byteLength&0xFF);pictureParameterSets=pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));}
avc1Box=[types.avc1,new Uint8Array([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,(track.width&0xff00)>>8,track.width&0xff,(track.height&0xff00)>>8,track.height&0xff,0x00,0x48,0x00,0x00,0x00,0x48,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x13,0x76,0x69,0x64,0x65,0x6f,0x6a,0x73,0x2d,0x63,0x6f,0x6e,0x74,0x72,0x69,0x62,0x2d,0x68,0x6c,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x11,0x11]),box(types.avcC,new Uint8Array([0x01,track.profileIdc,track.profileCompatibility,track.levelIdc,0xff].concat([sps.length],sequenceParameterSets,[pps.length],pictureParameterSets))),box(types.btrt,new Uint8Array([0x00,0x1c,0x9c,0x80,0x00,0x2d,0xc6,0xc0,0x00,0x2d,0xc6,0xc0]))];if(track.sarRatio){var hSpacing=track.sarRatio[0],vSpacing=track.sarRatio[1];avc1Box.push(box(types.pasp,new Uint8Array([(hSpacing&0xFF000000)>>24,(hSpacing&0xFF0000)>>16,(hSpacing&0xFF00)>>8,hSpacing&0xFF,(vSpacing&0xFF000000)>>24,(vSpacing&0xFF0000)>>16,(vSpacing&0xFF00)>>8,vSpacing&0xFF])));}
return box.apply(null,avc1Box);};audioSample=function audioSample(track){return box(types.mp4a,new Uint8Array([0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,(track.channelcount&0xff00)>>8,track.channelcount&0xff,(track.samplesize&0xff00)>>8,track.samplesize&0xff,0x00,0x00,0x00,0x00,(track.samplerate&0xff00)>>8,track.samplerate&0xff,0x00,0x00]),esds(track));};})();tkhd=function tkhd(track){var result=new Uint8Array([0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,(track.id&0xFF000000)>>24,(track.id&0xFF0000)>>16,(track.id&0xFF00)>>8,track.id&0xFF,0x00,0x00,0x00,0x00,(track.duration&0xFF000000)>>24,(track.duration&0xFF0000)>>16,(track.duration&0xFF00)>>8,track.duration&0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,(track.width&0xFF00)>>8,track.width&0xFF,0x00,0x00,(track.height&0xFF00)>>8,track.height&0xFF,0x00,0x00]);return box(types.tkhd,result);};traf=function traf(track){var trackFragmentHeader,trackFragmentDecodeTime,trackFragmentRun,sampleDependencyTable,dataOffset,upperWordBaseMediaDecodeTime,lowerWordBaseMediaDecodeTime;trackFragmentHeader=box(types.tfhd,new Uint8Array([0x00,0x00,0x00,0x3a,(track.id&0xFF000000)>>24,(track.id&0xFF0000)>>16,(track.id&0xFF00)>>8,track.id&0xFF,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]));upperWordBaseMediaDecodeTime=Math.floor(track.baseMediaDecodeTime/(UINT32_MAX+1));lowerWordBaseMediaDecodeTime=Math.floor(track.baseMediaDecodeTime%(UINT32_MAX+1));trackFragmentDecodeTime=box(types.tfdt,new Uint8Array([0x01,0x00,0x00,0x00,upperWordBaseMediaDecodeTime>>>24&0xFF,upperWordBaseMediaDecodeTime>>>16&0xFF,upperWordBaseMediaDecodeTime>>>8&0xFF,upperWordBaseMediaDecodeTime&0xFF,lowerWordBaseMediaDecodeTime>>>24&0xFF,lowerWordBaseMediaDecodeTime>>>16&0xFF,lowerWordBaseMediaDecodeTime>>>8&0xFF,lowerWordBaseMediaDecodeTime&0xFF]));dataOffset=32+
20+
8+
16+
8+
8;if(track.type==='audio'){trackFragmentRun=trun(track,dataOffset);return box(types.traf,trackFragmentHeader,trackFragmentDecodeTime,trackFragmentRun);}
sampleDependencyTable=sdtp(track);trackFragmentRun=trun(track,sampleDependencyTable.length+dataOffset);return box(types.traf,trackFragmentHeader,trackFragmentDecodeTime,trackFragmentRun,sampleDependencyTable);};trak=function trak(track){track.duration=track.duration||0xffffffff;return box(types.trak,tkhd(track),mdia(track));};trex=function trex(track){var result=new Uint8Array([0x00,0x00,0x00,0x00,(track.id&0xFF000000)>>24,(track.id&0xFF0000)>>16,(track.id&0xFF00)>>8,track.id&0xFF,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x01]);if(track.type!=='video'){result[result.length-1]=0x00;}
return box(types.trex,result);};(function(){var audioTrun,videoTrun,trunHeader;trunHeader=function trunHeader(samples,offset){var durationPresent=0,sizePresent=0,flagsPresent=0,compositionTimeOffset=0;if(samples.length){if(samples[0].duration!==undefined){durationPresent=0x1;}
if(samples[0].size!==undefined){sizePresent=0x2;}
if(samples[0].flags!==undefined){flagsPresent=0x4;}
if(samples[0].compositionTimeOffset!==undefined){compositionTimeOffset=0x8;}}
return[0x00,0x00,durationPresent|sizePresent|flagsPresent|compositionTimeOffset,0x01,(samples.length&0xFF000000)>>>24,(samples.length&0xFF0000)>>>16,(samples.length&0xFF00)>>>8,samples.length&0xFF,(offset&0xFF000000)>>>24,(offset&0xFF0000)>>>16,(offset&0xFF00)>>>8,offset&0xFF];};videoTrun=function videoTrun(track,offset){var bytesOffest,bytes,header,samples,sample,i;samples=track.samples||[];offset+=8+12+16*samples.length;header=trunHeader(samples,offset);bytes=new Uint8Array(header.length+samples.length*16);bytes.set(header);bytesOffest=header.length;for(i=0;i<samples.length;i++){sample=samples[i];bytes[bytesOffest++]=(sample.duration&0xFF000000)>>>24;bytes[bytesOffest++]=(sample.duration&0xFF0000)>>>16;bytes[bytesOffest++]=(sample.duration&0xFF00)>>>8;bytes[bytesOffest++]=sample.duration&0xFF;bytes[bytesOffest++]=(sample.size&0xFF000000)>>>24;bytes[bytesOffest++]=(sample.size&0xFF0000)>>>16;bytes[bytesOffest++]=(sample.size&0xFF00)>>>8;bytes[bytesOffest++]=sample.size&0xFF;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++]=sample.flags.degradationPriority&0xF0<<8;bytes[bytesOffest++]=sample.flags.degradationPriority&0x0F;bytes[bytesOffest++]=(sample.compositionTimeOffset&0xFF000000)>>>24;bytes[bytesOffest++]=(sample.compositionTimeOffset&0xFF0000)>>>16;bytes[bytesOffest++]=(sample.compositionTimeOffset&0xFF00)>>>8;bytes[bytesOffest++]=sample.compositionTimeOffset&0xFF;}
return box(types.trun,bytes);};audioTrun=function audioTrun(track,offset){var bytes,bytesOffest,header,samples,sample,i;samples=track.samples||[];offset+=8+12+8*samples.length;header=trunHeader(samples,offset);bytes=new Uint8Array(header.length+samples.length*8);bytes.set(header);bytesOffest=header.length;for(i=0;i<samples.length;i++){sample=samples[i];bytes[bytesOffest++]=(sample.duration&0xFF000000)>>>24;bytes[bytesOffest++]=(sample.duration&0xFF0000)>>>16;bytes[bytesOffest++]=(sample.duration&0xFF00)>>>8;bytes[bytesOffest++]=sample.duration&0xFF;bytes[bytesOffest++]=(sample.size&0xFF000000)>>>24;bytes[bytesOffest++]=(sample.size&0xFF0000)>>>16;bytes[bytesOffest++]=(sample.size&0xFF00)>>>8;bytes[bytesOffest++]=sample.size&0xFF;}
return box(types.trun,bytes);};trun=function trun(track,offset){if(track.type==='audio'){return audioTrun(track,offset);}
return videoTrun(track,offset);};})();var mp4Generator={ftyp:ftyp,mdat:mdat,moof:moof,moov:moov,initSegment:function initSegment(tracks){var fileType=ftyp(),movie=moov(tracks),result;result=new Uint8Array(fileType.byteLength+movie.byteLength);result.set(fileType);result.set(movie,fileType.byteLength);return result;}};var groupNalsIntoFrames=function groupNalsIntoFrames(nalUnits){var i,currentNal,currentFrame=[],frames=[];frames.byteLength=0;frames.nalCount=0;frames.duration=0;currentFrame.byteLength=0;for(i=0;i<nalUnits.length;i++){currentNal=nalUnits[i];if(currentNal.nalUnitType==='access_unit_delimiter_rbsp'){if(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];currentFrame.byteLength=currentNal.data.byteLength;currentFrame.pts=currentNal.pts;currentFrame.dts=currentNal.dts;}else{if(currentNal.nalUnitType==='slice_layer_without_partitioning_rbsp_idr'){currentFrame.keyFrame=true;}
currentFrame.duration=currentNal.dts-currentFrame.dts;currentFrame.byteLength+=currentNal.data.byteLength;currentFrame.push(currentNal);}}
if(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;frames.push(currentFrame);return frames;};var groupFramesIntoGops=function groupFramesIntoGops(frames){var i,currentFrame,currentGop=[],gops=[];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;for(i=0;i<frames.length;i++){currentFrame=frames[i];if(currentFrame.keyFrame){if(currentGop.length){gops.push(currentGop);gops.byteLength+=currentGop.byteLength;gops.nalCount+=currentGop.nalCount;gops.duration+=currentGop.duration;}
currentGop=[currentFrame];currentGop.nalCount=currentFrame.length;currentGop.byteLength=currentFrame.byteLength;currentGop.pts=currentFrame.pts;currentGop.dts=currentFrame.dts;currentGop.duration=currentFrame.duration;}else{currentGop.duration+=currentFrame.duration;currentGop.nalCount+=currentFrame.length;currentGop.byteLength+=currentFrame.byteLength;currentGop.push(currentFrame);}}
if(gops.length&&currentGop.duration<=0){currentGop.duration=gops[gops.length-1].duration;}
gops.byteLength+=currentGop.byteLength;gops.nalCount+=currentGop.nalCount;gops.duration+=currentGop.duration;gops.push(currentGop);return gops;};var extendFirstKeyFrame=function extendFirstKeyFrame(gops){var currentGop;if(!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;}
return gops;};var createDefaultSample=function createDefaultSample(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}};};var sampleForFrame=function sampleForFrame(frame,dataOffset){var sample=createDefaultSample();sample.dataOffset=dataOffset;sample.compositionTimeOffset=frame.pts-frame.dts;sample.duration=frame.duration;sample.size=4*frame.length;sample.size+=frame.byteLength;if(frame.keyFrame){sample.flags.dependsOn=2;sample.flags.isNonSyncSample=0;}
return sample;};var generateSampleTable=function generateSampleTable(gops,baseDataOffset){var h,i,sample,currentGop,currentFrame,dataOffset=baseDataOffset||0,samples=[];for(h=0;h<gops.length;h++){currentGop=gops[h];for(i=0;i<currentGop.length;i++){currentFrame=currentGop[i];sample=sampleForFrame(currentFrame,dataOffset);dataOffset+=sample.size;samples.push(sample);}}
return samples;};var concatenateNalData=function concatenateNalData(gops){var h,i,j,currentGop,currentFrame,currentNal,dataOffset=0,nalsByteLength=gops.byteLength,numberOfNals=gops.nalCount,totalByteLength=nalsByteLength+4*numberOfNals,data=new Uint8Array(totalByteLength),view=new DataView(data.buffer);for(h=0;h<gops.length;h++){currentGop=gops[h];for(i=0;i<currentGop.length;i++){currentFrame=currentGop[i];for(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;};var generateSampleTableForFrame=function generateSampleTableForFrame(frame,baseDataOffset){var sample,dataOffset=baseDataOffset||0,samples=[];sample=sampleForFrame(frame,dataOffset);samples.push(sample);return samples;};var concatenateNalDataForFrame=function concatenateNalDataForFrame(frame){var i,currentNal,dataOffset=0,nalsByteLength=frame.byteLength,numberOfNals=frame.length,totalByteLength=nalsByteLength+4*numberOfNals,data=new Uint8Array(totalByteLength),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;};var frameUtils={groupNalsIntoFrames:groupNalsIntoFrames,groupFramesIntoGops:groupFramesIntoGops,extendFirstKeyFrame:extendFirstKeyFrame,generateSampleTable:generateSampleTable,concatenateNalData:concatenateNalData,generateSampleTableForFrame:generateSampleTableForFrame,concatenateNalDataForFrame:concatenateNalDataForFrame};var highPrefix=[33,16,5,32,164,27];var lowPrefix=[33,65,108,84,1,2,4,8,168,2,4,8,17,191,252];var zeroFill=function zeroFill(count){var a=[];while(count--){a.push(0);}
return a;};var makeTable=function makeTable(metaTable){return Object.keys(metaTable).reduce(function(obj,key){obj[key]=new Uint8Array(metaTable[key].reduce(function(arr,part){return arr.concat(part);},[]));return obj;},{});};var silence;var silence_1=function silence_1(){if(!silence){var coneOfSilence={96000:[highPrefix,[227,64],zeroFill(154),[56]],88200:[highPrefix,[231],zeroFill(170),[56]],64000:[highPrefix,[248,192],zeroFill(240),[56]],48000:[highPrefix,[255,192],zeroFill(268),[55,148,128],zeroFill(54),[112]],44100:[highPrefix,[255,192],zeroFill(268),[55,163,128],zeroFill(84),[112]],32000:[highPrefix,[255,192],zeroFill(268),[55,234],zeroFill(226),[112]],24000:[highPrefix,[255,192],zeroFill(268),[55,255,128],zeroFill(268),[111,112],zeroFill(126),[224]],16000:[highPrefix,[255,192],zeroFill(268),[55,255,128],zeroFill(268),[111,255],zeroFill(269),[223,108],zeroFill(195),[1,192]],12000:[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]],8000:[lowPrefix,zeroFill(268),[3,121,16],zeroFill(47),[7]]};silence=makeTable(coneOfSilence);}
return silence;};var ONE_SECOND_IN_TS=90000,secondsToVideoTs,secondsToAudioTs,videoTsToSeconds,audioTsToSeconds,audioTsToVideoTs,videoTsToAudioTs,metadataTsToSeconds;secondsToVideoTs=function secondsToVideoTs(seconds){return seconds*ONE_SECOND_IN_TS;};secondsToAudioTs=function secondsToAudioTs(seconds,sampleRate){return seconds*sampleRate;};videoTsToSeconds=function videoTsToSeconds(timestamp){return timestamp/ONE_SECOND_IN_TS;};audioTsToSeconds=function audioTsToSeconds(timestamp,sampleRate){return timestamp/sampleRate;};audioTsToVideoTs=function audioTsToVideoTs(timestamp,sampleRate){return secondsToVideoTs(audioTsToSeconds(timestamp,sampleRate));};videoTsToAudioTs=function videoTsToAudioTs(timestamp,sampleRate){return secondsToAudioTs(videoTsToSeconds(timestamp),sampleRate);};metadataTsToSeconds=function metadataTsToSeconds(timestamp,timelineStartPts,keepOriginalTimestamps){return videoTsToSeconds(keepOriginalTimestamps?timestamp:timestamp-timelineStartPts);};var clock={ONE_SECOND_IN_TS:ONE_SECOND_IN_TS,secondsToVideoTs:secondsToVideoTs,secondsToAudioTs:secondsToAudioTs,videoTsToSeconds:videoTsToSeconds,audioTsToSeconds:audioTsToSeconds,audioTsToVideoTs:audioTsToVideoTs,videoTsToAudioTs:videoTsToAudioTs,metadataTsToSeconds:metadataTsToSeconds};var sumFrameByteLengths=function sumFrameByteLengths(array){var i,currentObj,sum=0;for(i=0;i<array.length;i++){currentObj=array[i];sum+=currentObj.data.byteLength;}
return sum;};var prefixWithSilence=function prefixWithSilence(track,frames,audioAppendStartTs,videoBaseMediaDecodeTime){var baseMediaDecodeTimeTs,frameDuration=0,audioGapDuration=0,audioFillFrameCount=0,audioFillDuration=0,silentFrame,i,firstFrame;if(!frames.length){return;}
baseMediaDecodeTimeTs=clock.audioTsToVideoTs(track.baseMediaDecodeTime,track.samplerate);frameDuration=Math.ceil(clock.ONE_SECOND_IN_TS/(track.samplerate/1024));if(audioAppendStartTs&&videoBaseMediaDecodeTime){audioGapDuration=baseMediaDecodeTimeTs-Math.max(audioAppendStartTs,videoBaseMediaDecodeTime);audioFillFrameCount=Math.floor(audioGapDuration/frameDuration);audioFillDuration=audioFillFrameCount*frameDuration;}
if(audioFillFrameCount<1||audioFillDuration>clock.ONE_SECOND_IN_TS/2){return;}
silentFrame=silence_1()[track.samplerate];if(!silentFrame){silentFrame=frames[0].data;}
for(i=0;i<audioFillFrameCount;i++){firstFrame=frames[0];frames.splice(0,0,{data:silentFrame,dts:firstFrame.dts-frameDuration,pts:firstFrame.pts-frameDuration});}
track.baseMediaDecodeTime-=Math.floor(clock.videoTsToAudioTs(audioFillDuration,track.samplerate));return audioFillDuration;};var trimAdtsFramesByEarliestDts=function trimAdtsFramesByEarliestDts(adtsFrames,track,earliestAllowedDts){if(track.minSegmentDts>=earliestAllowedDts){return adtsFrames;}
track.minSegmentDts=Infinity;return adtsFrames.filter(function(currentFrame){if(currentFrame.dts>=earliestAllowedDts){track.minSegmentDts=Math.min(track.minSegmentDts,currentFrame.dts);track.minSegmentPts=track.minSegmentDts;return true;}
return false;});};var generateSampleTable$1=function generateSampleTable(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;};var concatenateFrameData=function concatenateFrameData(frames){var i,currentFrame,dataOffset=0,data=new Uint8Array(sumFrameByteLengths(frames));for(i=0;i<frames.length;i++){currentFrame=frames[i];data.set(currentFrame.data,dataOffset);dataOffset+=currentFrame.data.byteLength;}
return data;};var audioFrameUtils={prefixWithSilence:prefixWithSilence,trimAdtsFramesByEarliestDts:trimAdtsFramesByEarliestDts,generateSampleTable:generateSampleTable$1,concatenateFrameData:concatenateFrameData};var ONE_SECOND_IN_TS$1=clock.ONE_SECOND_IN_TS;var collectDtsInfo=function collectDtsInfo(track,data){if(typeof data.pts==='number'){if(track.timelineStartInfo.pts===undefined){track.timelineStartInfo.pts=data.pts;}
if(track.minSegmentPts===undefined){track.minSegmentPts=data.pts;}else{track.minSegmentPts=Math.min(track.minSegmentPts,data.pts);}
if(track.maxSegmentPts===undefined){track.maxSegmentPts=data.pts;}else{track.maxSegmentPts=Math.max(track.maxSegmentPts,data.pts);}}
if(typeof data.dts==='number'){if(track.timelineStartInfo.dts===undefined){track.timelineStartInfo.dts=data.dts;}
if(track.minSegmentDts===undefined){track.minSegmentDts=data.dts;}else{track.minSegmentDts=Math.min(track.minSegmentDts,data.dts);}
if(track.maxSegmentDts===undefined){track.maxSegmentDts=data.dts;}else{track.maxSegmentDts=Math.max(track.maxSegmentDts,data.dts);}}};var clearDtsInfo=function clearDtsInfo(track){delete track.minSegmentDts;delete track.maxSegmentDts;delete track.minSegmentPts;delete track.maxSegmentPts;};var calculateTrackBaseMediaDecodeTime=function calculateTrackBaseMediaDecodeTime(track,keepOriginalTimestamps){var baseMediaDecodeTime,scale,minSegmentDts=track.minSegmentDts;if(!keepOriginalTimestamps){minSegmentDts-=track.timelineStartInfo.dts;}
baseMediaDecodeTime=track.timelineStartInfo.baseMediaDecodeTime;baseMediaDecodeTime+=minSegmentDts;baseMediaDecodeTime=Math.max(0,baseMediaDecodeTime);if(track.type==='audio'){scale=track.samplerate/ONE_SECOND_IN_TS$1;baseMediaDecodeTime*=scale;baseMediaDecodeTime=Math.floor(baseMediaDecodeTime);}
return baseMediaDecodeTime;};var trackDecodeInfo={clearDtsInfo:clearDtsInfo,calculateTrackBaseMediaDecodeTime:calculateTrackBaseMediaDecodeTime,collectDtsInfo:collectDtsInfo};var USER_DATA_REGISTERED_ITU_T_T35=4,RBSP_TRAILING_BITS=128;var parseSei=function parseSei(bytes){var i=0,result={payloadType:-1,payloadSize:0},payloadType=0,payloadSize=0;while(i<bytes.byteLength){if(bytes[i]===RBSP_TRAILING_BITS){break;}
while(bytes[i]===0xFF){payloadType+=255;i++;}
payloadType+=bytes[i++];while(bytes[i]===0xFF){payloadSize+=255;i++;}
payloadSize+=bytes[i++];if(!result.payload&&payloadType===USER_DATA_REGISTERED_ITU_T_T35){var userIdentifier=String.fromCharCode(bytes[i+3],bytes[i+4],bytes[i+5],bytes[i+6]);if(userIdentifier==='GA94'){result.payloadType=payloadType;result.payloadSize=payloadSize;result.payload=bytes.subarray(i,i+payloadSize);break;}else{result.payload=void 0;}}
i+=payloadSize;payloadType=0;payloadSize=0;}
return result;};var parseUserData=function parseUserData(sei){if(sei.payload[0]!==181){return null;}
if((sei.payload[1]<<8|sei.payload[2])!==49){return null;}
if(String.fromCharCode(sei.payload[3],sei.payload[4],sei.payload[5],sei.payload[6])!=='GA94'){return null;}
if(sei.payload[7]!==0x03){return null;}
return sei.payload.subarray(8,sei.payload.length-1);};var parseCaptionPackets=function parseCaptionPackets(pts,userData){var results=[],i,count,offset,data;if(!(userData[0]&0x40)){return results;}
count=userData[0]&0x1f;for(i=0;i<count;i++){offset=i*3;data={type:userData[offset+2]&0x03,pts:pts};if(userData[offset+2]&0x04){data.ccData=userData[offset+3]<<8|userData[offset+4];results.push(data);}}
return results;};var discardEmulationPreventionBytes=function discardEmulationPreventionBytes(data){var length=data.byteLength,emulationPreventionBytesPositions=[],i=1,newLength,newData;while(i<length-2){if(data[i]===0&&data[i+1]===0&&data[i+2]===0x03){emulationPreventionBytesPositions.push(i+2);i+=2;}else{i++;}}
if(emulationPreventionBytesPositions.length===0){return data;}
newLength=length-emulationPreventionBytesPositions.length;newData=new Uint8Array(newLength);var sourceIndex=0;for(i=0;i<newLength;sourceIndex++,i++){if(sourceIndex===emulationPreventionBytesPositions[0]){sourceIndex++;emulationPreventionBytesPositions.shift();}
newData[i]=data[sourceIndex];}
return newData;};var captionPacketParser={parseSei:parseSei,parseUserData:parseUserData,parseCaptionPackets:parseCaptionPackets,discardEmulationPreventionBytes:discardEmulationPreventionBytes,USER_DATA_REGISTERED_ITU_T_T35:USER_DATA_REGISTERED_ITU_T_T35};var CaptionStream=function CaptionStream(){CaptionStream.prototype.init.call(this);this.captionPackets_=[];this.ccStreams_=[new Cea608Stream(0,0),new Cea608Stream(0,1),new Cea608Stream(1,0),new Cea608Stream(1,1)];this.cc708Stream_=new Cea708Stream();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.cc708Stream_.on('data',this.trigger.bind(this,'data'));this.cc708Stream_.on('partialdone',this.trigger.bind(this,'partialdone'));this.cc708Stream_.on('done',this.trigger.bind(this,'done'));};CaptionStream.prototype=new stream();CaptionStream.prototype.push=function(event){var sei,userData,newCaptionPackets;if(event.nalUnitType!=='sei_rbsp'){return;}
sei=captionPacketParser.parseSei(event.escapedRBSP);if(!sei.payload){return;}
if(sei.payloadType!==captionPacketParser.USER_DATA_REGISTERED_ITU_T_T35){return;}
userData=captionPacketParser.parseUserData(sei);if(!userData){return;}
if(event.dts<this.latestDts_){this.ignoreNextEqualDts_=true;return;}else if(event.dts===this.latestDts_&&this.ignoreNextEqualDts_){this.numSameDts_--;if(!this.numSameDts_){this.ignoreNextEqualDts_=false;}
return;}
newCaptionPackets=captionPacketParser.parseCaptionPackets(event.pts,userData);this.captionPackets_=this.captionPackets_.concat(newCaptionPackets);if(this.latestDts_!==event.dts){this.numSameDts_=0;}
this.numSameDts_++;this.latestDts_=event.dts;};CaptionStream.prototype.flushCCStreams=function(flushType){this.ccStreams_.forEach(function(cc){return flushType==='flush'?cc.flush():cc.partialFlush();},this);};CaptionStream.prototype.flushStream=function(flushType){if(!this.captionPackets_.length){this.flushCCStreams(flushType);return;}
this.captionPackets_.forEach(function(elem,idx){elem.presortIndex=idx;});this.captionPackets_.sort(function(a,b){if(a.pts===b.pts){return a.presortIndex-b.presortIndex;}
return a.pts-b.pts;});this.captionPackets_.forEach(function(packet){if(packet.type<2){this.dispatchCea608Packet(packet);}else{this.dispatchCea708Packet(packet);}},this);this.captionPackets_.length=0;this.flushCCStreams(flushType);};CaptionStream.prototype.flush=function(){return this.flushStream('flush');};CaptionStream.prototype.partialFlush=function(){return this.flushStream('partialFlush');};CaptionStream.prototype.reset=function(){this.latestDts_=null;this.ignoreNextEqualDts_=false;this.numSameDts_=0;this.activeCea608Channel_=[null,null];this.ccStreams_.forEach(function(ccStream){ccStream.reset();});};CaptionStream.prototype.dispatchCea608Packet=function(packet){if(this.setsTextOrXDSActive(packet)){this.activeCea608Channel_[packet.type]=null;}else if(this.setsChannel1Active(packet)){this.activeCea608Channel_[packet.type]=0;}else if(this.setsChannel2Active(packet)){this.activeCea608Channel_[packet.type]=1;}
if(this.activeCea608Channel_[packet.type]===null){return;}
this.ccStreams_[(packet.type<<1)+this.activeCea608Channel_[packet.type]].push(packet);};CaptionStream.prototype.setsChannel1Active=function(packet){return(packet.ccData&0x7800)===0x1000;};CaptionStream.prototype.setsChannel2Active=function(packet){return(packet.ccData&0x7800)===0x1800;};CaptionStream.prototype.setsTextOrXDSActive=function(packet){return(packet.ccData&0x7100)===0x0100||(packet.ccData&0x78fe)===0x102a||(packet.ccData&0x78fe)===0x182a;};CaptionStream.prototype.dispatchCea708Packet=function(packet){this.cc708Stream_.push(packet);};var CHARACTER_TRANSLATION_708={0x7f:0x266a,0x1020:0x20,0x1021:0xa0,0x1025:0x2026,0x102a:0x0160,0x102c:0x0152,0x1030:0x2588,0x1031:0x2018,0x1032:0x2019,0x1033:0x201c,0x1034:0x201d,0x1035:0x2022,0x1039:0x2122,0x103a:0x0161,0x103c:0x0153,0x103d:0x2120,0x103f:0x0178,0x1076:0x215b,0x1077:0x215c,0x1078:0x215d,0x1079:0x215e,0x107a:0x23d0,0x107b:0x23a4,0x107c:0x23a3,0x107d:0x23af,0x107e:0x23a6,0x107f:0x23a1,0x10a0:0x3138};var get708CharFromCode=function get708CharFromCode(code){var newCode=CHARACTER_TRANSLATION_708[code]||code;if(code&0x1000&&code===newCode){return'';}
return String.fromCharCode(newCode);};var within708TextBlock=function within708TextBlock(b){return 0x20<=b&&b<=0x7f||0xa0<=b&&b<=0xff;};var Cea708Window=function Cea708Window(windowNum){this.windowNum=windowNum;this.reset();};Cea708Window.prototype.reset=function(){this.clearText();this.pendingNewLine=false;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){if(this.rows.length>=this.virtualRowCount&&typeof this.beforeRowOverflow==='function'){this.beforeRowOverflow(pts);}
if(this.rows.length>0){this.rows.push('');this.rowIdx++;}
while(this.rows.length>this.virtualRowCount){this.rows.shift();this.rowIdx--;}};Cea708Window.prototype.isEmpty=function(){if(this.rows.length===0){return true;}else if(this.rows.length===1){return this.rows[0]==='';}
return false;};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 Cea708Service(serviceNum){this.serviceNum=serviceNum;this.text='';this.currentWindow=new Cea708Window(-1);this.windows=[];};Cea708Service.prototype.init=function(pts,beforeRowOverflow){this.startPts=pts;for(var win=0;win<8;win++){this.windows[win]=new Cea708Window(win);if(typeof beforeRowOverflow==='function'){this.windows[win].beforeRowOverflow=beforeRowOverflow;}}};Cea708Service.prototype.setCurrentWindow=function(windowNum){this.currentWindow=this.windows[windowNum];};var Cea708Stream=function Cea708Stream(){Cea708Stream.prototype.init.call(this);var self=this;this.current708Packet=null;this.services={};this.push=function(packet){if(packet.type===3){self.new708Packet();self.add708Bytes(packet);}else{if(self.current708Packet===null){self.new708Packet();}
self.add708Bytes(packet);}};};Cea708Stream.prototype=new stream();Cea708Stream.prototype.new708Packet=function(){if(this.current708Packet!==null){this.push708Packet();}
this.current708Packet={data:[],ptsVals:[]};};Cea708Stream.prototype.add708Bytes=function(packet){var data=packet.ccData;var byte0=data>>>8;var byte1=data&0xff;this.current708Packet.ptsVals.push(packet.pts);this.current708Packet.data.push(byte0);this.current708Packet.data.push(byte1);};Cea708Stream.prototype.push708Packet=function(){var packet708=this.current708Packet;var packetData=packet708.data;var serviceNum=null;var blockSize=null;var i=0;var b=packetData[i++];packet708.seq=b>>6;packet708.sizeCode=b&0x3f;for(;i<packetData.length;i++){b=packetData[i++];serviceNum=b>>5;blockSize=b&0x1f;if(serviceNum===7&&blockSize>0){b=packetData[i++];serviceNum=b;}
this.pushServiceBlock(serviceNum,i,blockSize);if(blockSize>0){i+=blockSize-1;}}};Cea708Stream.prototype.pushServiceBlock=function(serviceNum,start,size){var b;var i=start;var packetData=this.current708Packet.data;var service=this.services[serviceNum];if(!service){service=this.initService(serviceNum,i);}
for(;i<start+size&&i<packetData.length;i++){b=packetData[i];if(within708TextBlock(b)){i=this.handleText(i,service);}else if(b===0x10){i=this.extendedCommands(i,service);}else if(0x80<=b&&b<=0x87){i=this.setCurrentWindow(i,service);}else if(0x98<=b&&b<=0x9f){i=this.defineWindow(i,service);}else if(b===0x88){i=this.clearWindows(i,service);}else if(b===0x8c){i=this.deleteWindows(i,service);}else if(b===0x89){i=this.displayWindows(i,service);}else if(b===0x8a){i=this.hideWindows(i,service);}else if(b===0x8b){i=this.toggleWindows(i,service);}else if(b===0x97){i=this.setWindowAttributes(i,service);}else if(b===0x90){i=this.setPenAttributes(i,service);}else if(b===0x91){i=this.setPenColor(i,service);}else if(b===0x92){i=this.setPenLocation(i,service);}else if(b===0x8f){service=this.reset(i,service);}else if(b===0x08){service.currentWindow.backspace();}else if(b===0x0c){service.currentWindow.clearText();}else if(b===0x0d){service.currentWindow.pendingNewLine=true;}else if(b===0x0e){service.currentWindow.clearText();}else if(b===0x8d){i++;}}};Cea708Stream.prototype.extendedCommands=function(i,service){var packetData=this.current708Packet.data;var b=packetData[++i];if(within708TextBlock(b)){i=this.handleText(i,service,true);}
return i;};Cea708Stream.prototype.getPts=function(byteIndex){return this.current708Packet.ptsVals[Math.floor(byteIndex/2)];};Cea708Stream.prototype.initService=function(serviceNum,i){var self=this;this.services[serviceNum]=new Cea708Service(serviceNum);this.services[serviceNum].init(this.getPts(i),function(pts){self.flushDisplayed(pts,self.services[serviceNum]);});return this.services[serviceNum];};Cea708Stream.prototype.handleText=function(i,service,isExtended){var packetData=this.current708Packet.data;var b=packetData[i];var extended=isExtended?0x1000:0x0000;var _char=get708CharFromCode(extended|b);var win=service.currentWindow;if(win.pendingNewLine&&!win.isEmpty()){win.newLine(this.getPts(i));}
win.pendingNewLine=false;win.addText(_char);return i;};Cea708Stream.prototype.setCurrentWindow=function(i,service){var packetData=this.current708Packet.data;var b=packetData[i];var windowNum=b&0x07;service.setCurrentWindow(windowNum);return i;};Cea708Stream.prototype.defineWindow=function(i,service){var packetData=this.current708Packet.data;var b=packetData[i];var windowNum=b&0x07;service.setCurrentWindow(windowNum);var win=service.currentWindow;b=packetData[++i];win.visible=(b&0x20)>>5;win.rowLock=(b&0x10)>>4;win.columnLock=(b&0x08)>>3;win.priority=b&0x07;b=packetData[++i];win.relativePositioning=(b&0x80)>>7;win.anchorVertical=b&0x7f;b=packetData[++i];win.anchorHorizontal=b;b=packetData[++i];win.anchorPoint=(b&0xf0)>>4;win.rowCount=b&0x0f;b=packetData[++i];win.columnCount=b&0x3f;b=packetData[++i];win.windowStyle=(b&0x38)>>3;win.penStyle=b&0x07;win.virtualRowCount=win.rowCount+1;return i;};Cea708Stream.prototype.setWindowAttributes=function(i,service){var packetData=this.current708Packet.data;var b=packetData[i];var winAttr=service.currentWindow.winAttr;b=packetData[++i];winAttr.fillOpacity=(b&0xc0)>>6;winAttr.fillRed=(b&0x30)>>4;winAttr.fillGreen=(b&0x0c)>>2;winAttr.fillBlue=b&0x03;b=packetData[++i];winAttr.borderType=(b&0xc0)>>6;winAttr.borderRed=(b&0x30)>>4;winAttr.borderGreen=(b&0x0c)>>2;winAttr.borderBlue=b&0x03;b=packetData[++i];winAttr.borderType+=(b&0x80)>>5;winAttr.wordWrap=(b&0x40)>>6;winAttr.printDirection=(b&0x30)>>4;winAttr.scrollDirection=(b&0x0c)>>2;winAttr.justify=b&0x03;b=packetData[++i];winAttr.effectSpeed=(b&0xf0)>>4;winAttr.effectDirection=(b&0x0c)>>2;winAttr.displayEffect=b&0x03;return i;};Cea708Stream.prototype.flushDisplayed=function(pts,service){var displayedText=[];for(var winId=0;winId<8;winId++){if(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){if(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 packetData=this.current708Packet.data;var b=packetData[++i];var pts=this.getPts(i);this.flushDisplayed(pts,service);for(var winId=0;winId<8;winId++){if(b&0x01<<winId){service.windows[winId].visible=1;}}
return i;};Cea708Stream.prototype.hideWindows=function(i,service){var packetData=this.current708Packet.data;var b=packetData[++i];var pts=this.getPts(i);this.flushDisplayed(pts,service);for(var winId=0;winId<8;winId++){if(b&0x01<<winId){service.windows[winId].visible=0;}}
return i;};Cea708Stream.prototype.toggleWindows=function(i,service){var packetData=this.current708Packet.data;var b=packetData[++i];var pts=this.getPts(i);this.flushDisplayed(pts,service);for(var winId=0;winId<8;winId++){if(b&0x01<<winId){service.windows[winId].visible^=1;}}
return i;};Cea708Stream.prototype.clearWindows=function(i,service){var packetData=this.current708Packet.data;var b=packetData[++i];var pts=this.getPts(i);this.flushDisplayed(pts,service);for(var winId=0;winId<8;winId++){if(b&0x01<<winId){service.windows[winId].clearText();}}
return i;};Cea708Stream.prototype.deleteWindows=function(i,service){var packetData=this.current708Packet.data;var b=packetData[++i];var pts=this.getPts(i);this.flushDisplayed(pts,service);for(var winId=0;winId<8;winId++){if(b&0x01<<winId){service.windows[winId].reset();}}
return i;};Cea708Stream.prototype.setPenAttributes=function(i,service){var packetData=this.current708Packet.data;var b=packetData[i];var penAttr=service.currentWindow.penAttr;b=packetData[++i];penAttr.textTag=(b&0xf0)>>4;penAttr.offset=(b&0x0c)>>2;penAttr.penSize=b&0x03;b=packetData[++i];penAttr.italics=(b&0x80)>>7;penAttr.underline=(b&0x40)>>6;penAttr.edgeType=(b&0x38)>>3;penAttr.fontStyle=b&0x07;return i;};Cea708Stream.prototype.setPenColor=function(i,service){var packetData=this.current708Packet.data;var b=packetData[i];var penColor=service.currentWindow.penColor;b=packetData[++i];penColor.fgOpacity=(b&0xc0)>>6;penColor.fgRed=(b&0x30)>>4;penColor.fgGreen=(b&0x0c)>>2;penColor.fgBlue=b&0x03;b=packetData[++i];penColor.bgOpacity=(b&0xc0)>>6;penColor.bgRed=(b&0x30)>>4;penColor.bgGreen=(b&0x0c)>>2;penColor.bgBlue=b&0x03;b=packetData[++i];penColor.edgeRed=(b&0x30)>>4;penColor.edgeGreen=(b&0x0c)>>2;penColor.edgeBlue=b&0x03;return i;};Cea708Stream.prototype.setPenLocation=function(i,service){var packetData=this.current708Packet.data;var b=packetData[i];var penLoc=service.currentWindow.penLoc;service.currentWindow.pendingNewLine=true;b=packetData[++i];penLoc.row=b&0x0f;b=packetData[++i];penLoc.column=b&0x3f;return i;};Cea708Stream.prototype.reset=function(i,service){var pts=this.getPts(i);this.flushDisplayed(pts,service);return this.initService(service.serviceNum,i);};var CHARACTER_TRANSLATION={0x2a:0xe1,0x5c:0xe9,0x5e:0xed,0x5f:0xf3,0x60:0xfa,0x7b:0xe7,0x7c:0xf7,0x7d:0xd1,0x7e:0xf1,0x7f:0x2588,0x0130:0xae,0x0131:0xb0,0x0132:0xbd,0x0133:0xbf,0x0134:0x2122,0x0135:0xa2,0x0136:0xa3,0x0137:0x266a,0x0138:0xe0,0x0139:0xa0,0x013a:0xe8,0x013b:0xe2,0x013c:0xea,0x013d:0xee,0x013e:0xf4,0x013f:0xfb,0x0220:0xc1,0x0221:0xc9,0x0222:0xd3,0x0223:0xda,0x0224:0xdc,0x0225:0xfc,0x0226:0x2018,0x0227:0xa1,0x0228:0x2a,0x0229:0x27,0x022a:0x2014,0x022b:0xa9,0x022c:0x2120,0x022d:0x2022,0x022e:0x201c,0x022f:0x201d,0x0230:0xc0,0x0231:0xc2,0x0232:0xc7,0x0233:0xc8,0x0234:0xca,0x0235:0xcb,0x0236:0xeb,0x0237:0xce,0x0238:0xcf,0x0239:0xef,0x023a:0xd4,0x023b:0xd9,0x023c:0xf9,0x023d:0xdb,0x023e:0xab,0x023f:0xbb,0x0320:0xc3,0x0321:0xe3,0x0322:0xcd,0x0323:0xcc,0x0324:0xec,0x0325:0xd2,0x0326:0xf2,0x0327:0xd5,0x0328:0xf5,0x0329:0x7b,0x032a:0x7d,0x032b:0x5c,0x032c:0x5e,0x032d:0x5f,0x032e:0x7c,0x032f:0x7e,0x0330:0xc4,0x0331:0xe4,0x0332:0xd6,0x0333:0xf6,0x0334:0xdf,0x0335:0xa5,0x0336:0xa4,0x0337:0x2502,0x0338:0xc5,0x0339:0xe5,0x033a:0xd8,0x033b:0xf8,0x033c:0x250c,0x033d:0x2510,0x033e:0x2514,0x033f:0x2518};var getCharFromCode=function getCharFromCode(code){if(code===null){return'';}
code=CHARACTER_TRANSLATION[code]||code;return String.fromCharCode(code);};var BOTTOM_ROW=14;var ROWS=[0x1100,0x1120,0x1200,0x1220,0x1500,0x1520,0x1600,0x1620,0x1700,0x1720,0x1000,0x1300,0x1320,0x1400,0x1420];var createDisplayBuffer=function createDisplayBuffer(){var result=[],i=BOTTOM_ROW+1;while(i--){result.push('');}
return result;};var Cea608Stream=function Cea608Stream(field,dataChannel){Cea608Stream.prototype.init.call(this);this.field_=field||0;this.dataChannel_=dataChannel||0;this.name_='CC'+((this.field_<<1|this.dataChannel_)+1);this.setConstants();this.reset();this.push=function(packet){var data,swap,char0,char1,text;data=packet.ccData&0x7f7f;if(data===this.lastControlCode_){this.lastControlCode_=null;return;}
if((data&0xf000)===0x1000){this.lastControlCode_=data;}else if(data!==this.PADDING_){this.lastControlCode_=null;}
char0=data>>>8;char1=data&0xff;if(data===this.PADDING_){return;}else 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.ROLL_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_){if(this.mode_==='popOn'){this.nonDisplayed_[this.row_]=this.nonDisplayed_[this.row_].slice(0,-1);}else{this.displayed_[this.row_]=this.displayed_[this.row_].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_){if(this.mode_!=='paintOn'){this.flushDisplayed(packet.pts);this.displayed_=createDisplayBuffer();}
this.mode_='paintOn';this.startPts_=packet.pts;}else if(this.isSpecialCharacter(char0,char1)){char0=(char0&0x03)<<8;text=getCharFromCode(char0|char1);this[this.mode_](packet.pts,text);this.column_++;}else if(this.isExtCharacter(char0,char1)){if(this.mode_==='popOn'){this.nonDisplayed_[this.row_]=this.nonDisplayed_[this.row_].slice(0,-1);}else{this.displayed_[this.row_]=this.displayed_[this.row_].slice(0,-1);}
char0=(char0&0x03)<<8;text=getCharFromCode(char0|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_++;if((char1&0xe)===0xe){this.addFormatting(packet.pts,['i']);}
if((char1&0x1)===0x1){this.addFormatting(packet.pts,['u']);}}else if(this.isOffsetControlCode(char0,char1)){this.column_+=char1&0x03;}else if(this.isPAC(char0,char1)){var row=ROWS.indexOf(data&0x1f20);if(this.mode_==='rollUp'){if(row-this.rollUpRows_+1<0){row=this.rollUpRows_-1;}
this.setRollUp(packet.pts,row);}
if(row!==this.row_){this.clearFormatting(packet.pts);this.row_=row;}
if(char1&0x1&&this.formatting_.indexOf('u')===-1){this.addFormatting(packet.pts,['u']);}
if((data&0x10)===0x10){this.column_=((data&0xe)>>1)*4;}
if(this.isColorPAC(char1)){if((char1&0xe)===0xe){this.addFormatting(packet.pts,['i']);}}}else if(this.isNormalChar(char0)){if(char1===0x00){char1=null;}
text=getCharFromCode(char0);text+=getCharFromCode(char1);this[this.mode_](packet.pts,text);this.column_+=text.length;}};};Cea608Stream.prototype=new stream();Cea608Stream.prototype.flushDisplayed=function(pts){var content=this.displayed_.map(function(row){try{return row.trim();}catch(e){console.error('Skipping malformed caption.');return'';}}).join('\n').replace(/^\n+|\n+$/g,'');if(content.length){this.trigger('data',{startPts:this.startPts_,endPts:pts,text:content,stream:this.name_});}};Cea608Stream.prototype.reset=function(){this.mode_='popOn';this.topRow_=0;this.startPts_=0;this.displayed_=createDisplayBuffer();this.nonDisplayed_=createDisplayBuffer();this.lastControlCode_=null;this.column_=0;this.row_=BOTTOM_ROW;this.rollUpRows_=2;this.formatting_=[];};Cea608Stream.prototype.setConstants=function(){if(this.dataChannel_===0){this.BASE_=0x10;this.EXT_=0x11;this.CONTROL_=(0x14|this.field_)<<8;this.OFFSET_=0x17;}else if(this.dataChannel_===1){this.BASE_=0x18;this.EXT_=0x19;this.CONTROL_=(0x1c|this.field_)<<8;this.OFFSET_=0x1f;}
this.PADDING_=0x0000;this.RESUME_CAPTION_LOADING_=this.CONTROL_|0x20;this.END_OF_CAPTION_=this.CONTROL_|0x2f;this.ROLL_UP_2_ROWS_=this.CONTROL_|0x25;this.ROLL_UP_3_ROWS_=this.CONTROL_|0x26;this.ROLL_UP_4_ROWS_=this.CONTROL_|0x27;this.CARRIAGE_RETURN_=this.CONTROL_|0x2d;this.RESUME_DIRECT_CAPTIONING_=this.CONTROL_|0x29;this.BACKSPACE_=this.CONTROL_|0x21;this.ERASE_DISPLAYED_MEMORY_=this.CONTROL_|0x2c;this.ERASE_NON_DISPLAYED_MEMORY_=this.CONTROL_|0x2e;};Cea608Stream.prototype.isSpecialCharacter=function(char0,char1){return char0===this.EXT_&&char1>=0x30&&char1<=0x3f;};Cea608Stream.prototype.isExtCharacter=function(char0,char1){return(char0===this.EXT_+1||char0===this.EXT_+2)&&char1>=0x20&&char1<=0x3f;};Cea608Stream.prototype.isMidRowCode=function(char0,char1){return char0===this.EXT_&&char1>=0x20&&char1<=0x2f;};Cea608Stream.prototype.isOffsetControlCode=function(char0,char1){return char0===this.OFFSET_&&char1>=0x21&&char1<=0x23;};Cea608Stream.prototype.isPAC=function(char0,char1){return char0>=this.BASE_&&char0<this.BASE_+8&&char1>=0x40&&char1<=0x7f;};Cea608Stream.prototype.isColorPAC=function(char1){return char1>=0x40&&char1<=0x4f||char1>=0x60&&char1<=0x7f;};Cea608Stream.prototype.isNormalChar=function(_char2){return _char2>=0x20&&_char2<=0x7f;};Cea608Stream.prototype.setRollUp=function(pts,newBaseRow){if(this.mode_!=='rollUp'){this.row_=BOTTOM_ROW;this.mode_='rollUp';this.flushDisplayed(pts);this.nonDisplayed_=createDisplayBuffer();this.displayed_=createDisplayBuffer();}
if(newBaseRow!==undefined&&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]='';}}
if(newBaseRow===undefined){newBaseRow=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){return;}
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_];baseRow+=text;this.nonDisplayed_[this.row_]=baseRow;};Cea608Stream.prototype.rollUp=function(pts,text){var baseRow=this.displayed_[this.row_];baseRow+=text;this.displayed_[this.row_]=baseRow;};Cea608Stream.prototype.shiftRowsUp_=function(){var i;for(i=0;i<this.topRow_;i++){this.displayed_[i]='';}
for(i=this.row_+1;i<BOTTOM_ROW+1;i++){this.displayed_[i]='';}
for(i=this.topRow_;i<this.row_;i++){this.displayed_[i]=this.displayed_[i+1];}
this.displayed_[this.row_]='';};Cea608Stream.prototype.paintOn=function(pts,text){var baseRow=this.displayed_[this.row_];baseRow+=text;this.displayed_[this.row_]=baseRow;};var captionStream={CaptionStream:CaptionStream,Cea608Stream:Cea608Stream,Cea708Stream:Cea708Stream};var streamTypes={H264_STREAM_TYPE:0x1B,ADTS_STREAM_TYPE:0x0F,METADATA_STREAM_TYPE:0x15};var MAX_TS=8589934592;var RO_THRESH=4294967296;var TYPE_SHARED='shared';var handleRollover=function handleRollover(value,reference){var direction=1;if(value>reference){direction=-1;}
while(Math.abs(reference-value)>RO_THRESH){value+=direction*MAX_TS;}
return value;};var TimestampRolloverStream=function TimestampRolloverStream(type){var lastDTS,referenceDTS;TimestampRolloverStream.prototype.init.call(this);this.type_=type||TYPE_SHARED;this.push=function(data){if(this.type_!==TYPE_SHARED&&data.type!==this.type_){return;}
if(referenceDTS===undefined){referenceDTS=data.dts;}
data.dts=handleRollover(data.dts,referenceDTS);data.pts=handleRollover(data.pts,referenceDTS);lastDTS=data.dts;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.prototype=new stream();var timestampRolloverStream={TimestampRolloverStream:TimestampRolloverStream,handleRollover:handleRollover};var percentEncode=function percentEncode(bytes,start,end){var i,result='';for(i=start;i<end;i++){result+='%'+('00'+bytes[i].toString(16)).slice(-2);}
return result;},parseUtf8=function parseUtf8(bytes,start,end){return decodeURIComponent(percentEncode(bytes,start,end));},parseIso88591=function parseIso88591(bytes,start,end){return unescape(percentEncode(bytes,start,end));},parseSyncSafeInteger=function parseSyncSafeInteger(data){return data[0]<<21|data[1]<<14|data[2]<<7|data[3];},tagParsers={TXXX:function TXXX(tag){var i;if(tag.data[0]!==3){return;}
for(i=1;i<tag.data.length;i++){if(tag.data[i]===0){tag.description=parseUtf8(tag.data,1,i);tag.value=parseUtf8(tag.data,i+1,tag.data.length).replace(/\0*$/,'');break;}}
tag.data=tag.value;},WXXX:function WXXX(tag){var i;if(tag.data[0]!==3){return;}
for(i=1;i<tag.data.length;i++){if(tag.data[i]===0){tag.description=parseUtf8(tag.data,1,i);tag.url=parseUtf8(tag.data,i+1,tag.data.length);break;}}},PRIV:function PRIV(tag){var i;for(i=0;i<tag.data.length;i++){if(tag.data[i]===0){tag.owner=parseIso88591(tag.data,0,i);break;}}
tag.privateData=tag.data.subarray(i+1);tag.data=tag.privateData;}},_MetadataStream;_MetadataStream=function MetadataStream(options){var settings={debug:!!(options&&options.debug),descriptor:options&&options.descriptor},tagSize=0,buffer=[],bufferSize=0,i;_MetadataStream.prototype.init.call(this);this.dispatchType=streamTypes.METADATA_STREAM_TYPE.toString(16);if(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,frameHeader;if(chunk.type!=='timed-metadata'){return;}
if(chunk.dataAlignmentIndicator){bufferSize=0;buffer.length=0;}
if(buffer.length===0&&(chunk.data.length<10||chunk.data[0]!=='I'.charCodeAt(0)||chunk.data[1]!=='D'.charCodeAt(0)||chunk.data[2]!=='3'.charCodeAt(0))){if(settings.debug){console.log('Skipping unrecognized metadata packet');}
return;}
buffer.push(chunk);bufferSize+=chunk.data.byteLength;if(buffer.length===1){tagSize=parseSyncSafeInteger(chunk.data.subarray(6,10));tagSize+=10;}
if(bufferSize<tagSize){return;}
tag={data:new Uint8Array(tagSize),frames:[],pts:buffer[0].pts,dts:buffer[0].dts};for(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;if(tag.data[5]&0x40){frameStart+=4;frameStart+=parseSyncSafeInteger(tag.data.subarray(10,14));tagSize-=parseSyncSafeInteger(tag.data.subarray(16,20));}
do{frameSize=parseSyncSafeInteger(tag.data.subarray(frameStart+4,frameStart+8));if(frameSize<1){return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');}
frameHeader=String.fromCharCode(tag.data[frameStart],tag.data[frameStart+1],tag.data[frameStart+2],tag.data[frameStart+3]);frame={id:frameHeader,data:tag.data.subarray(frameStart+10,frameStart+frameSize+10)};frame.key=frame.id;if(tagParsers[frame.id]){tagParsers[frame.id](frame);if(frame.owner==='com.apple.streaming.transportStreamTimestamp'){var d=frame.data,size=(d[3]&0x01)<<30|d[4]<<22|d[5]<<14|d[6]<<6|d[7]>>>2;size*=4;size+=d[7]&0x03;frame.timeStamp=size;if(tag.pts===undefined&&tag.dts===undefined){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);};};_MetadataStream.prototype=new stream();var metadataStream=_MetadataStream;var TimestampRolloverStream$1=timestampRolloverStream.TimestampRolloverStream;var _TransportPacketStream,_TransportParseStream,_ElementaryStream;var MP2T_PACKET_LENGTH=188,SYNC_BYTE=0x47;_TransportPacketStream=function TransportPacketStream(){var buffer=new Uint8Array(MP2T_PACKET_LENGTH),bytesInBuffer=0;_TransportPacketStream.prototype.init.call(this);this.push=function(bytes){var startIndex=0,endIndex=MP2T_PACKET_LENGTH,everything;if(bytesInBuffer){everything=new Uint8Array(bytes.byteLength+bytesInBuffer);everything.set(buffer.subarray(0,bytesInBuffer));everything.set(bytes,bytesInBuffer);bytesInBuffer=0;}else{everything=bytes;}
while(endIndex<everything.byteLength){if(everything[startIndex]===SYNC_BYTE&&everything[endIndex]===SYNC_BYTE){this.trigger('data',everything.subarray(startIndex,endIndex));startIndex+=MP2T_PACKET_LENGTH;endIndex+=MP2T_PACKET_LENGTH;continue;}
startIndex++;endIndex++;}
if(startIndex<everything.byteLength){buffer.set(everything.subarray(startIndex),0);bytesInBuffer=everything.byteLength-startIndex;}};this.flush=function(){if(bytesInBuffer===MP2T_PACKET_LENGTH&&buffer[0]===SYNC_BYTE){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');};};_TransportPacketStream.prototype=new stream();_TransportParseStream=function TransportParseStream(){var parsePsi,parsePat,parsePmt,self;_TransportParseStream.prototype.init.call(this);self=this;this.packetsWaitingForPmt=[];this.programMapTable=undefined;parsePsi=function parsePsi(payload,psi){var offset=0;if(psi.payloadUnitStartIndicator){offset+=payload[offset]+1;}
if(psi.type==='pat'){parsePat(payload.subarray(offset),psi);}else{parsePmt(payload.subarray(offset),psi);}};parsePat=function parsePat(payload,pat){pat.section_number=payload[7];pat.last_section_number=payload[8];self.pmtPid=(payload[10]&0x1F)<<8|payload[11];pat.pmtPid=self.pmtPid;};parsePmt=function parsePmt(payload,pmt){var sectionLength,tableEnd,programInfoLength,offset;if(!(payload[5]&0x01)){return;}
self.programMapTable={video:null,audio:null,'timed-metadata':{}};sectionLength=(payload[1]&0x0f)<<8|payload[2];tableEnd=3+sectionLength-4;programInfoLength=(payload[10]&0x0f)<<8|payload[11];offset=12+programInfoLength;while(offset<tableEnd){var streamType=payload[offset];var pid=(payload[offset+1]&0x1F)<<8|payload[offset+2];if(streamType===streamTypes.H264_STREAM_TYPE&&self.programMapTable.video===null){self.programMapTable.video=pid;}else if(streamType===streamTypes.ADTS_STREAM_TYPE&&self.programMapTable.audio===null){self.programMapTable.audio=pid;}else if(streamType===streamTypes.METADATA_STREAM_TYPE){self.programMapTable['timed-metadata'][pid]=streamType;}
offset+=((payload[offset+3]&0x0F)<<8|payload[offset+4])+5;}
pmt.programMapTable=self.programMapTable;};this.push=function(packet){var result={},offset=4;result.payloadUnitStartIndicator=!!(packet[1]&0x40);result.pid=packet[1]&0x1f;result.pid<<=8;result.pid|=packet[2];if((packet[3]&0x30)>>>4>0x01){offset+=packet[offset]+1;}
if(result.pid===0){result.type='pat';parsePsi(packet.subarray(offset),result);this.trigger('data',result);}else if(result.pid===this.pmtPid){result.type='pmt';parsePsi(packet.subarray(offset),result);this.trigger('data',result);while(this.packetsWaitingForPmt.length){this.processPes_.apply(this,this.packetsWaitingForPmt.shift());}}else if(this.programMapTable===undefined){this.packetsWaitingForPmt.push([packet,offset,result]);}else{this.processPes_(packet,offset,result);}};this.processPes_=function(packet,offset,result){if(result.pid===this.programMapTable.video){result.streamType=streamTypes.H264_STREAM_TYPE;}else if(result.pid===this.programMapTable.audio){result.streamType=streamTypes.ADTS_STREAM_TYPE;}else{result.streamType=this.programMapTable['timed-metadata'][result.pid];}
result.type='pes';result.data=packet.subarray(offset);this.trigger('data',result);};};_TransportParseStream.prototype=new stream();_TransportParseStream.STREAM_TYPES={h264:0x1b,adts:0x0f};_ElementaryStream=function ElementaryStream(){var self=this,video={data:[],size:0},audio={data:[],size:0},timedMetadata={data:[],size:0},programMapTable,parsePes=function parsePes(payload,pes){var ptsDtsFlags;pes.packetLength=6+(payload[4]<<8|payload[5]);pes.dataAlignmentIndicator=(payload[6]&0x04)!==0;ptsDtsFlags=payload[7];if(ptsDtsFlags&0xC0){pes.pts=(payload[9]&0x0E)<<27|(payload[10]&0xFF)<<20|(payload[11]&0xFE)<<12|(payload[12]&0xFF)<<5|(payload[13]&0xFE)>>>3;pes.pts*=4;pes.pts+=(payload[13]&0x06)>>>1;pes.dts=pes.pts;if(ptsDtsFlags&0x40){pes.dts=(payload[14]&0x0E)<<27|(payload[15]&0xFF)<<20|(payload[16]&0xFE)<<12|(payload[17]&0xFF)<<5|(payload[18]&0xFE)>>>3;pes.dts*=4;pes.dts+=(payload[18]&0x06)>>>1;}}
pes.data=payload.subarray(9+payload[8]);},flushStream=function flushStream(stream,type,forceFlush){var packetData=new Uint8Array(stream.size),event={type:type},i=0,offset=0,packetFlushable=false,fragment;if(!stream.data.length||stream.size<9){return;}
event.trackId=stream.data[0].pid;for(i=0;i<stream.data.length;i++){fragment=stream.data[i];packetData.set(fragment.data,offset);offset+=fragment.data.byteLength;}
parsePes(packetData,event);packetFlushable=type==='video'||event.packetLength<=stream.size;if(forceFlush||packetFlushable){stream.size=0;stream.data.length=0;}
if(packetFlushable){self.trigger('data',event);}};_ElementaryStream.prototype.init.call(this);this.push=function(data){({pat:function pat(){},pes:function pes(){var stream,streamType;switch(data.streamType){case streamTypes.H264_STREAM_TYPE:stream=video;streamType='video';break;case streamTypes.ADTS_STREAM_TYPE:stream=audio;streamType='audio';break;case streamTypes.METADATA_STREAM_TYPE:stream=timedMetadata;streamType='timed-metadata';break;default:return;}
if(data.payloadUnitStartIndicator){flushStream(stream,streamType,true);}
stream.data.push(data);stream.size+=data.data.byteLength;},pmt:function pmt(){var event={type:'metadata',tracks:[]};programMapTable=data.programMapTable;if(programMapTable.video!==null){event.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+programMapTable.video,codec:'avc',type:'video'});}
if(programMapTable.audio!==null){event.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+programMapTable.audio,codec:'adts',type:'audio'});}
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(){this.flushStreams_();this.trigger('done');};};_ElementaryStream.prototype=new stream();var m2ts={PAT_PID:0x0000,MP2T_PACKET_LENGTH:MP2T_PACKET_LENGTH,TransportPacketStream:_TransportPacketStream,TransportParseStream:_TransportParseStream,ElementaryStream:_ElementaryStream,TimestampRolloverStream:TimestampRolloverStream$1,CaptionStream:captionStream.CaptionStream,Cea608Stream:captionStream.Cea608Stream,Cea708Stream:captionStream.Cea708Stream,MetadataStream:metadataStream};for(var type in streamTypes){if(streamTypes.hasOwnProperty(type)){m2ts[type]=streamTypes[type];}}
var m2ts_1=m2ts;var ONE_SECOND_IN_TS$2=clock.ONE_SECOND_IN_TS;var _AdtsStream;var ADTS_SAMPLING_FREQUENCIES=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350];_AdtsStream=function AdtsStream(handlePartialSegments){var buffer,frameNum=0;_AdtsStream.prototype.init.call(this);this.push=function(packet){var i=0,frameLength,protectionSkipBytes,frameEnd,oldBuffer,sampleCount,adtsFrameDuration;if(!handlePartialSegments){frameNum=0;}
if(packet.type!=='audio'){return;}
if(buffer){oldBuffer=buffer;buffer=new Uint8Array(oldBuffer.byteLength+packet.data.byteLength);buffer.set(oldBuffer);buffer.set(packet.data,oldBuffer.byteLength);}else{buffer=packet.data;}
while(i+5<buffer.length){if(buffer[i]!==0xFF||(buffer[i+1]&0xF6)!==0xF0){i++;continue;}
protectionSkipBytes=(~buffer[i+1]&0x01)*2;frameLength=(buffer[i+3]&0x03)<<11|buffer[i+4]<<3|(buffer[i+5]&0xe0)>>5;sampleCount=((buffer[i+6]&0x03)+1)*1024;adtsFrameDuration=sampleCount*ONE_SECOND_IN_TS$2/ADTS_SAMPLING_FREQUENCIES[(buffer[i+2]&0x3c)>>>2];frameEnd=i+frameLength;if(buffer.byteLength<frameEnd){return;}
this.trigger('data',{pts:packet.pts+frameNum*adtsFrameDuration,dts:packet.dts+frameNum*adtsFrameDuration,sampleCount:sampleCount,audioobjecttype:(buffer[i+2]>>>6&0x03)+1,channelcount:(buffer[i+2]&1)<<2|(buffer[i+3]&0xc0)>>>6,samplerate:ADTS_SAMPLING_FREQUENCIES[(buffer[i+2]&0x3c)>>>2],samplingfrequencyindex:(buffer[i+2]&0x3c)>>>2,samplesize:16,data:buffer.subarray(i+7+protectionSkipBytes,frameEnd)});frameNum++;if(buffer.byteLength===frameEnd){buffer=undefined;return;}
buffer=buffer.subarray(frameEnd);}};this.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');};};_AdtsStream.prototype=new stream();var adts=_AdtsStream;var ExpGolomb;ExpGolomb=function ExpGolomb(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(availableBytes===0){throw new Error('no bytes available');}
workingBytes.set(workingData.subarray(position,position+availableBytes));workingWord=new DataView(workingBytes.buffer).getUint32(0);workingBitsAvailable=availableBytes*8;workingBytesAvailable-=availableBytes;};this.skipBits=function(count){var skipBytes;if(workingBitsAvailable>count){workingWord<<=count;workingBitsAvailable-=count;}else{count-=workingBitsAvailable;skipBytes=Math.floor(count/8);count-=skipBytes*8;workingBytesAvailable-=skipBytes;this.loadWord();workingWord<<=count;workingBitsAvailable-=count;}};this.readBits=function(size){var bits=Math.min(workingBitsAvailable,size),valu=workingWord>>>32-bits;workingBitsAvailable-=bits;if(workingBitsAvailable>0){workingWord<<=bits;}else if(workingBytesAvailable>0){this.loadWord();}
bits=size-bits;if(bits>0){return valu<<bits|this.readBits(bits);}
return valu;};this.skipLeadingZeros=function(){var leadingZeroCount;for(leadingZeroCount=0;leadingZeroCount<workingBitsAvailable;++leadingZeroCount){if((workingWord&0x80000000>>>leadingZeroCount)!==0){workingWord<<=leadingZeroCount;workingBitsAvailable-=leadingZeroCount;return leadingZeroCount;}}
this.loadWord();return 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();return this.readBits(clz+1)-1;};this.readExpGolomb=function(){var valu=this.readUnsignedExpGolomb();if(0x01&valu){return 1+valu>>>1;}
return-1*(valu>>>1);};this.readBoolean=function(){return this.readBits(1)===1;};this.readUnsignedByte=function(){return this.readBits(8);};this.loadWord();};var expGolomb=ExpGolomb;var _H264Stream,_NalByteStream;var PROFILES_WITH_OPTIONAL_SPS_DATA;_NalByteStream=function NalByteStream(){var syncPoint=0,i,buffer;_NalByteStream.prototype.init.call(this);this.push=function(data){var swapBuffer;if(!buffer){buffer=data.data;}else{swapBuffer=new Uint8Array(buffer.byteLength+data.data.byteLength);swapBuffer.set(buffer);swapBuffer.set(data.data,buffer.byteLength);buffer=swapBuffer;}
var len=buffer.byteLength;for(;syncPoint<len-3;syncPoint++){if(buffer[syncPoint+2]===1){i=syncPoint+5;break;}}
while(i<len){switch(buffer[i]){case 0:if(buffer[i-1]!==0){i+=2;break;}else if(buffer[i-2]!==0){i++;break;}
if(syncPoint+3!==i-2){this.trigger('data',buffer.subarray(syncPoint+3,i-2));}
do{i++;}while(buffer[i]!==1&&i<len);syncPoint=i-2;i+=3;break;case 1:if(buffer[i-1]!==0||buffer[i-2]!==0){i+=3;break;}
this.trigger('data',buffer.subarray(syncPoint+3,i-2));syncPoint=i-2;i+=3;break;default:i+=3;break;}}
buffer=buffer.subarray(syncPoint);i-=syncPoint;syncPoint=0;};this.reset=function(){buffer=null;syncPoint=0;this.trigger('reset');};this.flush=function(){if(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');};};_NalByteStream.prototype=new stream();PROFILES_WITH_OPTIONAL_SPS_DATA={100:true,110:true,122:true,244:true,44:true,83:true,86:true,118:true,128:true,138:true,139:true,134:true};_H264Stream=function H264Stream(){var nalByteStream=new _NalByteStream(),self,trackId,currentPts,currentDts,discardEmulationPreventionBytes,readSequenceParameterSet,skipScalingList;_H264Stream.prototype.init.call(this);self=this;this.push=function(packet){if(packet.type!=='video'){return;}
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};switch(data[0]&0x1f){case 0x05:event.nalUnitType='slice_layer_without_partitioning_rbsp_idr';break;case 0x06:event.nalUnitType='sei_rbsp';event.escapedRBSP=discardEmulationPreventionBytes(data.subarray(1));break;case 0x07:event.nalUnitType='seq_parameter_set_rbsp';event.escapedRBSP=discardEmulationPreventionBytes(data.subarray(1));event.config=readSequenceParameterSet(event.escapedRBSP);break;case 0x08:event.nalUnitType='pic_parameter_set_rbsp';break;case 0x09:event.nalUnitType='access_unit_delimiter_rbsp';break;}
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=function(){nalByteStream.reset();};this.endTimeline=function(){nalByteStream.endTimeline();};skipScalingList=function skipScalingList(count,expGolombDecoder){var lastScale=8,nextScale=8,j,deltaScale;for(j=0;j<count;j++){if(nextScale!==0){deltaScale=expGolombDecoder.readExpGolomb();nextScale=(lastScale+deltaScale+256)%256;}
lastScale=nextScale===0?lastScale:nextScale;}};discardEmulationPreventionBytes=function discardEmulationPreventionBytes(data){var length=data.byteLength,emulationPreventionBytesPositions=[],i=1,newLength,newData;while(i<length-2){if(data[i]===0&&data[i+1]===0&&data[i+2]===0x03){emulationPreventionBytesPositions.push(i+2);i+=2;}else{i++;}}
if(emulationPreventionBytesPositions.length===0){return data;}
newLength=length-emulationPreventionBytesPositions.length;newData=new Uint8Array(newLength);var sourceIndex=0;for(i=0;i<newLength;sourceIndex++,i++){if(sourceIndex===emulationPreventionBytesPositions[0]){sourceIndex++;emulationPreventionBytesPositions.shift();}
newData[i]=data[sourceIndex];}
return newData;};readSequenceParameterSet=function readSequenceParameterSet(data){var frameCropLeftOffset=0,frameCropRightOffset=0,frameCropTopOffset=0,frameCropBottomOffset=0,sarScale=1,expGolombDecoder,profileIdc,levelIdc,profileCompatibility,chromaFormatIdc,picOrderCntType,numRefFramesInPicOrderCntCycle,picWidthInMbsMinus1,picHeightInMapUnitsMinus1,frameMbsOnlyFlag,scalingListCount,sarRatio,aspectRatioIdc,i;expGolombDecoder=new expGolomb(data);profileIdc=expGolombDecoder.readUnsignedByte();profileCompatibility=expGolombDecoder.readUnsignedByte();levelIdc=expGolombDecoder.readUnsignedByte();expGolombDecoder.skipUnsignedExpGolomb();if(PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]){chromaFormatIdc=expGolombDecoder.readUnsignedExpGolomb();if(chromaFormatIdc===3){expGolombDecoder.skipBits(1);}
expGolombDecoder.skipUnsignedExpGolomb();expGolombDecoder.skipUnsignedExpGolomb();expGolombDecoder.skipBits(1);if(expGolombDecoder.readBoolean()){scalingListCount=chromaFormatIdc!==3?8:12;for(i=0;i<scalingListCount;i++){if(expGolombDecoder.readBoolean()){if(i<6){skipScalingList(16,expGolombDecoder);}else{skipScalingList(64,expGolombDecoder);}}}}}
expGolombDecoder.skipUnsignedExpGolomb();picOrderCntType=expGolombDecoder.readUnsignedExpGolomb();if(picOrderCntType===0){expGolombDecoder.readUnsignedExpGolomb();}else if(picOrderCntType===1){expGolombDecoder.skipBits(1);expGolombDecoder.skipExpGolomb();expGolombDecoder.skipExpGolomb();numRefFramesInPicOrderCntCycle=expGolombDecoder.readUnsignedExpGolomb();for(i=0;i<numRefFramesInPicOrderCntCycle;i++){expGolombDecoder.skipExpGolomb();}}
expGolombDecoder.skipUnsignedExpGolomb();expGolombDecoder.skipBits(1);picWidthInMbsMinus1=expGolombDecoder.readUnsignedExpGolomb();picHeightInMapUnitsMinus1=expGolombDecoder.readUnsignedExpGolomb();frameMbsOnlyFlag=expGolombDecoder.readBits(1);if(frameMbsOnlyFlag===0){expGolombDecoder.skipBits(1);}
expGolombDecoder.skipBits(1);if(expGolombDecoder.readBoolean()){frameCropLeftOffset=expGolombDecoder.readUnsignedExpGolomb();frameCropRightOffset=expGolombDecoder.readUnsignedExpGolomb();frameCropTopOffset=expGolombDecoder.readUnsignedExpGolomb();frameCropBottomOffset=expGolombDecoder.readUnsignedExpGolomb();}
if(expGolombDecoder.readBoolean()){if(expGolombDecoder.readBoolean()){aspectRatioIdc=expGolombDecoder.readUnsignedByte();switch(aspectRatioIdc){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()];break;}}
if(sarRatio){sarScale=sarRatio[0]/sarRatio[1];}}}
return{profileIdc:profileIdc,levelIdc:levelIdc,profileCompatibility:profileCompatibility,width:Math.ceil(((picWidthInMbsMinus1+1)*16-frameCropLeftOffset*2-frameCropRightOffset*2)*sarScale),height:(2-frameMbsOnlyFlag)*(picHeightInMapUnitsMinus1+1)*16-frameCropTopOffset*2-frameCropBottomOffset*2,sarRatio:sarRatio};};};_H264Stream.prototype=new stream();var h264={H264Stream:_H264Stream,NalByteStream:_NalByteStream};var ADTS_SAMPLING_FREQUENCIES$1=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350];var parseId3TagSize=function parseId3TagSize(header,byteIndex){var returnSize=header[byteIndex+6]<<21|header[byteIndex+7]<<14|header[byteIndex+8]<<7|header[byteIndex+9],flags=header[byteIndex+5],footerPresent=(flags&16)>>4;returnSize=returnSize>=0?returnSize:0;if(footerPresent){return returnSize+20;}
return returnSize+10;};var getId3Offset=function getId3Offset(data,offset){if(data.length-offset<10||data[offset]!=='I'.charCodeAt(0)||data[offset+1]!=='D'.charCodeAt(0)||data[offset+2]!=='3'.charCodeAt(0)){return offset;}
offset+=parseId3TagSize(data,offset);return getId3Offset(data,offset);};var isLikelyAacData=function isLikelyAacData(data){var offset=getId3Offset(data,0);return data.length>=offset+2&&(data[offset]&0xFF)===0xFF&&(data[offset+1]&0xF0)===0xF0&&(data[offset+1]&0x16)===0x10;};var parseSyncSafeInteger$1=function parseSyncSafeInteger(data){return data[0]<<21|data[1]<<14|data[2]<<7|data[3];};var percentEncode$1=function percentEncode(bytes,start,end){var i,result='';for(i=start;i<end;i++){result+='%'+('00'+bytes[i].toString(16)).slice(-2);}
return result;};var parseIso88591$1=function parseIso88591(bytes,start,end){return unescape(percentEncode$1(bytes,start,end));};var parseAdtsSize=function parseAdtsSize(header,byteIndex){var lowThree=(header[byteIndex+5]&0xE0)>>5,middle=header[byteIndex+4]<<3,highTwo=header[byteIndex+3]&0x3<<11;return highTwo|middle|lowThree;};var parseType=function parseType(header,byteIndex){if(header[byteIndex]==='I'.charCodeAt(0)&&header[byteIndex+1]==='D'.charCodeAt(0)&&header[byteIndex+2]==='3'.charCodeAt(0)){return'timed-metadata';}else if(header[byteIndex]&0xff===0xff&&(header[byteIndex+1]&0xf0)===0xf0){return'audio';}
return null;};var parseSampleRate=function parseSampleRate(packet){var i=0;while(i+5<packet.length){if(packet[i]!==0xFF||(packet[i+1]&0xF6)!==0xF0){i++;continue;}
return ADTS_SAMPLING_FREQUENCIES$1[(packet[i+2]&0x3c)>>>2];}
return null;};var parseAacTimestamp=function parseAacTimestamp(packet){var frameStart,frameSize,frame,frameHeader;frameStart=10;if(packet[5]&0x40){frameStart+=4;frameStart+=parseSyncSafeInteger$1(packet.subarray(10,14));}
do{frameSize=parseSyncSafeInteger$1(packet.subarray(frameStart+4,frameStart+8));if(frameSize<1){return null;}
frameHeader=String.fromCharCode(packet[frameStart],packet[frameStart+1],packet[frameStart+2],packet[frameStart+3]);if(frameHeader==='PRIV'){frame=packet.subarray(frameStart+10,frameStart+frameSize+10);for(var i=0;i<frame.byteLength;i++){if(frame[i]===0){var owner=parseIso88591$1(frame,0,i);if(owner==='com.apple.streaming.transportStreamTimestamp'){var d=frame.subarray(i+1);var size=(d[3]&0x01)<<30|d[4]<<22|d[5]<<14|d[6]<<6|d[7]>>>2;size*=4;size+=d[7]&0x03;return size;}
break;}}}
frameStart+=10;frameStart+=frameSize;}while(frameStart<packet.byteLength);return null;};var utils={isLikelyAacData:isLikelyAacData,parseId3TagSize:parseId3TagSize,parseAdtsSize:parseAdtsSize,parseType:parseType,parseSampleRate:parseSampleRate,parseAacTimestamp:parseAacTimestamp};var _AacStream;_AacStream=function AacStream(){var everything=new Uint8Array(),timeStamp=0;_AacStream.prototype.init.call(this);this.setTimestamp=function(timestamp){timeStamp=timestamp;};this.push=function(bytes){var frameSize=0,byteIndex=0,bytesLeft,chunk,packet,tempLength;if(everything.length){tempLength=everything.length;everything=new Uint8Array(bytes.byteLength+tempLength);everything.set(everything.subarray(0,tempLength));everything.set(bytes,tempLength);}else{everything=bytes;}
while(everything.length-byteIndex>=3){if(everything[byteIndex]==='I'.charCodeAt(0)&&everything[byteIndex+1]==='D'.charCodeAt(0)&&everything[byteIndex+2]==='3'.charCodeAt(0)){if(everything.length-byteIndex<10){break;}
frameSize=utils.parseId3TagSize(everything,byteIndex);if(byteIndex+frameSize>everything.length){break;}
chunk={type:'timed-metadata',data:everything.subarray(byteIndex,byteIndex+frameSize)};this.trigger('data',chunk);byteIndex+=frameSize;continue;}else if((everything[byteIndex]&0xff)===0xff&&(everything[byteIndex+1]&0xf0)===0xf0){if(everything.length-byteIndex<7){break;}
frameSize=utils.parseAdtsSize(everything,byteIndex);if(byteIndex+frameSize>everything.length){break;}
packet={type:'audio',data:everything.subarray(byteIndex,byteIndex+frameSize),pts:timeStamp,dts:timeStamp};this.trigger('data',packet);byteIndex+=frameSize;continue;}
byteIndex++;}
bytesLeft=everything.length-byteIndex;if(bytesLeft>0){everything=everything.subarray(byteIndex);}else{everything=new Uint8Array();}};this.reset=function(){everything=new Uint8Array();this.trigger('reset');};this.endTimeline=function(){everything=new Uint8Array();this.trigger('endedtimeline');};};_AacStream.prototype=new stream();var aac=_AacStream;var AUDIO_PROPERTIES=['audioobjecttype','channelcount','samplerate','samplingfrequencyindex','samplesize'];var audioProperties=AUDIO_PROPERTIES;var VIDEO_PROPERTIES=['width','height','profileIdc','levelIdc','profileCompatibility','sarRatio'];var videoProperties=VIDEO_PROPERTIES;var H264Stream=h264.H264Stream;var isLikelyAacData$1=utils.isLikelyAacData;var ONE_SECOND_IN_TS$3=clock.ONE_SECOND_IN_TS;var _VideoSegmentStream,_AudioSegmentStream,_Transmuxer,_CoalesceStream;var arrayEquals=function arrayEquals(a,b){var i;if(a.length!==b.length){return false;}
for(i=0;i<a.length;i++){if(a[i]!==b[i]){return false;}}
return true;};var generateSegmentTimingInfo=function generateSegmentTimingInfo(baseMediaDecodeTime,startDts,startPts,endDts,endPts,prependedContentDuration){var ptsOffsetFromDts=startPts-startDts,decodeDuration=endDts-startDts,presentationDuration=endPts-startPts;return{start:{dts:baseMediaDecodeTime,pts:baseMediaDecodeTime+ptsOffsetFromDts},end:{dts:baseMediaDecodeTime+decodeDuration,pts:baseMediaDecodeTime+presentationDuration},prependedContentDuration:prependedContentDuration,baseMediaDecodeTime:baseMediaDecodeTime};};_AudioSegmentStream=function AudioSegmentStream(track,options){var adtsFrames=[],sequenceNumber=0,earliestAllowedDts=0,audioAppendStartTs=0,videoBaseMediaDecodeTime=Infinity;options=options||{};_AudioSegmentStream.prototype.init.call(this);this.push=function(data){trackDecodeInfo.collectDtsInfo(track,data);if(track){audioProperties.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,videoClockCyclesOfSilencePrefixed;if(adtsFrames.length===0){this.trigger('done','AudioSegmentStream');return;}
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=mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));adtsFrames=[];moof=mp4Generator.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(ONE_SECOND_IN_TS$3*1024/track.samplerate);if(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].pts+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.reset=function(){trackDecodeInfo.clearDtsInfo(track);adtsFrames=[];this.trigger('reset');};};_AudioSegmentStream.prototype=new stream();_VideoSegmentStream=function VideoSegmentStream(track,options){var sequenceNumber=0,nalUnits=[],gopsToAlignWith=[],config,pps;options=options||{};_VideoSegmentStream.prototype.init.call(this);delete track.minPTS;this.gopCache_=[];this.push=function(nalUnit){trackDecodeInfo.collectDtsInfo(track,nalUnit);if(nalUnit.nalUnitType==='seq_parameter_set_rbsp'&&!config){config=nalUnit.config;track.sps=[nalUnit.data];videoProperties.forEach(function(prop){track[prop]=config[prop];},this);}
if(nalUnit.nalUnitType==='pic_parameter_set_rbsp'&&!pps){pps=nalUnit.data;track.pps=[nalUnit.data];}
nalUnits.push(nalUnit);};this.flush=function(){var frames,gopForFusion,gops,moof,mdat,boxes,prependedContentDuration=0,firstGop,lastGop;while(nalUnits.length){if(nalUnits[0].nalUnitType==='access_unit_delimiter_rbsp'){break;}
nalUnits.shift();}
if(nalUnits.length===0){this.resetStream_();this.trigger('done','VideoSegmentStream');return;}
frames=frameUtils.groupNalsIntoFrames(nalUnits);gops=frameUtils.groupFramesIntoGops(frames);if(!gops[0][0].keyFrame){gopForFusion=this.getGopForFusion_(nalUnits[0],track);if(gopForFusion){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;}else{gops=frameUtils.extendFirstKeyFrame(gops);}}
if(gopsToAlignWith.length){var alignedGops;if(options.alignGopsAtEnd){alignedGops=this.alignGopsAtEnd_(gops);}else{alignedGops=this.alignGopsAtStart_(gops);}
if(!alignedGops){this.gopCache_.unshift({gop:gops.pop(),pps:track.pps,sps:track.sps});this.gopCache_.length=Math.min(6,this.gopCache_.length);nalUnits=[];this.resetStream_();this.trigger('done','VideoSegmentStream');return;}
trackDecodeInfo.clearDtsInfo(track);gops=alignedGops;}
trackDecodeInfo.collectDtsInfo(track,gops);track.samples=frameUtils.generateSampleTable(gops);mdat=mp4Generator.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('baseMediaDecodeTime',track.baseMediaDecodeTime);this.trigger('timelineStartInfo',track.timelineStartInfo);moof=mp4Generator.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=undefined;pps=undefined;};this.getGopForFusion_=function(nalUnit){var halfSecond=45000,allowableOverlap=10000,nearestDistance=Infinity,dtsDistance,nearestGopObj,currentGop,currentGopObj,i;for(i=0;i<this.gopCache_.length;i++){currentGopObj=this.gopCache_[i];currentGop=currentGopObj.gop;if(!(track.pps&&arrayEquals(track.pps[0],currentGopObj.pps[0]))||!(track.sps&&arrayEquals(track.sps[0],currentGopObj.sps[0]))){continue;}
if(currentGop.dts<track.timelineStartInfo.dts){continue;}
dtsDistance=nalUnit.dts-currentGop.dts-currentGop.duration;if(dtsDistance>=-allowableOverlap&&dtsDistance<=halfSecond){if(!nearestGopObj||nearestDistance>dtsDistance){nearestGopObj=currentGopObj;nearestDistance=dtsDistance;}}}
if(nearestGopObj){return nearestGopObj.gop;}
return null;};this.alignGopsAtStart_=function(gops){var alignIndex,gopIndex,align,gop,byteLength,nalCount,duration,alignedGops;byteLength=gops.byteLength;nalCount=gops.nalCount;duration=gops.duration;alignIndex=gopIndex=0;while(alignIndex<gopsToAlignWith.length&&gopIndex<gops.length){align=gopsToAlignWith[alignIndex];gop=gops[gopIndex];if(align.pts===gop.pts){break;}
if(gop.pts>align.pts){alignIndex++;continue;}
gopIndex++;byteLength-=gop.byteLength;nalCount-=gop.nalCount;duration-=gop.duration;}
if(gopIndex===0){return gops;}
if(gopIndex===gops.length){return null;}
alignedGops=gops.slice(gopIndex);alignedGops.byteLength=byteLength;alignedGops.duration=duration;alignedGops.nalCount=nalCount;alignedGops.pts=alignedGops[0].pts;alignedGops.dts=alignedGops[0].dts;return alignedGops;};this.alignGopsAtEnd_=function(gops){var alignIndex,gopIndex,align,gop,alignEndIndex,matchFound;alignIndex=gopsToAlignWith.length-1;gopIndex=gops.length-1;alignEndIndex=null;matchFound=false;while(alignIndex>=0&&gopIndex>=0){align=gopsToAlignWith[alignIndex];gop=gops[gopIndex];if(align.pts===gop.pts){matchFound=true;break;}
if(align.pts>gop.pts){alignIndex--;continue;}
if(alignIndex===gopsToAlignWith.length-1){alignEndIndex=gopIndex;}
gopIndex--;}
if(!matchFound&&alignEndIndex===null){return null;}
var trimIndex;if(matchFound){trimIndex=gopIndex;}else{trimIndex=alignEndIndex;}
if(trimIndex===0){return gops;}
var alignedGops=gops.slice(trimIndex);var metadata=alignedGops.reduce(function(total,gop){total.byteLength+=gop.byteLength;total.duration+=gop.duration;total.nalCount+=gop.nalCount;return total;},{byteLength:0,duration:0,nalCount:0});alignedGops.byteLength=metadata.byteLength;alignedGops.duration=metadata.duration;alignedGops.nalCount=metadata.nalCount;alignedGops.pts=alignedGops[0].pts;alignedGops.dts=alignedGops[0].dts;return alignedGops;};this.alignGopsWith=function(newGopsToAlignWith){gopsToAlignWith=newGopsToAlignWith;};};_VideoSegmentStream.prototype=new stream();_CoalesceStream=function CoalesceStream(options,metadataStream){this.numberOfTracks=0;this.metadataStream=metadataStream;options=options||{};if(typeof options.remux!=='undefined'){this.remuxTracks=!!options.remux;}else{this.remuxTracks=true;}
if(typeof options.keepOriginalTimestamps==='boolean'){this.keepOriginalTimestamps=options.keepOriginalTimestamps;}else{this.keepOriginalTimestamps=false;}
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){if(output.text){return this.pendingCaptions.push(output);}
if(output.frames){return this.pendingMetadata.push(output);}
this.pendingTracks.push(output.track);this.pendingBytes+=output.boxes.byteLength;if(output.track.type==='video'){this.videoTrack=output.track;this.pendingBoxes.push(output.boxes);}
if(output.track.type==='audio'){this.audioTrack=output.track;this.pendingBoxes.unshift(output.boxes);}};};_CoalesceStream.prototype=new stream();_CoalesceStream.prototype.flush=function(flushSource){var offset=0,event={captions:[],captionStreams:{},metadata:[],info:{}},caption,id3,initSegment,timelineStartPts=0,i;if(this.pendingTracks.length<this.numberOfTracks){if(flushSource!=='VideoSegmentStream'&&flushSource!=='AudioSegmentStream'){return;}else if(this.remuxTracks){return;}else if(this.pendingTracks.length===0){this.emittedTracks++;if(this.emittedTracks>=this.numberOfTracks){this.trigger('done');this.emittedTracks=0;}
return;}}
if(this.videoTrack){timelineStartPts=this.videoTrack.timelineStartInfo.pts;videoProperties.forEach(function(prop){event.info[prop]=this.videoTrack[prop];},this);}else if(this.audioTrack){timelineStartPts=this.audioTrack.timelineStartInfo.pts;audioProperties.forEach(function(prop){event.info[prop]=this.audioTrack[prop];},this);}
if(this.videoTrack||this.audioTrack){if(this.pendingTracks.length===1){event.type=this.pendingTracks[0].type;}else{event.type='combined';}
this.emittedTracks+=this.pendingTracks.length;initSegment=mp4Generator.initSegment(this.pendingTracks);event.initSegment=new Uint8Array(initSegment.byteLength);event.initSegment.set(initSegment);event.data=new Uint8Array(this.pendingBytes);for(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];caption.startTime=clock.metadataTsToSeconds(caption.startPts,timelineStartPts,this.keepOriginalTimestamps);caption.endTime=clock.metadataTsToSeconds(caption.endPts,timelineStartPts,this.keepOriginalTimestamps);event.captionStreams[caption.stream]=true;event.captions.push(caption);}
for(i=0;i<this.pendingMetadata.length;i++){id3=this.pendingMetadata[i];id3.cueTime=clock.metadataTsToSeconds(id3.pts,timelineStartPts,this.keepOriginalTimestamps);event.metadata.push(id3);}
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);for(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);}}
if(this.emittedTracks>=this.numberOfTracks){this.trigger('done');this.emittedTracks=0;}};_CoalesceStream.prototype.setRemux=function(val){this.remuxTracks=val;};_Transmuxer=function Transmuxer(options){var self=this,hasFlushed=true,videoTrack,audioTrack;_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_1.MetadataStream();pipeline.aacStream=new aac();pipeline.audioTimestampRolloverStream=new m2ts_1.TimestampRolloverStream('audio');pipeline.timedMetadataTimestampRolloverStream=new m2ts_1.TimestampRolloverStream('timed-metadata');pipeline.adtsStream=new adts();pipeline.coalesceStream=new _CoalesceStream(options,pipeline.metadataStream);pipeline.headOfPipeline=pipeline.aacStream;pipeline.aacStream.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){if(data.type!=='timed-metadata'&&data.type!=='audio'||pipeline.audioSegmentStream){return;}
audioTrack=audioTrack||{timelineStartInfo:{baseMediaDecodeTime:self.baseMediaDecodeTime},codec:'adts',type:'audio'};pipeline.coalesceStream.numberOfTracks++;pipeline.audioSegmentStream=new _AudioSegmentStream(audioTrack,options);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('data',this.trigger.bind(this,'data'));pipeline.coalesceStream.on('done',this.trigger.bind(this,'done'));};this.setupTsPipeline=function(){var pipeline={};this.transmuxPipeline_=pipeline;pipeline.type='ts';pipeline.metadataStream=new m2ts_1.MetadataStream();pipeline.packetStream=new m2ts_1.TransportPacketStream();pipeline.parseStream=new m2ts_1.TransportParseStream();pipeline.elementaryStream=new m2ts_1.ElementaryStream();pipeline.timestampRolloverStream=new m2ts_1.TimestampRolloverStream();pipeline.adtsStream=new adts();pipeline.h264Stream=new H264Stream();pipeline.captionStream=new m2ts_1.CaptionStream();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.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);pipeline.elementaryStream.on('data',function(data){var i;if(data.type==='metadata'){i=data.tracks.length;while(i--){if(!videoTrack&&data.tracks[i].type==='video'){videoTrack=data.tracks[i];videoTrack.timelineStartInfo.baseMediaDecodeTime=self.baseMediaDecodeTime;}else if(!audioTrack&&data.tracks[i].type==='audio'){audioTrack=data.tracks[i];audioTrack.timelineStartInfo.baseMediaDecodeTime=self.baseMediaDecodeTime;}}
if(videoTrack&&!pipeline.videoSegmentStream){pipeline.coalesceStream.numberOfTracks++;pipeline.videoSegmentStream=new _VideoSegmentStream(videoTrack,options);pipeline.videoSegmentStream.on('timelineStartInfo',function(timelineStartInfo){if(audioTrack&&!options.keepOriginalTimestamps){audioTrack.timelineStartInfo=timelineStartInfo;pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts-self.baseMediaDecodeTime);}});pipeline.videoSegmentStream.on('processedGopsInfo',self.trigger.bind(self,'gopInfo'));pipeline.videoSegmentStream.on('segmentTimingInfo',self.trigger.bind(self,'videoSegmentTimingInfo'));pipeline.videoSegmentStream.on('baseMediaDecodeTime',function(baseMediaDecodeTime){if(audioTrack){pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);}});pipeline.videoSegmentStream.on('timingInfo',self.trigger.bind(self,'videoTimingInfo'));pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);}
if(audioTrack&&!pipeline.audioSegmentStream){pipeline.coalesceStream.numberOfTracks++;pipeline.audioSegmentStream=new _AudioSegmentStream(audioTrack,options);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'));};this.setBaseMediaDecodeTime=function(baseMediaDecodeTime){var pipeline=this.transmuxPipeline_;if(!options.keepOriginalTimestamps){this.baseMediaDecodeTime=baseMediaDecodeTime;}
if(audioTrack){audioTrack.timelineStartInfo.dts=undefined;audioTrack.timelineStartInfo.pts=undefined;trackDecodeInfo.clearDtsInfo(audioTrack);if(pipeline.audioTimestampRolloverStream){pipeline.audioTimestampRolloverStream.discontinuity();}}
if(videoTrack){if(pipeline.videoSegmentStream){pipeline.videoSegmentStream.gopCache_=[];}
videoTrack.timelineStartInfo.dts=undefined;videoTrack.timelineStartInfo.pts=undefined;trackDecodeInfo.clearDtsInfo(videoTrack);pipeline.captionStream.reset();}
if(pipeline.timestampRolloverStream){pipeline.timestampRolloverStream.discontinuity();}};this.setAudioAppendStart=function(timestamp){if(audioTrack){this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);}};this.setRemux=function(val){var pipeline=this.transmuxPipeline_;options.remux=val;if(pipeline&&pipeline.coalesceStream){pipeline.coalesceStream.setRemux(val);}};this.alignGopsWith=function(gopsToAlignWith){if(videoTrack&&this.transmuxPipeline_.videoSegmentStream){this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);}};this.push=function(data){if(hasFlushed){var isAac=isLikelyAacData$1(data);if(isAac&&this.transmuxPipeline_.type!=='aac'){this.setupAacPipeline();}else if(!isAac&&this.transmuxPipeline_.type!=='ts'){this.setupTsPipeline();}
hasFlushed=false;}
this.transmuxPipeline_.headOfPipeline.push(data);};this.flush=function(){hasFlushed=true;this.transmuxPipeline_.headOfPipeline.flush();};this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline();};this.reset=function(){if(this.transmuxPipeline_.headOfPipeline){this.transmuxPipeline_.headOfPipeline.reset();}};this.resetCaptions=function(){if(this.transmuxPipeline_.captionStream){this.transmuxPipeline_.captionStream.reset();}};};_Transmuxer.prototype=new stream();var transmuxer={Transmuxer:_Transmuxer,VideoSegmentStream:_VideoSegmentStream,AudioSegmentStream:_AudioSegmentStream,AUDIO_PROPERTIES:audioProperties,VIDEO_PROPERTIES:videoProperties,generateSegmentTimingInfo:generateSegmentTimingInfo};var codecs={Adts:adts,h264:h264};var ONE_SECOND_IN_TS$4=clock.ONE_SECOND_IN_TS;var AudioSegmentStream=function AudioSegmentStream(track,options){var adtsFrames=[],sequenceNumber=0,earliestAllowedDts=0,audioAppendStartTs=0,videoBaseMediaDecodeTime=Infinity,segmentStartPts=null,segmentEndPts=null;options=options||{};AudioSegmentStream.prototype.init.call(this);this.push=function(data){trackDecodeInfo.collectDtsInfo(track,data);if(track){audioProperties.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.processFrames_=function(){var frames,moof,mdat,boxes,timingInfo;if(adtsFrames.length===0){return;}
frames=audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames,track,earliestAllowedDts);if(frames.length===0){return;}
track.baseMediaDecodeTime=trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track,options.keepOriginalTimestamps);audioFrameUtils.prefixWithSilence(track,frames,audioAppendStartTs,videoBaseMediaDecodeTime);track.samples=audioFrameUtils.generateSampleTable(frames);mdat=mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));adtsFrames=[];moof=mp4Generator.moof(sequenceNumber,[track]);sequenceNumber++;track.initSegment=mp4Generator.initSegment([track]);boxes=new Uint8Array(moof.byteLength+mdat.byteLength);boxes.set(moof);boxes.set(mdat,moof.byteLength);trackDecodeInfo.clearDtsInfo(track);if(segmentStartPts===null){segmentEndPts=segmentStartPts=frames[0].pts;}
segmentEndPts+=frames.length*(ONE_SECOND_IN_TS$4*1024/track.samplerate);timingInfo={start:segmentStartPts};this.trigger('timingInfo',timingInfo);this.trigger('data',{track:track,boxes:boxes});};this.flush=function(){this.processFrames_();this.trigger('timingInfo',{start:segmentStartPts,end:segmentEndPts});this.resetTiming_();this.trigger('done','AudioSegmentStream');};this.partialFlush=function(){this.processFrames_();this.trigger('partialdone','AudioSegmentStream');};this.endTimeline=function(){this.flush();this.trigger('endedtimeline','AudioSegmentStream');};this.resetTiming_=function(){trackDecodeInfo.clearDtsInfo(track);segmentStartPts=null;segmentEndPts=null;};this.reset=function(){this.resetTiming_();adtsFrames=[];this.trigger('reset');};};AudioSegmentStream.prototype=new stream();var audioSegmentStream=AudioSegmentStream;var VideoSegmentStream=function VideoSegmentStream(track,options){var sequenceNumber=0,nalUnits=[],frameCache=[],config,pps,segmentStartPts=null,segmentEndPts=null,gops,ensureNextFrameIsKeyFrame=true;options=options||{};VideoSegmentStream.prototype.init.call(this);this.push=function(nalUnit){trackDecodeInfo.collectDtsInfo(track,nalUnit);if(typeof track.timelineStartInfo.dts==='undefined'){track.timelineStartInfo.dts=nalUnit.dts;}
if(nalUnit.nalUnitType==='seq_parameter_set_rbsp'&&!config){config=nalUnit.config;track.sps=[nalUnit.data];videoProperties.forEach(function(prop){track[prop]=config[prop];},this);}
if(nalUnit.nalUnitType==='pic_parameter_set_rbsp'&&!pps){pps=nalUnit.data;track.pps=[nalUnit.data];}
nalUnits.push(nalUnit);};this.processNals_=function(cacheLastFrame){var i;nalUnits=frameCache.concat(nalUnits);while(nalUnits.length){if(nalUnits[0].nalUnitType==='access_unit_delimiter_rbsp'){break;}
nalUnits.shift();}
if(nalUnits.length===0){return;}
var frames=frameUtils.groupNalsIntoFrames(nalUnits);if(!frames.length){return;}
frameCache=frames[frames.length-1];if(cacheLastFrame){frames.pop();frames.duration-=frameCache.duration;frames.nalCount-=frameCache.length;frames.byteLength-=frameCache.byteLength;}
if(!frames.length){nalUnits=[];return;}
this.trigger('timelineStartInfo',track.timelineStartInfo);if(ensureNextFrameIsKeyFrame){gops=frameUtils.groupFramesIntoGops(frames);if(!gops[0][0].keyFrame){gops=frameUtils.extendFirstKeyFrame(gops);if(!gops[0][0].keyFrame){nalUnits=[].concat.apply([],frames).concat(frameCache);frameCache=[];return;}
frames=[].concat.apply([],gops);frames.duration=gops.duration;}
ensureNextFrameIsKeyFrame=false;}
if(segmentStartPts===null){segmentStartPts=frames[0].pts;segmentEndPts=segmentStartPts;}
segmentEndPts+=frames.duration;this.trigger('timingInfo',{start:segmentStartPts,end:segmentEndPts});for(i=0;i<frames.length;i++){var frame=frames[i];track.samples=frameUtils.generateSampleTableForFrame(frame);var mdat=mp4Generator.mdat(frameUtils.concatenateNalDataForFrame(frame));trackDecodeInfo.clearDtsInfo(track);trackDecodeInfo.collectDtsInfo(track,frame);track.baseMediaDecodeTime=trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track,options.keepOriginalTimestamps);var moof=mp4Generator.moof(sequenceNumber,[track]);sequenceNumber++;track.initSegment=mp4Generator.initSegment([track]);var boxes=new Uint8Array(moof.byteLength+mdat.byteLength);boxes.set(moof);boxes.set(mdat,moof.byteLength);this.trigger('data',{track:track,boxes:boxes,sequence:sequenceNumber,videoFrameDts:frame.dts,videoFramePts:frame.pts});}
nalUnits=[];};this.resetTimingAndConfig_=function(){config=undefined;pps=undefined;segmentStartPts=null;segmentEndPts=null;};this.partialFlush=function(){this.processNals_(true);this.trigger('partialdone','VideoSegmentStream');};this.flush=function(){this.processNals_(false);this.resetTimingAndConfig_();this.trigger('done','VideoSegmentStream');};this.endTimeline=function(){this.flush();this.trigger('endedtimeline','VideoSegmentStream');};this.reset=function(){this.resetTimingAndConfig_();frameCache=[];nalUnits=[];ensureNextFrameIsKeyFrame=true;this.trigger('reset');};};VideoSegmentStream.prototype=new stream();var videoSegmentStream=VideoSegmentStream;var isLikelyAacData$2=utils.isLikelyAacData;var createPipeline=function createPipeline(object){object.prototype=new stream();object.prototype.init.call(object);return object;};var tsPipeline=function tsPipeline(options){var pipeline={type:'ts',tracks:{audio:null,video:null},packet:new m2ts_1.TransportPacketStream(),parse:new m2ts_1.TransportParseStream(),elementary:new m2ts_1.ElementaryStream(),timestampRollover:new m2ts_1.TimestampRolloverStream(),adts:new codecs.Adts(),h264:new codecs.h264.H264Stream(),captionStream:new m2ts_1.CaptionStream(),metadataStream:new m2ts_1.MetadataStream()};pipeline.headOfPipeline=pipeline.packet;pipeline.packet.pipe(pipeline.parse).pipe(pipeline.elementary).pipe(pipeline.timestampRollover);pipeline.timestampRollover.pipe(pipeline.h264);pipeline.h264.pipe(pipeline.captionStream);pipeline.timestampRollover.pipe(pipeline.metadataStream);pipeline.timestampRollover.pipe(pipeline.adts);pipeline.elementary.on('data',function(data){if(data.type!=='metadata'){return;}
for(var i=0;i<data.tracks.length;i++){if(!pipeline.tracks[data.tracks[i].type]){pipeline.tracks[data.tracks[i].type]=data.tracks[i];pipeline.tracks[data.tracks[i].type].timelineStartInfo.baseMediaDecodeTime=options.baseMediaDecodeTime;}}
if(pipeline.tracks.video&&!pipeline.videoSegmentStream){pipeline.videoSegmentStream=new videoSegmentStream(pipeline.tracks.video,options);pipeline.videoSegmentStream.on('timelineStartInfo',function(timelineStartInfo){if(pipeline.tracks.audio&&!options.keepOriginalTimestamps){pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts-options.baseMediaDecodeTime);}});pipeline.videoSegmentStream.on('timingInfo',pipeline.trigger.bind(pipeline,'videoTimingInfo'));pipeline.videoSegmentStream.on('data',function(data){pipeline.trigger('data',{type:'video',data:data});});pipeline.videoSegmentStream.on('done',pipeline.trigger.bind(pipeline,'done'));pipeline.videoSegmentStream.on('partialdone',pipeline.trigger.bind(pipeline,'partialdone'));pipeline.videoSegmentStream.on('endedtimeline',pipeline.trigger.bind(pipeline,'endedtimeline'));pipeline.h264.pipe(pipeline.videoSegmentStream);}
if(pipeline.tracks.audio&&!pipeline.audioSegmentStream){pipeline.audioSegmentStream=new audioSegmentStream(pipeline.tracks.audio,options);pipeline.audioSegmentStream.on('data',function(data){pipeline.trigger('data',{type:'audio',data:data});});pipeline.audioSegmentStream.on('done',pipeline.trigger.bind(pipeline,'done'));pipeline.audioSegmentStream.on('partialdone',pipeline.trigger.bind(pipeline,'partialdone'));pipeline.audioSegmentStream.on('endedtimeline',pipeline.trigger.bind(pipeline,'endedtimeline'));pipeline.audioSegmentStream.on('timingInfo',pipeline.trigger.bind(pipeline,'audioTimingInfo'));pipeline.adts.pipe(pipeline.audioSegmentStream);}
pipeline.trigger('trackinfo',{hasAudio:!!pipeline.tracks.audio,hasVideo:!!pipeline.tracks.video});});pipeline.captionStream.on('data',function(caption){var timelineStartPts;if(pipeline.tracks.video){timelineStartPts=pipeline.tracks.video.timelineStartInfo.pts||0;}else{timelineStartPts=0;}
caption.startTime=clock.metadataTsToSeconds(caption.startPts,timelineStartPts,options.keepOriginalTimestamps);caption.endTime=clock.metadataTsToSeconds(caption.endPts,timelineStartPts,options.keepOriginalTimestamps);pipeline.trigger('caption',caption);});pipeline=createPipeline(pipeline);pipeline.metadataStream.on('data',pipeline.trigger.bind(pipeline,'id3Frame'));return pipeline;};var aacPipeline=function aacPipeline(options){var pipeline={type:'aac',tracks:{audio:null},metadataStream:new m2ts_1.MetadataStream(),aacStream:new aac(),audioRollover:new m2ts_1.TimestampRolloverStream('audio'),timedMetadataRollover:new m2ts_1.TimestampRolloverStream('timed-metadata'),adtsStream:new adts(true)};pipeline.headOfPipeline=pipeline.aacStream;pipeline.aacStream.pipe(pipeline.audioRollover).pipe(pipeline.adtsStream);pipeline.aacStream.pipe(pipeline.timedMetadataRollover).pipe(pipeline.metadataStream);pipeline.metadataStream.on('timestamp',function(frame){pipeline.aacStream.setTimestamp(frame.timeStamp);});pipeline.aacStream.on('data',function(data){if(data.type!=='timed-metadata'&&data.type!=='audio'||pipeline.audioSegmentStream){return;}
pipeline.tracks.audio=pipeline.tracks.audio||{timelineStartInfo:{baseMediaDecodeTime:options.baseMediaDecodeTime},codec:'adts',type:'audio'};pipeline.audioSegmentStream=new audioSegmentStream(pipeline.tracks.audio,options);pipeline.audioSegmentStream.on('data',function(data){pipeline.trigger('data',{type:'audio',data:data});});pipeline.audioSegmentStream.on('partialdone',pipeline.trigger.bind(pipeline,'partialdone'));pipeline.audioSegmentStream.on('done',pipeline.trigger.bind(pipeline,'done'));pipeline.audioSegmentStream.on('endedtimeline',pipeline.trigger.bind(pipeline,'endedtimeline'));pipeline.audioSegmentStream.on('timingInfo',pipeline.trigger.bind(pipeline,'audioTimingInfo'));pipeline.adtsStream.pipe(pipeline.audioSegmentStream);pipeline.trigger('trackinfo',{hasAudio:!!pipeline.tracks.audio,hasVideo:!!pipeline.tracks.video});});pipeline=createPipeline(pipeline);pipeline.metadataStream.on('data',pipeline.trigger.bind(pipeline,'id3Frame'));return pipeline;};var setupPipelineListeners=function setupPipelineListeners(pipeline,transmuxer){pipeline.on('data',transmuxer.trigger.bind(transmuxer,'data'));pipeline.on('done',transmuxer.trigger.bind(transmuxer,'done'));pipeline.on('partialdone',transmuxer.trigger.bind(transmuxer,'partialdone'));pipeline.on('endedtimeline',transmuxer.trigger.bind(transmuxer,'endedtimeline'));pipeline.on('audioTimingInfo',transmuxer.trigger.bind(transmuxer,'audioTimingInfo'));pipeline.on('videoTimingInfo',transmuxer.trigger.bind(transmuxer,'videoTimingInfo'));pipeline.on('trackinfo',transmuxer.trigger.bind(transmuxer,'trackinfo'));pipeline.on('id3Frame',function(event){event.dispatchType=pipeline.metadataStream.dispatchType;event.cueTime=clock.videoTsToSeconds(event.pts);transmuxer.trigger('id3Frame',event);});pipeline.on('caption',function(event){transmuxer.trigger('caption',event);});};var Transmuxer=function Transmuxer(options){var pipeline=null,hasFlushed=true;options=options||{};Transmuxer.prototype.init.call(this);options.baseMediaDecodeTime=options.baseMediaDecodeTime||0;this.push=function(bytes){if(hasFlushed){var isAac=isLikelyAacData$2(bytes);if(isAac&&(!pipeline||pipeline.type!=='aac')){pipeline=aacPipeline(options);setupPipelineListeners(pipeline,this);}else if(!isAac&&(!pipeline||pipeline.type!=='ts')){pipeline=tsPipeline(options);setupPipelineListeners(pipeline,this);}
hasFlushed=false;}
pipeline.headOfPipeline.push(bytes);};this.flush=function(){if(!pipeline){return;}
hasFlushed=true;pipeline.headOfPipeline.flush();};this.partialFlush=function(){if(!pipeline){return;}
pipeline.headOfPipeline.partialFlush();};this.endTimeline=function(){if(!pipeline){return;}
pipeline.headOfPipeline.endTimeline();};this.reset=function(){if(!pipeline){return;}
pipeline.headOfPipeline.reset();};this.setBaseMediaDecodeTime=function(baseMediaDecodeTime){if(!options.keepOriginalTimestamps){options.baseMediaDecodeTime=baseMediaDecodeTime;}
if(!pipeline){return;}
if(pipeline.tracks.audio){pipeline.tracks.audio.timelineStartInfo.dts=undefined;pipeline.tracks.audio.timelineStartInfo.pts=undefined;trackDecodeInfo.clearDtsInfo(pipeline.tracks.audio);if(pipeline.audioRollover){pipeline.audioRollover.discontinuity();}}
if(pipeline.tracks.video){if(pipeline.videoSegmentStream){pipeline.videoSegmentStream.gopCache_=[];}
pipeline.tracks.video.timelineStartInfo.dts=undefined;pipeline.tracks.video.timelineStartInfo.pts=undefined;trackDecodeInfo.clearDtsInfo(pipeline.tracks.video);}
if(pipeline.timestampRollover){pipeline.timestampRollover.discontinuity();}};this.setRemux=function(val){options.remux=val;if(pipeline&&pipeline.coalesceStream){pipeline.coalesceStream.setRemux(val);}};this.setAudioAppendStart=function(audioAppendStart){if(!pipeline||!pipeline.tracks.audio||!pipeline.audioSegmentStream){return;}
pipeline.audioSegmentStream.setAudioAppendStart(audioAppendStart);};this.alignGopsWith=function(gopsToAlignWith){return;};};Transmuxer.prototype=new stream();var transmuxer$1=Transmuxer;var toUnsigned=function toUnsigned(value){return value>>>0;};var toHexString=function toHexString(value){return('00'+value.toString(16)).slice(-2);};var bin={toUnsigned:toUnsigned,toHexString:toHexString};var parseType$1=function parseType(buffer){var result='';result+=String.fromCharCode(buffer[0]);result+=String.fromCharCode(buffer[1]);result+=String.fromCharCode(buffer[2]);result+=String.fromCharCode(buffer[3]);return result;};var parseType_1=parseType$1;var toUnsigned$1=bin.toUnsigned;var findBox=function findBox(data,path){var results=[],i,size,type,end,subresults;if(!path.length){return null;}
for(i=0;i<data.byteLength;){size=toUnsigned$1(data[i]<<24|data[i+1]<<16|data[i+2]<<8|data[i+3]);type=parseType_1(data.subarray(i+4,i+8));end=size>1?i+size:data.byteLength;if(type===path[0]){if(path.length===1){results.push(data.subarray(i+8,end));}else{subresults=findBox(data.subarray(i+8,end),path.slice(1));if(subresults.length){results=results.concat(subresults);}}}
i=end;}
return results;};var findBox_1=findBox;var toUnsigned$2=bin.toUnsigned;var tfdt=function tfdt(data){var result={version:data[0],flags:new Uint8Array(data.subarray(1,4)),baseMediaDecodeTime:toUnsigned$2(data[4]<<24|data[5]<<16|data[6]<<8|data[7])};if(result.version===1){result.baseMediaDecodeTime*=Math.pow(2,32);result.baseMediaDecodeTime+=toUnsigned$2(data[8]<<24|data[9]<<16|data[10]<<8|data[11]);}
return result;};var parseTfdt=tfdt;var parseSampleFlags=function parseSampleFlags(flags){return{isLeading:(flags[0]&0x0c)>>>2,dependsOn:flags[0]&0x03,isDependedOn:(flags[1]&0xc0)>>>6,hasRedundancy:(flags[1]&0x30)>>>4,paddingValue:(flags[1]&0x0e)>>>1,isNonSyncSample:flags[1]&0x01,degradationPriority:flags[2]<<8|flags[3]};};var parseSampleFlags_1=parseSampleFlags;var trun$1=function trun(data){var result={version:data[0],flags:new Uint8Array(data.subarray(1,4)),samples:[]},view=new DataView(data.buffer,data.byteOffset,data.byteLength),dataOffsetPresent=result.flags[2]&0x01,firstSampleFlagsPresent=result.flags[2]&0x04,sampleDurationPresent=result.flags[1]&0x01,sampleSizePresent=result.flags[1]&0x02,sampleFlagsPresent=result.flags[1]&0x04,sampleCompositionTimeOffsetPresent=result.flags[1]&0x08,sampleCount=view.getUint32(4),offset=8,sample;if(dataOffsetPresent){result.dataOffset=view.getInt32(offset);offset+=4;}
if(firstSampleFlagsPresent&&sampleCount){sample={flags:parseSampleFlags_1(data.subarray(offset,offset+4))};offset+=4;if(sampleDurationPresent){sample.duration=view.getUint32(offset);offset+=4;}
if(sampleSizePresent){sample.size=view.getUint32(offset);offset+=4;}
if(sampleCompositionTimeOffsetPresent){if(result.version===1){sample.compositionTimeOffset=view.getInt32(offset);}else{sample.compositionTimeOffset=view.getUint32(offset);}
offset+=4;}
result.samples.push(sample);sampleCount--;}
while(sampleCount--){sample={};if(sampleDurationPresent){sample.duration=view.getUint32(offset);offset+=4;}
if(sampleSizePresent){sample.size=view.getUint32(offset);offset+=4;}
if(sampleFlagsPresent){sample.flags=parseSampleFlags_1(data.subarray(offset,offset+4));offset+=4;}
if(sampleCompositionTimeOffsetPresent){if(result.version===1){sample.compositionTimeOffset=view.getInt32(offset);}else{sample.compositionTimeOffset=view.getUint32(offset);}
offset+=4;}
result.samples.push(sample);}
return result;};var parseTrun=trun$1;var tfhd=function tfhd(data){var 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=result.flags[2]&0x01,sampleDescriptionIndexPresent=result.flags[2]&0x02,defaultSampleDurationPresent=result.flags[2]&0x08,defaultSampleSizePresent=result.flags[2]&0x10,defaultSampleFlagsPresent=result.flags[2]&0x20,durationIsEmpty=result.flags[0]&0x010000,defaultBaseIsMoof=result.flags[0]&0x020000,i;i=8;if(baseDataOffsetPresent){i+=4;result.baseDataOffset=view.getUint32(12);i+=4;}
if(sampleDescriptionIndexPresent){result.sampleDescriptionIndex=view.getUint32(i);i+=4;}
if(defaultSampleDurationPresent){result.defaultSampleDuration=view.getUint32(i);i+=4;}
if(defaultSampleSizePresent){result.defaultSampleSize=view.getUint32(i);i+=4;}
if(defaultSampleFlagsPresent){result.defaultSampleFlags=view.getUint32(i);}
if(durationIsEmpty){result.durationIsEmpty=true;}
if(!baseDataOffsetPresent&&defaultBaseIsMoof){result.baseDataOffsetIsMoof=true;}
return result;};var parseTfhd=tfhd;var discardEmulationPreventionBytes$1=captionPacketParser.discardEmulationPreventionBytes;var CaptionStream$1=captionStream.CaptionStream;var mapToSample=function mapToSample(offset,samples){var approximateOffset=offset;for(var i=0;i<samples.length;i++){var sample=samples[i];if(approximateOffset<sample.size){return sample;}
approximateOffset-=sample.size;}
return null;};var findSeiNals=function findSeiNals(avcStream,samples,trackId){var avcView=new DataView(avcStream.buffer,avcStream.byteOffset,avcStream.byteLength),result=[],seiNal,i,length,lastMatchedSample;for(i=0;i+4<avcStream.length;i+=length){length=avcView.getUint32(i);i+=4;if(length<=0){continue;}
switch(avcStream[i]&0x1F){case 0x06:var data=avcStream.subarray(i+1,i+1+length);var matchingSample=mapToSample(i,samples);seiNal={nalUnitType:'sei_rbsp',size:length,data:data,escapedRBSP:discardEmulationPreventionBytes$1(data),trackId:trackId};if(matchingSample){seiNal.pts=matchingSample.pts;seiNal.dts=matchingSample.dts;lastMatchedSample=matchingSample;}else if(lastMatchedSample){seiNal.pts=lastMatchedSample.pts;seiNal.dts=lastMatchedSample.dts;}else{console.log("We've encountered a nal unit without data. See mux.js#233.");break;}
result.push(seiNal);break;}}
return result;};var parseSamples=function parseSamples(truns,baseMediaDecodeTime,tfhd){var currentDts=baseMediaDecodeTime;var defaultSampleDuration=tfhd.defaultSampleDuration||0;var defaultSampleSize=tfhd.defaultSampleSize||0;var trackId=tfhd.trackId;var allSamples=[];truns.forEach(function(trun){var trackRun=parseTrun(trun);var samples=trackRun.samples;samples.forEach(function(sample){if(sample.duration===undefined){sample.duration=defaultSampleDuration;}
if(sample.size===undefined){sample.size=defaultSampleSize;}
sample.trackId=trackId;sample.dts=currentDts;if(sample.compositionTimeOffset===undefined){sample.compositionTimeOffset=0;}
sample.pts=currentDts+sample.compositionTimeOffset;currentDts+=sample.duration;});allSamples=allSamples.concat(samples);});return allSamples;};var parseCaptionNals=function parseCaptionNals(segment,videoTrackId){var trafs=findBox_1(segment,['moof','traf']);var mdats=findBox_1(segment,['mdat']);var captionNals={};var mdatTrafPairs=[];mdats.forEach(function(mdat,index){var matchingTraf=trafs[index];mdatTrafPairs.push({mdat:mdat,traf:matchingTraf});});mdatTrafPairs.forEach(function(pair){var mdat=pair.mdat;var traf=pair.traf;var tfhd=findBox_1(traf,['tfhd']);var headerInfo=parseTfhd(tfhd[0]);var trackId=headerInfo.trackId;var tfdt=findBox_1(traf,['tfdt']);var baseMediaDecodeTime=tfdt.length>0?parseTfdt(tfdt[0]).baseMediaDecodeTime:0;var truns=findBox_1(traf,['trun']);var samples;var seiNals;if(videoTrackId===trackId&&truns.length>0){samples=parseSamples(truns,baseMediaDecodeTime,headerInfo);seiNals=findSeiNals(mdat,samples,trackId);if(!captionNals[trackId]){captionNals[trackId]=[];}
captionNals[trackId]=captionNals[trackId].concat(seiNals);}});return captionNals;};var parseEmbeddedCaptions=function parseEmbeddedCaptions(segment,trackId,timescale){var seiNals;if(trackId===null){return null;}
seiNals=parseCaptionNals(segment,trackId);return{seiNals:seiNals[trackId],timescale:timescale};};var CaptionParser=function CaptionParser(){var isInitialized=false;var captionStream;var segmentCache;var trackId;var timescale;var parsedCaptions;var parsingPartial;this.isInitialized=function(){return isInitialized;};this.init=function(options){captionStream=new CaptionStream$1();isInitialized=true;parsingPartial=options?options.isPartial:false;captionStream.on('data',function(event){event.startTime=event.startPts/timescale;event.endTime=event.endPts/timescale;parsedCaptions.captions.push(event);parsedCaptions.captionStreams[event.stream]=true;});};this.isNewInit=function(videoTrackIds,timescales){if(videoTrackIds&&videoTrackIds.length===0||timescales&&typeof timescales==='object'&&Object.keys(timescales).length===0){return false;}
return trackId!==videoTrackIds[0]||timescale!==timescales[trackId];};this.parse=function(segment,videoTrackIds,timescales){var parsedData;if(!this.isInitialized()){return null;}else if(!videoTrackIds||!timescales){return null;}else if(this.isNewInit(videoTrackIds,timescales)){trackId=videoTrackIds[0];timescale=timescales[trackId];}else if(trackId===null||!timescale){segmentCache.push(segment);return null;}
while(segmentCache.length>0){var cachedSegment=segmentCache.shift();this.parse(cachedSegment,videoTrackIds,timescales);}
parsedData=parseEmbeddedCaptions(segment,trackId,timescale);if(parsedData===null||!parsedData.seiNals){return null;}
this.pushNals(parsedData.seiNals);this.flushStream();return parsedCaptions;};this.pushNals=function(nals){if(!this.isInitialized()||!nals||nals.length===0){return null;}
nals.forEach(function(nal){captionStream.push(nal);});};this.flushStream=function(){if(!this.isInitialized()){return null;}
if(!parsingPartial){captionStream.flush();}else{captionStream.partialFlush();}};this.clearParsedCaptions=function(){parsedCaptions.captions=[];parsedCaptions.captionStreams={};};this.resetCaptionStream=function(){if(!this.isInitialized()){return null;}
captionStream.reset();};this.clearAllCaptions=function(){this.clearParsedCaptions();this.resetCaptionStream();};this.reset=function(){segmentCache=[];trackId=null;timescale=null;if(!parsedCaptions){parsedCaptions={captions:[],captionStreams:{}};}else{this.clearParsedCaptions();}
this.resetCaptionStream();};this.reset();};var captionParser=CaptionParser;var typeFromStreamString=function typeFromStreamString(streamString){if(streamString==='AudioSegmentStream'){return'audio';}
return streamString==='VideoSegmentStream'?'video':'';};var wireFullTransmuxerEvents=function wireFullTransmuxerEvents(self,transmuxer){transmuxer.on('data',function(segment){var initArray=segment.initSegment;segment.initSegment={data:initArray.buffer,byteOffset:initArray.byteOffset,byteLength:initArray.byteLength};var 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',function(gopInfo){self.postMessage({action:'gopInfo',gopInfo:gopInfo});});transmuxer.on('videoSegmentTimingInfo',function(timingInfo){var videoSegmentTimingInfo={start:{decode:clock.videoTsToSeconds(timingInfo.start.dts),presentation:clock.videoTsToSeconds(timingInfo.start.pts)},end:{decode:clock.videoTsToSeconds(timingInfo.end.dts),presentation:clock.videoTsToSeconds(timingInfo.end.pts)},baseMediaDecodeTime:clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)};if(timingInfo.prependedContentDuration){videoSegmentTimingInfo.prependedContentDuration=clock.videoTsToSeconds(timingInfo.prependedContentDuration);}
self.postMessage({action:'videoSegmentTimingInfo',videoSegmentTimingInfo:videoSegmentTimingInfo});});transmuxer.on('audioSegmentTimingInfo',function(timingInfo){var audioSegmentTimingInfo={start:{decode:clock.videoTsToSeconds(timingInfo.start.dts),presentation:clock.videoTsToSeconds(timingInfo.start.pts)},end:{decode:clock.videoTsToSeconds(timingInfo.end.dts),presentation:clock.videoTsToSeconds(timingInfo.end.pts)},baseMediaDecodeTime:clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)};if(timingInfo.prependedContentDuration){audioSegmentTimingInfo.prependedContentDuration=clock.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.videoTsToSeconds(audioTimingInfo.start),end:clock.videoTsToSeconds(audioTimingInfo.end)}});});transmuxer.on('videoTimingInfo',function(videoTimingInfo){self.postMessage({action:'videoTimingInfo',videoTimingInfo:{start:clock.videoTsToSeconds(videoTimingInfo.start),end:clock.videoTsToSeconds(videoTimingInfo.end)}});});};var wirePartialTransmuxerEvents=function wirePartialTransmuxerEvents(self,transmuxer){transmuxer.on('data',function(event){var initSegment={data:event.data.track.initSegment.buffer,byteOffset:event.data.track.initSegment.byteOffset,byteLength:event.data.track.initSegment.byteLength};var boxes={data:event.data.boxes.buffer,byteOffset:event.data.boxes.byteOffset,byteLength:event.data.boxes.byteLength};var segment={boxes:boxes,initSegment:initSegment,type:event.type,sequence:event.data.sequence};if(typeof event.data.videoFrameDts!=='undefined'){segment.videoFrameDtsTime=clock.videoTsToSeconds(event.data.videoFrameDts);}
if(typeof event.data.videoFramePts!=='undefined'){segment.videoFramePtsTime=clock.videoTsToSeconds(event.data.videoFramePts);}
self.postMessage({action:'data',segment:segment},[segment.boxes.data,segment.initSegment.data]);});transmuxer.on('id3Frame',function(id3Frame){self.postMessage({action:'id3Frame',id3Frame:id3Frame});});transmuxer.on('caption',function(caption){self.postMessage({action:'caption',caption:caption});});transmuxer.on('done',function(data){self.postMessage({action:'done',type:typeFromStreamString(data)});});transmuxer.on('partialdone',function(data){self.postMessage({action:'partialdone',type:typeFromStreamString(data)});});transmuxer.on('endedsegment',function(data){self.postMessage({action:'endedSegment',type:typeFromStreamString(data)});});transmuxer.on('trackinfo',function(trackInfo){self.postMessage({action:'trackinfo',trackInfo:trackInfo});});transmuxer.on('audioTimingInfo',function(audioTimingInfo){if(audioTimingInfo.start===null){self.postMessage({action:'audioTimingInfo',audioTimingInfo:audioTimingInfo});return;}
var timingInfoInSeconds={start:clock.videoTsToSeconds(audioTimingInfo.start)};if(audioTimingInfo.end){timingInfoInSeconds.end=clock.videoTsToSeconds(audioTimingInfo.end);}
self.postMessage({action:'audioTimingInfo',audioTimingInfo:timingInfoInSeconds});});transmuxer.on('videoTimingInfo',function(videoTimingInfo){var timingInfoInSeconds={start:clock.videoTsToSeconds(videoTimingInfo.start)};if(videoTimingInfo.end){timingInfoInSeconds.end=clock.videoTsToSeconds(videoTimingInfo.end);}
self.postMessage({action:'videoTimingInfo',videoTimingInfo:timingInfoInSeconds});});};var MessageHandlers=function(){function MessageHandlers(self,options){this.options=options||{};this.self=self;this.init();}
var _proto=MessageHandlers.prototype;_proto.init=function init(){if(this.transmuxer){this.transmuxer.dispose();}
this.transmuxer=this.options.handlePartialData?new transmuxer$1(this.options):new transmuxer.Transmuxer(this.options);if(this.options.handlePartialData){wirePartialTransmuxerEvents(this.self,this.transmuxer);}else{wireFullTransmuxerEvents(this.self,this.transmuxer);}};_proto.pushMp4Captions=function pushMp4Captions(data){if(!this.captionParser){this.captionParser=new captionParser();this.captionParser.init();}
var segment=new Uint8Array(data.data,data.byteOffset,data.byteLength);var parsed=this.captionParser.parse(segment,data.trackIds,data.timescales);this.self.postMessage({action:'mp4Captions',captions:parsed&&parsed.captions||[],data:segment.buffer},[segment.buffer]);};_proto.clearAllMp4Captions=function clearAllMp4Captions(){if(this.captionParser){this.captionParser.clearAllCaptions();}};_proto.clearParsedMp4Captions=function clearParsedMp4Captions(){if(this.captionParser){this.captionParser.clearParsedCaptions();}};_proto.push=function push(data){var segment=new Uint8Array(data.data,data.byteOffset,data.byteLength);this.transmuxer.push(segment);};_proto.reset=function reset(){this.transmuxer.reset();};_proto.setTimestampOffset=function setTimestampOffset(data){var timestampOffset=data.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(clock.secondsToVideoTs(timestampOffset)));};_proto.setAudioAppendStart=function setAudioAppendStart(data){this.transmuxer.setAudioAppendStart(Math.ceil(clock.secondsToVideoTs(data.appendStart)));};_proto.setRemux=function setRemux(data){this.transmuxer.setRemux(data.remux);};_proto.flush=function flush(data){this.transmuxer.flush();self.postMessage({action:'done',type:'transmuxed'});};_proto.partialFlush=function partialFlush(data){this.transmuxer.partialFlush();self.postMessage({action:'partialdone',type:'transmuxed'});};_proto.endTimeline=function endTimeline(){this.transmuxer.endTimeline();self.postMessage({action:'endedtimeline',type:'transmuxed'});};_proto.alignGopsWith=function alignGopsWith(data){this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());};return MessageHandlers;}();var TransmuxerWorker=function TransmuxerWorker(self){self.onmessage=function(event){if(event.data.action==='init'&&event.data.options){this.messageHandlers=new MessageHandlers(self,event.data.options);return;}
if(!this.messageHandlers){this.messageHandlers=new MessageHandlers(self);}
if(event.data&&event.data.action&&event.data.action!=='init'){if(this.messageHandlers[event.data.action]){this.messageHandlers[event.data.action](event.data);}}};};var transmuxerWorker=new TransmuxerWorker(self);return transmuxerWorker;}();});var getCodecs=function getCodecs(media){var mediaAttributes=media.attributes||{};if(mediaAttributes.CODECS){return codecs_11(mediaAttributes.CODECS);}};var isMaat=function isMaat(master,media){var mediaAttributes=media.attributes||{};return master&&master.mediaGroups&&master.mediaGroups.AUDIO&&mediaAttributes.AUDIO&&master.mediaGroups.AUDIO[mediaAttributes.AUDIO];};var isMuxed=function isMuxed(master,media){if(!isMaat(master,media)){return true;}
var mediaAttributes=media.attributes||{};var audioGroup=master.mediaGroups.AUDIO[mediaAttributes.AUDIO];for(var groupId in audioGroup){if(!audioGroup[groupId].uri&&!audioGroup[groupId].playlists){return true;}}
return false;};var codecsForPlaylist=function codecsForPlaylist(master,media){var mediaAttributes=media.attributes||{};var codecInfo=getCodecs(media)||{};if(isMaat(master,media)&&!codecInfo.audio){if(!isMuxed(master,media)){var defaultCodecs=codecs_4(master,mediaAttributes.AUDIO);if(defaultCodecs){codecInfo.audio=defaultCodecs.audio;}}}
var codecs={};if(codecInfo.video){codecs.video=codecs_12(""+codecInfo.video.type+codecInfo.video.details);}
if(codecInfo.audio){codecs.audio=codecs_12(""+codecInfo.audio.type+codecInfo.audio.details);}
if(codecInfo.text){codecs.text=codecInfo.text.type;}
if(codecInfo.unknown){codecs.unknown=codecInfo.unknown;}
return codecs;};var logger=function logger(source){if(videojs$1.log.debug){return videojs$1.log.debug.bind(videojs$1,'VHS:',source+" >");}
return function(){};};var logFn=logger('PlaylistSelector');var representationToString=function representationToString(representation){if(!representation||!representation.playlist){return;}
var playlist=representation.playlist;return JSON.stringify({id:playlist.id,bandwidth:representation.bandwidth,width:representation.width,height:representation.height,codecs:playlist.attributes&&playlist.attributes.CODECS||''});};var safeGetComputedStyle=function safeGetComputedStyle(el,property){if(!el){return'';}
var result=window_1$2.getComputedStyle(el);if(!result){return'';}
return result[property];};var stableSort=function stableSort(array,sortFn){var newArray=array.slice();array.sort(function(left,right){var cmp=sortFn(left,right);if(cmp===0){return newArray.indexOf(left)-newArray.indexOf(right);}
return cmp;});};var comparePlaylistBandwidth=function comparePlaylistBandwidth(left,right){var leftBandwidth;var rightBandwidth;if(left.attributes.BANDWIDTH){leftBandwidth=left.attributes.BANDWIDTH;}
leftBandwidth=leftBandwidth||window_1$2.Number.MAX_VALUE;if(right.attributes.BANDWIDTH){rightBandwidth=right.attributes.BANDWIDTH;}
rightBandwidth=rightBandwidth||window_1$2.Number.MAX_VALUE;return leftBandwidth-rightBandwidth;};var comparePlaylistResolution=function comparePlaylistResolution(left,right){var leftWidth;var rightWidth;if(left.attributes.RESOLUTION&&left.attributes.RESOLUTION.width){leftWidth=left.attributes.RESOLUTION.width;}
leftWidth=leftWidth||window_1$2.Number.MAX_VALUE;if(right.attributes.RESOLUTION&&right.attributes.RESOLUTION.width){rightWidth=right.attributes.RESOLUTION.width;}
rightWidth=rightWidth||window_1$2.Number.MAX_VALUE;if(leftWidth===rightWidth&&left.attributes.BANDWIDTH&&right.attributes.BANDWIDTH){return left.attributes.BANDWIDTH-right.attributes.BANDWIDTH;}
return leftWidth-rightWidth;};var simpleSelector=function simpleSelector(master,playerBandwidth,playerWidth,playerHeight,limitRenditionByPlayerDimensions){if(!master){return;}
var options={bandwidth:playerBandwidth,width:playerWidth,height:playerHeight,limitRenditionByPlayerDimensions:limitRenditionByPlayerDimensions};var sortedPlaylistReps=master.playlists.map(function(playlist){var bandwidth;var width=playlist.attributes.RESOLUTION&&playlist.attributes.RESOLUTION.width;var height=playlist.attributes.RESOLUTION&&playlist.attributes.RESOLUTION.height;bandwidth=playlist.attributes.BANDWIDTH;bandwidth=bandwidth||window_1$2.Number.MAX_VALUE;return{bandwidth:bandwidth,width:width,height:height,playlist:playlist};});stableSort(sortedPlaylistReps,function(left,right){return left.bandwidth-right.bandwidth;});sortedPlaylistReps=sortedPlaylistReps.filter(function(rep){return!Playlist.isIncompatible(rep.playlist);});var enabledPlaylistReps=sortedPlaylistReps.filter(function(rep){return Playlist.isEnabled(rep.playlist);});if(!enabledPlaylistReps.length){enabledPlaylistReps=sortedPlaylistReps.filter(function(rep){return!Playlist.isDisabled(rep.playlist);});}
var bandwidthPlaylistReps=enabledPlaylistReps.filter(function(rep){return rep.bandwidth*Config.BANDWIDTH_VARIANCE<playerBandwidth;});var highestRemainingBandwidthRep=bandwidthPlaylistReps[bandwidthPlaylistReps.length-1];var bandwidthBestRep=bandwidthPlaylistReps.filter(function(rep){return rep.bandwidth===highestRemainingBandwidthRep.bandwidth;})[0];if(limitRenditionByPlayerDimensions===false){var _chosenRep=bandwidthBestRep||enabledPlaylistReps[0]||sortedPlaylistReps[0];if(_chosenRep&&_chosenRep.playlist){var type='sortedPlaylistReps';if(bandwidthBestRep){type='bandwidthBestRep';}
if(enabledPlaylistReps[0]){type='enabledPlaylistReps';}
logFn("choosing "+representationToString(_chosenRep)+" using "+type+" with options",options);return _chosenRep.playlist;}
logFn('could not choose a playlist with options',options);return null;}
var haveResolution=bandwidthPlaylistReps.filter(function(rep){return rep.width&&rep.height;});stableSort(haveResolution,function(left,right){return left.width-right.width;});var resolutionBestRepList=haveResolution.filter(function(rep){return rep.width===playerWidth&&rep.height===playerHeight;});highestRemainingBandwidthRep=resolutionBestRepList[resolutionBestRepList.length-1];var resolutionBestRep=resolutionBestRepList.filter(function(rep){return rep.bandwidth===highestRemainingBandwidthRep.bandwidth;})[0];var resolutionPlusOneList;var resolutionPlusOneSmallest;var resolutionPlusOneRep;if(!resolutionBestRep){resolutionPlusOneList=haveResolution.filter(function(rep){return rep.width>playerWidth||rep.height>playerHeight;});resolutionPlusOneSmallest=resolutionPlusOneList.filter(function(rep){return rep.width===resolutionPlusOneList[0].width&&rep.height===resolutionPlusOneList[0].height;});highestRemainingBandwidthRep=resolutionPlusOneSmallest[resolutionPlusOneSmallest.length-1];resolutionPlusOneRep=resolutionPlusOneSmallest.filter(function(rep){return rep.bandwidth===highestRemainingBandwidthRep.bandwidth;})[0];}
var chosenRep=resolutionPlusOneRep||resolutionBestRep||bandwidthBestRep||enabledPlaylistReps[0]||sortedPlaylistReps[0];if(chosenRep&&chosenRep.playlist){var _type='sortedPlaylistReps';if(resolutionPlusOneRep){_type='resolutionPlusOneRep';}else if(resolutionBestRep){_type='resolutionBestRep';}else if(bandwidthBestRep){_type='bandwidthBestRep';}else if(enabledPlaylistReps[0]){_type='enabledPlaylistReps';}
logFn("choosing "+representationToString(chosenRep)+" using "+_type+" with options",options);return chosenRep.playlist;}
logFn('could not choose a playlist with options',options);return null;};var lastBandwidthSelector=function lastBandwidthSelector(){var pixelRatio=this.useDevicePixelRatio?window_1$2.devicePixelRatio||1:1;return simpleSelector(this.playlists.master,this.systemBandwidth,parseInt(safeGetComputedStyle(this.tech_.el(),'width'),10)*pixelRatio,parseInt(safeGetComputedStyle(this.tech_.el(),'height'),10)*pixelRatio,this.limitRenditionByPlayerDimensions);};var movingAverageBandwidthSelector=function movingAverageBandwidthSelector(decay){var average=-1;if(decay<0||decay>1){throw new Error('Moving average bandwidth decay must be between 0 and 1.');}
return function(){var pixelRatio=this.useDevicePixelRatio?window_1$2.devicePixelRatio||1:1;if(average<0){average=this.systemBandwidth;}
average=decay*this.systemBandwidth+(1-decay)*average;return simpleSelector(this.playlists.master,average,parseInt(safeGetComputedStyle(this.tech_.el(),'width'),10)*pixelRatio,parseInt(safeGetComputedStyle(this.tech_.el(),'height'),10)*pixelRatio,this.limitRenditionByPlayerDimensions);};};var minRebufferMaxBandwidthSelector=function minRebufferMaxBandwidthSelector(settings){var master=settings.master,currentTime=settings.currentTime,bandwidth=settings.bandwidth,duration=settings.duration,segmentDuration=settings.segmentDuration,timeUntilRebuffer=settings.timeUntilRebuffer,currentTimeline=settings.currentTimeline,syncController=settings.syncController;var compatiblePlaylists=master.playlists.filter(function(playlist){return!Playlist.isIncompatible(playlist);});var enabledPlaylists=compatiblePlaylists.filter(Playlist.isEnabled);if(!enabledPlaylists.length){enabledPlaylists=compatiblePlaylists.filter(function(playlist){return!Playlist.isDisabled(playlist);});}
var bandwidthPlaylists=enabledPlaylists.filter(Playlist.hasAttribute.bind(null,'BANDWIDTH'));var rebufferingEstimates=bandwidthPlaylists.map(function(playlist){var syncPoint=syncController.getSyncPoint(playlist,duration,currentTimeline,currentTime);var numRequests=syncPoint?1:2;var requestTimeEstimate=Playlist.estimateSegmentRequestTime(segmentDuration,bandwidth,playlist);var rebufferingImpact=requestTimeEstimate*numRequests-timeUntilRebuffer;return{playlist:playlist,rebufferingImpact:rebufferingImpact};});var noRebufferingPlaylists=rebufferingEstimates.filter(function(estimate){return estimate.rebufferingImpact<=0;});stableSort(noRebufferingPlaylists,function(a,b){return comparePlaylistBandwidth(b.playlist,a.playlist);});if(noRebufferingPlaylists.length){return noRebufferingPlaylists[0];}
stableSort(rebufferingEstimates,function(a,b){return a.rebufferingImpact-b.rebufferingImpact;});return rebufferingEstimates[0]||null;};var lowestBitrateCompatibleVariantSelector=function lowestBitrateCompatibleVariantSelector(){var _this=this;var playlists=this.playlists.master.playlists.filter(Playlist.isEnabled);stableSort(playlists,function(a,b){return comparePlaylistBandwidth(a,b);});var playlistsWithVideo=playlists.filter(function(playlist){return!!codecsForPlaylist(_this.playlists.master,playlist).video;});return playlistsWithVideo[0]||null;};var createCaptionsTrackIfNotExists=function createCaptionsTrackIfNotExists(inbandTextTracks,tech,captionStream){if(!inbandTextTracks[captionStream]){tech.trigger({type:'usage',name:'vhs-608'});tech.trigger({type:'usage',name:'hls-608'});var track=tech.textTracks().getTrackById(captionStream);if(track){inbandTextTracks[captionStream]=track;}else{inbandTextTracks[captionStream]=tech.addRemoteTextTrack({kind:'captions',id:captionStream,label:captionStream},false).track;}}};var addCaptionData=function addCaptionData(_ref){var inbandTextTracks=_ref.inbandTextTracks,captionArray=_ref.captionArray,timestampOffset=_ref.timestampOffset;if(!captionArray){return;}
var Cue=window_1$2.WebKitDataCue||window_1$2.VTTCue;captionArray.forEach(function(caption){var track=caption.stream;inbandTextTracks[track].addCue(new Cue(caption.startTime+timestampOffset,caption.endTime+timestampOffset,caption.text));});};var deprecateOldCue=function deprecateOldCue(cue){Object.defineProperties(cue.frame,{id:{get:function get(){videojs$1.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');return cue.value.key;}},value:{get:function get(){videojs$1.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');return cue.value.data;}},privateData:{get:function get(){videojs$1.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');return cue.value.data;}}});};var addMetadata=function addMetadata(_ref2){var inbandTextTracks=_ref2.inbandTextTracks,metadataArray=_ref2.metadataArray,timestampOffset=_ref2.timestampOffset,videoDuration=_ref2.videoDuration;if(!metadataArray){return;}
var Cue=window_1$2.WebKitDataCue||window_1$2.VTTCue;var metadataTrack=inbandTextTracks.metadataTrack_;if(!metadataTrack){return;}
metadataArray.forEach(function(metadata){var time=metadata.cueTime+timestampOffset;if(typeof time!=='number'||window_1$2.isNaN(time)||time<0||!(time<Infinity)){return;}
metadata.frames.forEach(function(frame){var cue=new Cue(time,time,frame.value||frame.url||frame.data||'');cue.frame=frame;cue.value=frame;deprecateOldCue(cue);metadataTrack.addCue(cue);});});if(!metadataTrack.cues||!metadataTrack.cues.length){return;}
var cues=metadataTrack.cues;var cuesArray=[];for(var i=0;i<cues.length;i++){if(cues[i]){cuesArray.push(cues[i]);}}
var cuesGroupedByStartTime=cuesArray.reduce(function(obj,cue){var timeSlot=obj[cue.startTime]||[];timeSlot.push(cue);obj[cue.startTime]=timeSlot;return obj;},{});var sortedStartTimes=Object.keys(cuesGroupedByStartTime).sort(function(a,b){return Number(a)-Number(b);});sortedStartTimes.forEach(function(startTime,idx){var cueGroup=cuesGroupedByStartTime[startTime];var nextTime=Number(sortedStartTimes[idx+1])||videoDuration;cueGroup.forEach(function(cue){cue.endTime=nextTime;});});};var createMetadataTrackIfNotExists=function createMetadataTrackIfNotExists(inbandTextTracks,dispatchType,tech){if(inbandTextTracks.metadataTrack_){return;}
inbandTextTracks.metadataTrack_=tech.addRemoteTextTrack({kind:'metadata',label:'Timed Metadata'},false).track;inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType=dispatchType;};var removeCuesFromTrack=function removeCuesFromTrack(start,end,track){var i;var cue;if(!track){return;}
if(!track.cues){return;}
i=track.cues.length;while(i--){cue=track.cues[i];if(cue.startTime>=start&&cue.endTime<=end){track.removeCue(cue);}}};var removeDuplicateCuesFromTrack=function removeDuplicateCuesFromTrack(track){var cues=track.cues;if(!cues){return;}
for(var i=0;i<cues.length;i++){var duplicates=[];var occurrences=0;for(var j=0;j<cues.length;j++){if(cues[i].startTime===cues[j].startTime&&cues[i].endTime===cues[j].endTime&&cues[i].text===cues[j].text){occurrences++;if(occurrences>1){duplicates.push(cues[j]);}}}
if(duplicates.length){duplicates.forEach(function(dupe){return track.removeCue(dupe);});}}};var gopsSafeToAlignWith=function gopsSafeToAlignWith(buffer,currentTime,mapping){if(typeof currentTime==='undefined'||currentTime===null||!buffer.length){return[];}
var currentTimePts=Math.ceil((currentTime-mapping+3)*clock_1);var i;for(i=0;i<buffer.length;i++){if(buffer[i].pts>currentTimePts){break;}}
return buffer.slice(i);};var updateGopBuffer=function updateGopBuffer(buffer,gops,replace){if(!gops.length){return buffer;}
if(replace){return gops.slice();}
var start=gops[0].pts;var i=0;for(i;i<buffer.length;i++){if(buffer[i].pts>=start){break;}}
return buffer.slice(0,i).concat(gops);};var removeGopBuffer=function removeGopBuffer(buffer,start,end,mapping){var startPts=Math.ceil((start-mapping)*clock_1);var endPts=Math.ceil((end-mapping)*clock_1);var updatedBuffer=buffer.slice();var i=buffer.length;while(i--){if(buffer[i].pts<=endPts){break;}}
if(i===-1){return updatedBuffer;}
var j=i+1;while(j--){if(buffer[j].pts<=startPts){break;}}
j=Math.max(j,0);updatedBuffer.splice(j,i-j+1);return updatedBuffer;};var shallowEqual=function shallowEqual(a,b){if(!a&&!b||!a&&b||a&&!b){return false;}
if(a===b){return true;}
var akeys=Object.keys(a).sort();var bkeys=Object.keys(b).sort();if(akeys.length!==bkeys.length){return false;}
for(var i=0;i<akeys.length;i++){var key=akeys[i];if(key!==bkeys[i]){return false;}
if(a[key]!==b[key]){return false;}}
return true;};var CHECK_BUFFER_DELAY=500;var finite=function finite(num){return typeof num==='number'&&isFinite(num);};var MIN_SEGMENT_DURATION_TO_SAVE_STATS=1/60;var illegalMediaSwitch=function illegalMediaSwitch(loaderType,startingMedia,trackInfo){if(loaderType!=='main'||!startingMedia||!trackInfo){return null;}
if(!trackInfo.hasAudio&&!trackInfo.hasVideo){return'Neither audio nor video found in segment.';}
if(startingMedia.hasVideo&&!trackInfo.hasVideo){return'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.';}
if(!startingMedia.hasVideo&&trackInfo.hasVideo){return'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.';}
return null;};var safeBackBufferTrimTime=function safeBackBufferTrimTime(seekable,currentTime,targetDuration){var trimTime=currentTime-Config.BACK_BUFFER_LENGTH;if(seekable.length){trimTime=Math.max(trimTime,seekable.start(0));}
var maxTrimTime=currentTime-targetDuration;return Math.min(maxTrimTime,trimTime);};var segmentInfoString=function segmentInfoString(segmentInfo){var _segmentInfo$segment=segmentInfo.segment,start=_segmentInfo$segment.start,end=_segmentInfo$segment.end,_segmentInfo$playlist=segmentInfo.playlist,seq=_segmentInfo$playlist.mediaSequence,id=_segmentInfo$playlist.id,_segmentInfo$playlist2=_segmentInfo$playlist.segments,segments=_segmentInfo$playlist2===void 0?[]:_segmentInfo$playlist2,index=segmentInfo.mediaIndex,timeline=segmentInfo.timeline;return["appending ["+index+"] of ["+seq+", "+(seq+segments.length)+"] from playlist ["+id+"]","["+start+" => "+end+"] in timeline ["+timeline+"]"].join(' ');};var timingInfoPropertyForMedia=function timingInfoPropertyForMedia(mediaType){return mediaType+"TimingInfo";};var timestampOffsetForSegment=function timestampOffsetForSegment(_ref){var segmentTimeline=_ref.segmentTimeline,currentTimeline=_ref.currentTimeline,startOfSegment=_ref.startOfSegment,buffered=_ref.buffered,overrideCheck=_ref.overrideCheck;if(!overrideCheck&&segmentTimeline===currentTimeline){return null;}
if(segmentTimeline<currentTimeline){return startOfSegment;}
return buffered.length?buffered.end(buffered.length-1):startOfSegment;};var shouldWaitForTimelineChange=function shouldWaitForTimelineChange(_ref2){var timelineChangeController=_ref2.timelineChangeController,currentTimeline=_ref2.currentTimeline,segmentTimeline=_ref2.segmentTimeline,loaderType=_ref2.loaderType,audioDisabled=_ref2.audioDisabled;if(currentTimeline===segmentTimeline){return false;}
if(loaderType==='audio'){var lastMainTimelineChange=timelineChangeController.lastTimelineChange({type:'main'});return!lastMainTimelineChange||lastMainTimelineChange.to!==segmentTimeline;}
if(loaderType==='main'&&audioDisabled){var pendingAudioTimelineChange=timelineChangeController.pendingTimelineChange({type:'audio'});if(pendingAudioTimelineChange&&pendingAudioTimelineChange.to===segmentTimeline){return false;}
return true;}
return false;};var mediaDuration=function mediaDuration(audioTimingInfo,videoTimingInfo){var audioDuration=audioTimingInfo&&typeof audioTimingInfo.start==='number'&&typeof audioTimingInfo.end==='number'?audioTimingInfo.end-audioTimingInfo.start:0;var videoDuration=videoTimingInfo&&typeof videoTimingInfo.start==='number'&&typeof videoTimingInfo.end==='number'?videoTimingInfo.end-videoTimingInfo.start:0;return Math.max(audioDuration,videoDuration);};var segmentTooLong=function segmentTooLong(_ref3){var segmentDuration=_ref3.segmentDuration,maxDuration=_ref3.maxDuration;if(!segmentDuration){return false;}
return Math.round(segmentDuration)>maxDuration+TIME_FUDGE_FACTOR;};var getTroublesomeSegmentDurationMessage=function getTroublesomeSegmentDurationMessage(segmentInfo,sourceType){if(sourceType!=='hls'){return null;}
var segmentDuration=mediaDuration(segmentInfo.audioTimingInfo,segmentInfo.videoTimingInfo);if(!segmentDuration){return null;}
var targetDuration=segmentInfo.playlist.targetDuration;var isSegmentWayTooLong=segmentTooLong({segmentDuration:segmentDuration,maxDuration:targetDuration*2});var isSegmentSlightlyTooLong=segmentTooLong({segmentDuration:segmentDuration,maxDuration:targetDuration});var segmentTooLongMessage="Segment with index "+segmentInfo.mediaIndex+" "+("from playlist "+segmentInfo.playlist.id+" ")+("has a duration of "+segmentDuration+" ")+("when the reported duration is "+segmentInfo.duration+" ")+("and the target duration is "+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';if(isSegmentWayTooLong||isSegmentSlightlyTooLong){return{severity:isSegmentWayTooLong?'warn':'info',message:segmentTooLongMessage};}
return null;};var SegmentLoader=function(_videojs$EventTarget){inheritsLoose$1(SegmentLoader,_videojs$EventTarget);function SegmentLoader(settings,options){var _this;_this=_videojs$EventTarget.call(this)||this;if(!settings){throw new TypeError('Initialization settings are required');}
if(typeof settings.currentTime!=='function'){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.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.handlePartialData_=settings.handlePartialData;_this.timelineChangeController_=settings.timelineChangeController;_this.shouldSaveSegmentTimingInfo_=true;_this.checkBufferTimeout_=null;_this.error_=void 0;_this.currentTimeline_=-1;_this.pendingSegment_=null;_this.xhrOptions_=null;_this.pendingSegments_=[];_this.audioDisabled_=false;_this.isPendingTimestampOffset_=false;_this.gopBuffer_=[];_this.timeMapping_=0;_this.safeAppend_=videojs$1.browser.IE_VERSION>=11;_this.appendInitSegment_={audio:true,video:true};_this.playlistOfLastInitSegment_={audio:null,video:null};_this.callQueue_=[];_this.loadQueue_=[];_this.metadataQueue_={id3:[],caption:[]};_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_=function(){return _this.trigger('syncinfoupdate');};_this.syncController_.on('syncinfoupdate',_this.triggerSyncInfoUpdate_);_this.mediaSource_.addEventListener('sourceopen',function(){if(!_this.isEndOfStream_()){_this.ended_=false;}});_this.fetchAtBuffer_=false;_this.logger_=logger("SegmentLoader["+_this.loaderType_+"]");Object.defineProperty(assertThisInitialized$1(_this),'state',{get:function get(){return this.state_;},set:function set(newState){if(newState!==this.state_){this.logger_(this.state_+" -> "+newState);this.state_=newState;this.trigger('statechange');}}});_this.sourceUpdater_.on('ready',function(){if(_this.hasEnoughInfoToAppend_()){_this.processCallQueue_();}});if(_this.loaderType_==='main'){_this.timelineChangeController_.on('pendingtimelinechange',function(){if(_this.hasEnoughInfoToAppend_()){_this.processCallQueue_();}});}
if(_this.loaderType_==='audio'){_this.timelineChangeController_.on('timelinechange',function(){if(_this.hasEnoughInfoToLoad_()){_this.processLoadQueue_();}
if(_this.hasEnoughInfoToAppend_()){_this.processCallQueue_();}});}
return _this;}
var _proto=SegmentLoader.prototype;_proto.createTransmuxer_=function createTransmuxer_(){var transmuxer=new TransmuxWorker();transmuxer.postMessage({action:'init',options:{remux:false,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:true,handlePartialData:this.handlePartialData_}});return transmuxer;};_proto.resetStats_=function resetStats_(){this.mediaBytesTransferred=0;this.mediaRequests=0;this.mediaRequestsAborted=0;this.mediaRequestsTimedout=0;this.mediaRequestsErrored=0;this.mediaTransferDuration=0;this.mediaSecondsLoaded=0;};_proto.dispose=function dispose(){this.trigger('dispose');this.state='DISPOSED';this.pause();this.abort_();if(this.transmuxer_){this.transmuxer_.terminate();segmentTransmuxer.dispose();}
this.resetStats_();if(this.checkBufferTimeout_){window_1$2.clearTimeout(this.checkBufferTimeout_);}
if(this.syncController_&&this.triggerSyncInfoUpdate_){this.syncController_.off('syncinfoupdate',this.triggerSyncInfoUpdate_);}
this.off();};_proto.setAudio=function setAudio(enable){this.audioDisabled_=!enable;if(enable){this.appendInitSegment_.audio=true;}else{this.sourceUpdater_.removeAudio(0,this.duration_());}};_proto.abort=function abort(){if(this.state!=='WAITING'){if(this.pendingSegment_){this.pendingSegment_=null;}
return;}
this.abort_();this.state='READY';if(!this.paused()){this.monitorBuffer_();}};_proto.abort_=function abort_(){if(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_);};_proto.checkForAbort_=function checkForAbort_(requestId){if(this.state==='APPENDING'&&!this.pendingSegment_){this.state='READY';return true;}
if(!this.pendingSegment_||this.pendingSegment_.requestId!==requestId){return true;}
return false;};_proto.error=function error(_error){if(typeof _error!=='undefined'){this.logger_('error occurred:',_error);this.error_=_error;}
this.pendingSegment_=null;return this.error_;};_proto.endOfStream=function endOfStream(){this.ended_=true;if(this.transmuxer_){segmentTransmuxer.reset(this.transmuxer_);}
this.gopBuffer_.length=0;this.pause();this.trigger('ended');};_proto.buffered_=function buffered_(){if(!this.sourceUpdater_||!this.startingMediaInfo_){return videojs$1.createTimeRanges();}
if(this.loaderType_==='main'){var _this$startingMediaIn=this.startingMediaInfo_,hasAudio=_this$startingMediaIn.hasAudio,hasVideo=_this$startingMediaIn.hasVideo,isMuxed=_this$startingMediaIn.isMuxed;if(hasVideo&&hasAudio&&!this.audioDisabled_&&!isMuxed){return this.sourceUpdater_.buffered();}
if(hasVideo){return this.sourceUpdater_.videoBuffered();}}
return this.sourceUpdater_.audioBuffered();};_proto.initSegmentForMap=function initSegmentForMap(map,set){if(set===void 0){set=false;}
if(!map){return null;}
var id=initSegmentId(map);var storedMap=this.initSegments_[id];if(set&&!storedMap&&map.bytes){this.initSegments_[id]=storedMap={resolvedUri:map.resolvedUri,byterange:map.byterange,bytes:map.bytes,tracks:map.tracks,timescales:map.timescales};}
return storedMap||map;};_proto.segmentKey=function segmentKey(key,set){if(set===void 0){set=false;}
if(!key){return null;}
var id=segmentKeyId(key);var storedKey=this.keyCache_[id];if(this.cacheEncryptionKeys_&&set&&!storedKey&&key.bytes){this.keyCache_[id]=storedKey={resolvedUri:key.resolvedUri,bytes:key.bytes};}
var result={resolvedUri:(storedKey||key).resolvedUri};if(storedKey){result.bytes=storedKey.bytes;}
return result;};_proto.couldBeginLoading_=function couldBeginLoading_(){return this.playlist_&&!this.paused();};_proto.load=function load(){this.monitorBuffer_();if(!this.playlist_){return;}
this.syncController_.setDateTimeMapping(this.playlist_);if(this.state==='INIT'&&this.couldBeginLoading_()){return this.init_();}
if(!this.couldBeginLoading_()||this.state!=='READY'&&this.state!=='INIT'){return;}
this.state='READY';};_proto.init_=function init_(){this.state='READY';this.resetEverything();return this.monitorBuffer_();};_proto.playlist=function playlist(newPlaylist,options){if(options===void 0){options={};}
if(!newPlaylist){return;}
var oldPlaylist=this.playlist_;var segmentInfo=this.pendingSegment_;this.playlist_=newPlaylist;this.xhrOptions_=options;if(this.state==='INIT'){newPlaylist.syncInfo={mediaSequence:newPlaylist.mediaSequence,time:0};}
var oldId=null;if(oldPlaylist){if(oldPlaylist.id){oldId=oldPlaylist.id;}else if(oldPlaylist.uri){oldId=oldPlaylist.uri;}}
this.logger_("playlist update ["+oldId+" => "+(newPlaylist.id||newPlaylist.uri)+"]");this.trigger('syncinfoupdate');if(this.state==='INIT'&&this.couldBeginLoading_()){return this.init_();}
if(!oldPlaylist||oldPlaylist.uri!==newPlaylist.uri){if(this.mediaIndex!==null||this.handlePartialData_){this.resyncLoader();}
this.currentMediaInfo_=void 0;this.trigger('playlistupdate');return;}
var mediaSequenceDiff=newPlaylist.mediaSequence-oldPlaylist.mediaSequence;this.logger_("live window shift ["+mediaSequenceDiff+"]");if(this.mediaIndex!==null){this.mediaIndex-=mediaSequenceDiff;}
if(segmentInfo){segmentInfo.mediaIndex-=mediaSequenceDiff;if(segmentInfo.mediaIndex>=0){segmentInfo.segment=newPlaylist.segments[segmentInfo.mediaIndex];}}
this.syncController_.saveExpiredSegmentInfo(oldPlaylist,newPlaylist);};_proto.pause=function pause(){if(this.checkBufferTimeout_){window_1$2.clearTimeout(this.checkBufferTimeout_);this.checkBufferTimeout_=null;}};_proto.paused=function paused(){return this.checkBufferTimeout_===null;};_proto.resetEverything=function resetEverything(done){this.ended_=false;this.appendInitSegment_={audio:true,video:true};this.resetLoader();this.remove(0,Infinity,done);if(this.transmuxer_){this.transmuxer_.postMessage({action:'clearAllMp4Captions'});}};_proto.resetLoader=function resetLoader(){this.fetchAtBuffer_=false;this.resyncLoader();};_proto.resyncLoader=function resyncLoader(){if(this.transmuxer_){segmentTransmuxer.reset(this.transmuxer_);}
this.mediaIndex=null;this.syncPoint_=null;this.isPendingTimestampOffset_=false;this.callQueue_=[];this.loadQueue_=[];this.metadataQueue_.id3=[];this.metadataQueue_.caption=[];this.abort();if(this.transmuxer_){this.transmuxer_.postMessage({action:'clearParsedMp4Captions'});}};_proto.remove=function remove(start,end,done){if(done===void 0){done=function done(){};}
if(end===Infinity){end=this.duration_();}
if(!this.sourceUpdater_||!this.currentMediaInfo_){return;}
var removesRemaining=1;var removeFinished=function removeFinished(){removesRemaining--;if(removesRemaining===0){done();}};if(!this.audioDisabled_){removesRemaining++;this.sourceUpdater_.removeAudio(start,end,removeFinished);}
if(this.loaderType_==='main'&&this.currentMediaInfo_&&this.currentMediaInfo_.hasVideo){this.gopBuffer_=removeGopBuffer(this.gopBuffer_,start,end,this.timeMapping_);removesRemaining++;this.sourceUpdater_.removeVideo(start,end,removeFinished);}
for(var track in this.inbandTextTracks_){removeCuesFromTrack(start,end,this.inbandTextTracks_[track]);}
removeCuesFromTrack(start,end,this.segmentMetadataTrack_);removeFinished();};_proto.monitorBuffer_=function monitorBuffer_(){if(this.checkBufferTimeout_){window_1$2.clearTimeout(this.checkBufferTimeout_);}
this.checkBufferTimeout_=window_1$2.setTimeout(this.monitorBufferTick_.bind(this),1);};_proto.monitorBufferTick_=function monitorBufferTick_(){if(this.state==='READY'){this.fillBuffer_();}
if(this.checkBufferTimeout_){window_1$2.clearTimeout(this.checkBufferTimeout_);}
this.checkBufferTimeout_=window_1$2.setTimeout(this.monitorBufferTick_.bind(this),CHECK_BUFFER_DELAY);};_proto.fillBuffer_=function fillBuffer_(){if(this.sourceUpdater_.updating()){return;}
if(!this.syncPoint_){this.syncPoint_=this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_());}
var buffered=this.buffered_();var segmentInfo=this.checkBuffer_(buffered,this.playlist_,this.mediaIndex,this.hasPlayed_(),this.currentTime_(),this.syncPoint_);if(!segmentInfo){return;}
segmentInfo.timestampOffset=timestampOffsetForSegment({segmentTimeline:segmentInfo.timeline,currentTimeline:this.currentTimeline_,startOfSegment:segmentInfo.startOfSegment,buffered:buffered,overrideCheck:this.isPendingTimestampOffset_});this.isPendingTimestampOffset_=false;if(typeof segmentInfo.timestampOffset==='number'){this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:segmentInfo.timeline});}
this.loadSegment_(segmentInfo);};_proto.isEndOfStream_=function isEndOfStream_(mediaIndex,playlist){if(mediaIndex===void 0){mediaIndex=this.mediaIndex;}
if(playlist===void 0){playlist=this.playlist_;}
if(!playlist||!this.mediaSource_){return false;}
var appendedLastSegment=mediaIndex+1===playlist.segments.length;return playlist.endList&&this.mediaSource_.readyState==='open'&&appendedLastSegment;};_proto.checkBuffer_=function checkBuffer_(buffered,playlist,currentMediaIndex,hasPlayed,currentTime,syncPoint){var lastBufferedEnd=0;if(buffered.length){lastBufferedEnd=buffered.end(buffered.length-1);}
var bufferedTime=Math.max(0,lastBufferedEnd-currentTime);if(!playlist.segments.length){return null;}
if(bufferedTime>=this.goalBufferLength_()){return null;}
if(!hasPlayed&&bufferedTime>=1){return null;}
var nextMediaIndex=null;var startOfSegment;var isSyncRequest=false;if(syncPoint===null){nextMediaIndex=this.getSyncSegmentCandidate_(playlist);isSyncRequest=true;}else if(currentMediaIndex!==null){var segment=playlist.segments[currentMediaIndex];if(segment&&segment.end){startOfSegment=segment.end;}else{startOfSegment=lastBufferedEnd;}
nextMediaIndex=currentMediaIndex+1;}else if(this.fetchAtBuffer_){var mediaSourceInfo=Playlist.getMediaInfoForTime(playlist,lastBufferedEnd,syncPoint.segmentIndex,syncPoint.time);nextMediaIndex=mediaSourceInfo.mediaIndex;startOfSegment=mediaSourceInfo.startTime;}else{var _mediaSourceInfo=Playlist.getMediaInfoForTime(playlist,currentTime,syncPoint.segmentIndex,syncPoint.time);nextMediaIndex=_mediaSourceInfo.mediaIndex;startOfSegment=_mediaSourceInfo.startTime;}
var segmentInfo=this.generateSegmentInfo_(playlist,nextMediaIndex,startOfSegment,isSyncRequest);if(!segmentInfo){return;}
if(this.mediaSource_&&this.playlist_&&segmentInfo.mediaIndex===this.playlist_.segments.length-1&&this.mediaSource_.readyState==='ended'&&!this.seeking_()){return;}
this.logger_("checkBuffer_ returning "+segmentInfo.uri,{segmentInfo:segmentInfo,playlist:playlist,currentMediaIndex:currentMediaIndex,nextMediaIndex:nextMediaIndex,startOfSegment:startOfSegment,isSyncRequest:isSyncRequest});return segmentInfo;};_proto.getSyncSegmentCandidate_=function getSyncSegmentCandidate_(playlist){var _this2=this;if(this.currentTimeline_===-1){return 0;}
var segmentIndexArray=playlist.segments.map(function(s,i){return{timeline:s.timeline,segmentIndex:i};}).filter(function(s){return s.timeline===_this2.currentTimeline_;});if(segmentIndexArray.length){return segmentIndexArray[Math.min(segmentIndexArray.length-1,1)].segmentIndex;}
return Math.max(playlist.segments.length-1,0);};_proto.generateSegmentInfo_=function generateSegmentInfo_(playlist,mediaIndex,startOfSegment,isSyncRequest){if(mediaIndex<0||mediaIndex>=playlist.segments.length){return null;}
var segment=playlist.segments[mediaIndex];var audioBuffered=this.sourceUpdater_.audioBuffered();var videoBuffered=this.sourceUpdater_.videoBuffered();var audioAppendStart;var gopsToAlignWith;if(audioBuffered.length){audioAppendStart=audioBuffered.end(audioBuffered.length-1)-this.sourceUpdater_.audioTimestampOffset();}
if(videoBuffered.length){gopsToAlignWith=gopsSafeToAlignWith(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_);}
return{requestId:'segment-loader-'+Math.random(),uri:segment.resolvedUri,mediaIndex:mediaIndex,isSyncRequest:isSyncRequest,startOfSegment:startOfSegment,playlist:playlist,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:segment.timeline,duration:segment.duration,segment:segment,byteLength:0,transmuxer:this.transmuxer_,audioAppendStart:audioAppendStart,gopsToAlignWith:gopsToAlignWith};};_proto.earlyAbortWhenNeeded_=function earlyAbortWhenNeeded_(stats){if(this.vhs_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH){return;}
if(Date.now()-(stats.firstBytesReceivedAt||Date.now())<1000){return;}
var currentTime=this.currentTime_();var measuredBandwidth=stats.bandwidth;var segmentDuration=this.pendingSegment_.duration;var requestTimeRemaining=Playlist.estimateSegmentRequestTime(segmentDuration,measuredBandwidth,this.playlist_,stats.bytesReceived);var timeUntilRebuffer$1=timeUntilRebuffer(this.buffered_(),currentTime,this.vhs_.tech_.playbackRate())-1;if(requestTimeRemaining<=timeUntilRebuffer$1){return;}
var switchCandidate=minRebufferMaxBandwidthSelector({master:this.vhs_.playlists.master,currentTime:currentTime,bandwidth:measuredBandwidth,duration:this.duration_(),segmentDuration:segmentDuration,timeUntilRebuffer:timeUntilRebuffer$1,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!switchCandidate){return;}
var rebufferingImpact=requestTimeRemaining-timeUntilRebuffer$1;var timeSavedBySwitching=rebufferingImpact-switchCandidate.rebufferingImpact;var minimumTimeSaving=0.5;if(timeUntilRebuffer$1<=TIME_FUDGE_FACTOR){minimumTimeSaving=1;}
if(!switchCandidate.playlist||switchCandidate.playlist.uri===this.playlist_.uri||timeSavedBySwitching<minimumTimeSaving){return;}
this.bandwidth=switchCandidate.playlist.attributes.BANDWIDTH*Config.BANDWIDTH_VARIANCE+1;this.trigger('earlyabort');};_proto.handleAbort_=function handleAbort_(){this.mediaRequestsAborted+=1;};_proto.handleProgress_=function handleProgress_(event,simpleSegment){this.earlyAbortWhenNeeded_(simpleSegment.stats);if(this.checkForAbort_(simpleSegment.requestId)){return;}
this.trigger('progress');};_proto.handleTrackInfo_=function handleTrackInfo_(simpleSegment,trackInfo){this.earlyAbortWhenNeeded_(simpleSegment.stats);if(this.checkForAbort_(simpleSegment.requestId)){return;}
if(this.checkForIllegalMediaSwitch(trackInfo)){return;}
trackInfo=trackInfo||{};if(!shallowEqual(this.currentMediaInfo_,trackInfo)){this.appendInitSegment_={audio:true,video:true};this.startingMediaInfo_=trackInfo;this.currentMediaInfo_=trackInfo;this.logger_('trackinfo update',trackInfo);this.trigger('trackinfo');}
if(this.checkForAbort_(simpleSegment.requestId)){return;}
this.pendingSegment_.trackInfo=trackInfo;if(this.hasEnoughInfoToAppend_()){this.processCallQueue_();}};_proto.handleTimingInfo_=function handleTimingInfo_(simpleSegment,mediaType,timeType,time){this.earlyAbortWhenNeeded_(simpleSegment.stats);if(this.checkForAbort_(simpleSegment.requestId)){return;}
var segmentInfo=this.pendingSegment_;var timingInfoProperty=timingInfoPropertyForMedia(mediaType);segmentInfo[timingInfoProperty]=segmentInfo[timingInfoProperty]||{};segmentInfo[timingInfoProperty][timeType]=time;this.logger_("timinginfo: "+mediaType+" - "+timeType+" - "+time);if(this.hasEnoughInfoToAppend_()){this.processCallQueue_();}};_proto.handleCaptions_=function handleCaptions_(simpleSegment,captionData){var _this3=this;this.earlyAbortWhenNeeded_(simpleSegment.stats);if(this.checkForAbort_(simpleSegment.requestId)){return;}
if(captionData.length===0){this.logger_('SegmentLoader received no captions from a caption event');return;}
var segmentInfo=this.pendingSegment_;if(!segmentInfo.hasAppendedData_){this.metadataQueue_.caption.push(this.handleCaptions_.bind(this,simpleSegment,captionData));return;}
var timestampOffset=this.sourceUpdater_.videoTimestampOffset()===null?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();var captionTracks={};captionData.forEach(function(caption){captionTracks[caption.stream]=captionTracks[caption.stream]||{startTime:Infinity,captions:[],endTime:0};var 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(function(trackName){var _captionTracks$trackN=captionTracks[trackName],startTime=_captionTracks$trackN.startTime,endTime=_captionTracks$trackN.endTime,captions=_captionTracks$trackN.captions;var inbandTextTracks=_this3.inbandTextTracks_;_this3.logger_("adding cues from "+startTime+" -> "+endTime+" for "+trackName);createCaptionsTrackIfNotExists(inbandTextTracks,_this3.vhs_.tech_,trackName);removeCuesFromTrack(startTime,endTime,inbandTextTracks[trackName]);addCaptionData({captionArray:captions,inbandTextTracks:inbandTextTracks,timestampOffset:timestampOffset});});if(this.transmuxer_){this.transmuxer_.postMessage({action:'clearParsedMp4Captions'});}};_proto.handleId3_=function handleId3_(simpleSegment,id3Frames,dispatchType){this.earlyAbortWhenNeeded_(simpleSegment.stats);if(this.checkForAbort_(simpleSegment.requestId)){return;}
var segmentInfo=this.pendingSegment_;if(!segmentInfo.hasAppendedData_){this.metadataQueue_.id3.push(this.handleId3_.bind(this,simpleSegment,id3Frames,dispatchType));return;}
var timestampOffset=this.sourceUpdater_.videoTimestampOffset()===null?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();createMetadataTrackIfNotExists(this.inbandTextTracks_,dispatchType,this.vhs_.tech_);addMetadata({inbandTextTracks:this.inbandTextTracks_,metadataArray:id3Frames,timestampOffset:timestampOffset,videoDuration:this.duration_()});};_proto.processMetadataQueue_=function processMetadataQueue_(){this.metadataQueue_.id3.forEach(function(fn){return fn();});this.metadataQueue_.caption.forEach(function(fn){return fn();});this.metadataQueue_.id3=[];this.metadataQueue_.caption=[];};_proto.processCallQueue_=function processCallQueue_(){var callQueue=this.callQueue_;this.callQueue_=[];callQueue.forEach(function(fun){return fun();});};_proto.processLoadQueue_=function processLoadQueue_(){var loadQueue=this.loadQueue_;this.loadQueue_=[];loadQueue.forEach(function(fun){return fun();});};_proto.hasEnoughInfoToLoad_=function hasEnoughInfoToLoad_(){if(this.loaderType_!=='audio'){return true;}
var segmentInfo=this.pendingSegment_;if(!segmentInfo){return false;}
if(!this.currentMediaInfo_){return true;}
if(shouldWaitForTimelineChange({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:segmentInfo.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_})){return false;}
return true;};_proto.hasEnoughInfoToAppend_=function hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready()){return false;}
var segmentInfo=this.pendingSegment_;if(!segmentInfo||!segmentInfo.trackInfo){return false;}
if(!this.handlePartialData_){var _this$currentMediaInf=this.currentMediaInfo_,hasAudio=_this$currentMediaInf.hasAudio,hasVideo=_this$currentMediaInf.hasVideo,isMuxed=_this$currentMediaInf.isMuxed;if(hasVideo&&!segmentInfo.videoTimingInfo){return false;}
if(hasAudio&&!this.audioDisabled_&&!isMuxed&&!segmentInfo.audioTimingInfo){return false;}}
if(shouldWaitForTimelineChange({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:segmentInfo.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_})){return false;}
return true;};_proto.handleData_=function handleData_(simpleSegment,result){this.earlyAbortWhenNeeded_(simpleSegment.stats);if(this.checkForAbort_(simpleSegment.requestId)){return;}
if(this.callQueue_.length||!this.hasEnoughInfoToAppend_()){this.callQueue_.push(this.handleData_.bind(this,simpleSegment,result));return;}
var segmentInfo=this.pendingSegment_;this.setTimeMapping_(segmentInfo.timeline);this.updateMediaSecondsLoaded_(segmentInfo.segment);if(this.mediaSource_.readyState==='closed'){return;}
if(simpleSegment.map){simpleSegment.map=this.initSegmentForMap(simpleSegment.map,true);segmentInfo.segment.map=simpleSegment.map;}
if(simpleSegment.key){this.segmentKey(simpleSegment.key,true);}
segmentInfo.isFmp4=simpleSegment.isFmp4;segmentInfo.timingInfo=segmentInfo.timingInfo||{};if(segmentInfo.isFmp4){this.trigger('fmp4');segmentInfo.timingInfo.start=segmentInfo[timingInfoPropertyForMedia(result.type)].start;}else{var useVideoTimingInfo=this.loaderType_==='main'&&this.currentMediaInfo_.hasVideo;var firstVideoFrameTimeForData;if(useVideoTimingInfo){firstVideoFrameTimeForData=this.handlePartialData_?result.videoFramePtsTime: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});}
this.updateAppendInitSegmentStatus(segmentInfo,result.type);this.updateSourceBufferTimestampOffset_(segmentInfo);segmentInfo.hasAppendedData_=true;this.processMetadataQueue_();this.appendData_(segmentInfo,result);};_proto.updateAppendInitSegmentStatus=function updateAppendInitSegmentStatus(segmentInfo,type){if(this.loaderType_==='main'&&typeof segmentInfo.timestampOffset==='number'&&!segmentInfo.changedTimestampOffset){this.appendInitSegment_={audio:true,video:true};}
if(this.playlistOfLastInitSegment_[type]!==segmentInfo.playlist){this.appendInitSegment_[type]=true;}};_proto.getInitSegmentAndUpdateState_=function getInitSegmentAndUpdateState_(_ref4){var type=_ref4.type,initSegment=_ref4.initSegment,map=_ref4.map,playlist=_ref4.playlist;if(map){var id=initSegmentId(map);if(this.activeInitSegmentId_===id){return null;}
initSegment=this.initSegmentForMap(map,true).bytes;this.activeInitSegmentId_=id;}
if(initSegment&&this.appendInitSegment_[type]){this.playlistOfLastInitSegment_[type]=playlist;this.appendInitSegment_[type]=map?true:false;this.activeInitSegmentId_=null;return initSegment;}
return null;};_proto.appendToSourceBuffer_=function appendToSourceBuffer_(_ref5){var _this4=this;var segmentInfo=_ref5.segmentInfo,type=_ref5.type,initSegment=_ref5.initSegment,data=_ref5.data;var segments=[data];var byteLength=data.byteLength;if(initSegment){segments.unshift(initSegment);byteLength+=initSegment.byteLength;}
var bytes=concatSegments({bytes:byteLength,segments:segments});this.sourceUpdater_.appendBuffer({segmentInfo:segmentInfo,type:type,bytes:bytes},function(error){if(error){_this4.error(type+" append of "+bytes.length+"b failed for segment #"+segmentInfo.mediaIndex+" in playlist "+segmentInfo.playlist.id);_this4.trigger('appenderror');}});};_proto.handleSegmentTimingInfo_=function handleSegmentTimingInfo_(type,requestId,segmentTimingInfo){if(!this.pendingSegment_||requestId!==this.pendingSegment_.requestId){return;}
var segment=this.pendingSegment_.segment;var timingInfoProperty=type+"TimingInfo";if(!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;};_proto.appendData_=function appendData_(segmentInfo,result){var type=result.type,data=result.data;if(!data||!data.byteLength){return;}
if(type==='audio'&&this.audioDisabled_){return;}
var initSegment=this.getInitSegmentAndUpdateState_({type:type,initSegment:result.initSegment,playlist:segmentInfo.playlist,map:segmentInfo.isFmp4?segmentInfo.segment.map:null});this.appendToSourceBuffer_({segmentInfo:segmentInfo,type:type,initSegment:initSegment,data:data});};_proto.loadSegment_=function loadSegment_(segmentInfo){var _this5=this;this.state='WAITING';this.pendingSegment_=segmentInfo;this.trimBackBuffer_(segmentInfo);if(typeof segmentInfo.timestampOffset==='number'){if(this.transmuxer_){this.transmuxer_.postMessage({action:'clearAllMp4Captions'});}}
if(!this.hasEnoughInfoToLoad_()){this.loadQueue_.push(function(){var buffered=_this5.buffered_();if(typeof segmentInfo.timestampOffset==='number'){segmentInfo.timestampOffset=timestampOffsetForSegment({segmentTimeline:segmentInfo.timeline,currentTimeline:_this5.currentTimeline_,startOfSegment:segmentInfo.startOfSegment,buffered:buffered,overrideCheck:true});}
delete segmentInfo.audioAppendStart;var audioBuffered=_this5.sourceUpdater_.audioBuffered();if(audioBuffered.length){segmentInfo.audioAppendStart=audioBuffered.end(audioBuffered.length-1)-_this5.sourceUpdater_.audioTimestampOffset();}
_this5.updateTransmuxerAndRequestSegment_(segmentInfo);});return;}
this.updateTransmuxerAndRequestSegment_(segmentInfo);};_proto.updateTransmuxerAndRequestSegment_=function updateTransmuxerAndRequestSegment_(segmentInfo){if(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});}
var simpleSegment=this.createSimplifiedSegmentObj_(segmentInfo);segmentInfo.abortRequests=mediaSegmentRequest({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:simpleSegment,handlePartialData:this.handlePartialData_,abortFn:this.handleAbort_.bind(this),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),id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this)});};_proto.trimBackBuffer_=function trimBackBuffer_(segmentInfo){var removeToTime=safeBackBufferTrimTime(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);if(removeToTime>0){this.remove(0,removeToTime);}};_proto.createSimplifiedSegmentObj_=function createSimplifiedSegmentObj_(segmentInfo){var segment=segmentInfo.segment;var simpleSegment={resolvedUri:segment.resolvedUri,byterange:segment.byterange,requestId:segmentInfo.requestId,transmuxer:segmentInfo.transmuxer,audioAppendStart:segmentInfo.audioAppendStart,gopsToAlignWith:segmentInfo.gopsToAlignWith};var previousSegment=segmentInfo.playlist.segments[segmentInfo.mediaIndex-1];if(previousSegment&&previousSegment.timeline===segment.timeline){if(previousSegment.videoTimingInfo){simpleSegment.baseStartTime=previousSegment.videoTimingInfo.transmuxedDecodeEnd;}else if(previousSegment.audioTimingInfo){simpleSegment.baseStartTime=previousSegment.audioTimingInfo.transmuxedDecodeEnd;}}
if(segment.key){var iv=segment.key.iv||new Uint32Array([0,0,0,segmentInfo.mediaIndex+segmentInfo.playlist.mediaSequence]);simpleSegment.key=this.segmentKey(segment.key);simpleSegment.key.iv=iv;}
if(segment.map){simpleSegment.map=this.initSegmentForMap(segment.map);}
return simpleSegment;};_proto.saveTransferStats_=function saveTransferStats_(stats){this.mediaRequests+=1;if(stats){this.mediaBytesTransferred+=stats.bytesReceived;this.mediaTransferDuration+=stats.roundTripTime;}};_proto.saveBandwidthRelatedStats_=function saveBandwidthRelatedStats_(duration,stats){this.pendingSegment_.byteLength=stats.bytesReceived;if(duration<MIN_SEGMENT_DURATION_TO_SAVE_STATS){this.logger_("Ignoring segment's bandwidth because its duration of "+duration+(" is less than the min to record "+MIN_SEGMENT_DURATION_TO_SAVE_STATS));return;}
this.bandwidth=stats.bandwidth;this.roundTrip=stats.roundTripTime;};_proto.handleTimeout_=function handleTimeout_(){this.mediaRequestsTimedout+=1;this.bandwidth=1;this.roundTrip=NaN;this.trigger('bandwidthupdate');};_proto.segmentRequestFinished_=function segmentRequestFinished_(error,simpleSegment,result){if(this.callQueue_.length){this.callQueue_.push(this.segmentRequestFinished_.bind(this,error,simpleSegment,result));return;}
this.saveTransferStats_(simpleSegment.stats);if(!this.pendingSegment_){return;}
if(simpleSegment.requestId!==this.pendingSegment_.requestId){return;}
if(error){this.pendingSegment_=null;this.state='READY';if(error.code===REQUEST_ERRORS.ABORTED){return;}
this.pause();if(error.code===REQUEST_ERRORS.TIMEOUT){this.handleTimeout_();return;}
this.mediaRequestsErrored+=1;this.error(error);this.trigger('error');return;}
var segmentInfo=this.pendingSegment_;this.saveBandwidthRelatedStats_(segmentInfo.duration,simpleSegment.stats);segmentInfo.endOfAllRequests=simpleSegment.endOfAllRequests;if(result.gopInfo){this.gopBuffer_=updateGopBuffer(this.gopBuffer_,result.gopInfo,this.safeAppend_);}
this.state='APPENDING';var isEndOfStream=this.isEndOfStream_(segmentInfo.mediaIndex,segmentInfo.playlist);var isWalkingForward=this.mediaIndex!==null;var isDiscontinuity=segmentInfo.timeline!==this.currentTimeline_&&segmentInfo.timeline>0;if(!segmentInfo.isFmp4&&(isEndOfStream||isWalkingForward&&isDiscontinuity)){segmentTransmuxer.endTimeline(this.transmuxer_);}
this.trigger('appending');this.waitForAppendsToComplete_(segmentInfo);};_proto.setTimeMapping_=function setTimeMapping_(timeline){var timelineMapping=this.syncController_.mappingForTimeline(timeline);if(timelineMapping!==null){this.timeMapping_=timelineMapping;}};_proto.updateMediaSecondsLoaded_=function updateMediaSecondsLoaded_(segment){if(typeof segment.start==='number'&&typeof segment.end==='number'){this.mediaSecondsLoaded+=segment.end-segment.start;}else{this.mediaSecondsLoaded+=segment.duration;}};_proto.shouldUpdateTransmuxerTimestampOffset_=function shouldUpdateTransmuxerTimestampOffset_(timestampOffset){if(timestampOffset===null){return false;}
if(this.loaderType_==='main'&&timestampOffset!==this.sourceUpdater_.videoTimestampOffset()){return true;}
if(!this.audioDisabled_&&timestampOffset!==this.sourceUpdater_.audioTimestampOffset()){return true;}
return false;};_proto.trueSegmentStart_=function trueSegmentStart_(_ref6){var currentStart=_ref6.currentStart,playlist=_ref6.playlist,mediaIndex=_ref6.mediaIndex,firstVideoFrameTimeForData=_ref6.firstVideoFrameTimeForData,currentVideoTimestampOffset=_ref6.currentVideoTimestampOffset,useVideoTimingInfo=_ref6.useVideoTimingInfo,videoTimingInfo=_ref6.videoTimingInfo,audioTimingInfo=_ref6.audioTimingInfo;if(typeof currentStart!=='undefined'){return currentStart;}
if(!useVideoTimingInfo){return audioTimingInfo.start;}
var previousSegment=playlist.segments[mediaIndex-1];if(mediaIndex===0||!previousSegment||typeof previousSegment.start==='undefined'||previousSegment.end!==firstVideoFrameTimeForData+currentVideoTimestampOffset){return firstVideoFrameTimeForData;}
return videoTimingInfo.start;};_proto.waitForAppendsToComplete_=function waitForAppendsToComplete_(segmentInfo){if(!this.currentMediaInfo_){this.error({message:'No starting media returned, likely due to an unsupported media format.',blacklistDuration:Infinity});this.trigger('error');return;}
var _this$currentMediaInf2=this.currentMediaInfo_,hasAudio=_this$currentMediaInf2.hasAudio,hasVideo=_this$currentMediaInf2.hasVideo,isMuxed=_this$currentMediaInf2.isMuxed;var waitForVideo=this.loaderType_==='main'&&hasVideo;var waitForAudio=!this.audioDisabled_&&hasAudio&&!isMuxed;segmentInfo.waitingOnAppends=0;if(!segmentInfo.hasAppendedData_){if(!segmentInfo.timingInfo&&typeof segmentInfo.timestampOffset==='number'){this.isPendingTimestampOffset_=true;}
segmentInfo.timingInfo={start:0};segmentInfo.waitingOnAppends++;if(!this.isPendingTimestampOffset_){this.updateSourceBufferTimestampOffset_(segmentInfo);this.processMetadataQueue_();}
this.checkAppendsDone_(segmentInfo);return;}
if(waitForVideo){segmentInfo.waitingOnAppends++;}
if(waitForAudio){segmentInfo.waitingOnAppends++;}
if(waitForVideo){this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,segmentInfo));}
if(waitForAudio){this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this,segmentInfo));}};_proto.checkAppendsDone_=function checkAppendsDone_(segmentInfo){if(this.checkForAbort_(segmentInfo.requestId)){return;}
segmentInfo.waitingOnAppends--;if(segmentInfo.waitingOnAppends===0){this.handleAppendsDone_();}};_proto.checkForIllegalMediaSwitch=function checkForIllegalMediaSwitch(trackInfo){var illegalMediaSwitchError=illegalMediaSwitch(this.loaderType_,this.currentMediaInfo_,trackInfo);if(illegalMediaSwitchError){this.error({message:illegalMediaSwitchError,blacklistDuration:Infinity});this.trigger('error');return true;}
return false;};_proto.updateSourceBufferTimestampOffset_=function updateSourceBufferTimestampOffset_(segmentInfo){if(segmentInfo.timestampOffset===null||typeof segmentInfo.timingInfo.start!=='number'||segmentInfo.changedTimestampOffset||this.loaderType_!=='main'){return;}
var didChange=false;segmentInfo.timestampOffset-=segmentInfo.timingInfo.start;segmentInfo.changedTimestampOffset=true;if(segmentInfo.timestampOffset!==this.sourceUpdater_.videoTimestampOffset()){this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);didChange=true;}
if(segmentInfo.timestampOffset!==this.sourceUpdater_.audioTimestampOffset()){this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);didChange=true;}
if(didChange){this.trigger('timestampoffset');}};_proto.updateTimingInfoEnd_=function updateTimingInfoEnd_(segmentInfo){segmentInfo.timingInfo=segmentInfo.timingInfo||{};var useVideoTimingInfo=this.loaderType_==='main'&&this.currentMediaInfo_.hasVideo;var prioritizedTimingInfo=useVideoTimingInfo&&segmentInfo.videoTimingInfo?segmentInfo.videoTimingInfo:segmentInfo.audioTimingInfo;if(!prioritizedTimingInfo){return;}
segmentInfo.timingInfo.end=typeof prioritizedTimingInfo.end==='number'?prioritizedTimingInfo.end:prioritizedTimingInfo.start+segmentInfo.duration;};_proto.handleAppendsDone_=function handleAppendsDone_(){if(this.pendingSegment_){this.trigger('appendsdone');}
if(!this.pendingSegment_){this.state='READY';if(!this.paused()){this.monitorBuffer_();}
return;}
var segmentInfo=this.pendingSegment_;this.updateTimingInfoEnd_(segmentInfo);if(this.shouldSaveSegmentTimingInfo_){this.syncController_.saveSegmentTimingInfo({segmentInfo:segmentInfo,shouldSaveTimelineMapping:this.loaderType_==='main'});}
this.logger_(segmentInfoString(segmentInfo));var segmentDurationMessage=getTroublesomeSegmentDurationMessage(segmentInfo,this.sourceType_);if(segmentDurationMessage){if(segmentDurationMessage.severity==='warn'){videojs$1.log.warn(segmentDurationMessage.message);}else{this.logger_(segmentDurationMessage.message);}}
this.recordThroughput_(segmentInfo);this.pendingSegment_=null;this.state='READY';if(segmentInfo.isSyncRequest){this.trigger('syncinfoupdate');return;}
this.addSegmentMetadataCue_(segmentInfo);this.fetchAtBuffer_=true;if(this.currentTimeline_!==segmentInfo.timeline){this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:segmentInfo.timeline});if(this.loaderType_==='main'&&!this.audioDisabled_){this.timelineChangeController_.lastTimelineChange({type:'audio',from:this.currentTimeline_,to:segmentInfo.timeline});}}
this.currentTimeline_=segmentInfo.timeline;this.trigger('syncinfoupdate');var segment=segmentInfo.segment;if(segment.end&&this.currentTime_()-segment.end>segmentInfo.playlist.targetDuration*3){this.resetEverything();return;}
var isWalkingForward=this.mediaIndex!==null;if(isWalkingForward){this.trigger('bandwidthupdate');}
this.trigger('progress');this.mediaIndex=segmentInfo.mediaIndex;if(this.isEndOfStream_(segmentInfo.mediaIndex,segmentInfo.playlist)){this.endOfStream();}
this.trigger('appended');if(!this.paused()){this.monitorBuffer_();}};_proto.recordThroughput_=function recordThroughput_(segmentInfo){if(segmentInfo.duration<MIN_SEGMENT_DURATION_TO_SAVE_STATS){this.logger_("Ignoring segment's throughput because its duration of "+segmentInfo.duration+(" is less than the min to record "+MIN_SEGMENT_DURATION_TO_SAVE_STATS));return;}
var rate=this.throughput.rate;var segmentProcessingTime=Date.now()-segmentInfo.endOfAllRequests+1;var segmentProcessingThroughput=Math.floor(segmentInfo.byteLength/segmentProcessingTime*8*1000);this.throughput.rate+=(segmentProcessingThroughput-rate)/++this.throughput.count;};_proto.addSegmentMetadataCue_=function addSegmentMetadataCue_(segmentInfo){if(!this.segmentMetadataTrack_){return;}
var segment=segmentInfo.segment;var start=segment.start;var end=segment.end;if(!finite(start)||!finite(end)){return;}
removeCuesFromTrack(start,end,this.segmentMetadataTrack_);var Cue=window_1$2.WebKitDataCue||window_1$2.VTTCue;var value={custom:segment.custom,dateTimeObject:segment.dateTimeObject,dateTimeString:segment.dateTimeString,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};var data=JSON.stringify(value);var cue=new Cue(start,end,data);cue.value=value;this.segmentMetadataTrack_.addCue(cue);};return SegmentLoader;}(videojs$1.EventTarget);function noop$1(){}
var toTitleCase$1=function toTitleCase(string){if(typeof string!=='string'){return string;}
return string.replace(/./,function(w){return w.toUpperCase();});};var bufferTypes=['video','audio'];var _updating=function updating(type,sourceUpdater){var sourceBuffer=sourceUpdater[type+"Buffer"];return sourceBuffer&&sourceBuffer.updating||sourceUpdater.queuePending[type];};var nextQueueIndexOfType=function nextQueueIndexOfType(type,queue){for(var i=0;i<queue.length;i++){var queueEntry=queue[i];if(queueEntry.type==='mediaSource'){return null;}
if(queueEntry.type===type){return i;}}
return null;};var shiftQueue=function shiftQueue(type,sourceUpdater){if(sourceUpdater.queue.length===0){return;}
var queueIndex=0;var queueEntry=sourceUpdater.queue[queueIndex];if(queueEntry.type==='mediaSource'){if(!sourceUpdater.updating()&&sourceUpdater.mediaSource.readyState!=='closed'){sourceUpdater.queue.shift();queueEntry.action(sourceUpdater);if(queueEntry.doneFn){queueEntry.doneFn();}
shiftQueue('audio',sourceUpdater);shiftQueue('video',sourceUpdater);}
return;}
if(type==='mediaSource'){return;}
if(!sourceUpdater.ready()||sourceUpdater.mediaSource.readyState==='closed'||_updating(type,sourceUpdater)){return;}
if(queueEntry.type!==type){queueIndex=nextQueueIndexOfType(type,sourceUpdater.queue);if(queueIndex===null){return;}
queueEntry=sourceUpdater.queue[queueIndex];}
sourceUpdater.queue.splice(queueIndex,1);queueEntry.action(type,sourceUpdater);if(!queueEntry.doneFn){shiftQueue(type,sourceUpdater);return;}
sourceUpdater.queuePending[type]=queueEntry;};var cleanupBuffer=function cleanupBuffer(type,sourceUpdater){var buffer=sourceUpdater[type+"Buffer"];var titleType=toTitleCase$1(type);if(!buffer){return;}
buffer.removeEventListener('updateend',sourceUpdater["on"+titleType+"UpdateEnd_"]);buffer.removeEventListener('error',sourceUpdater["on"+titleType+"Error_"]);sourceUpdater.codecs[type]=null;sourceUpdater[type+"Buffer"]=null;};var inSourceBuffers=function inSourceBuffers(mediaSource,sourceBuffer){return mediaSource&&sourceBuffer&&Array.prototype.indexOf.call(mediaSource.sourceBuffers,sourceBuffer)!==-1;};var actions={appendBuffer:function appendBuffer(bytes,segmentInfo){return function(type,sourceUpdater){var sourceBuffer=sourceUpdater[type+"Buffer"];if(!inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)){return;}
sourceUpdater.logger_("Appending segment "+segmentInfo.mediaIndex+"'s "+bytes.length+" bytes to "+type+"Buffer");sourceBuffer.appendBuffer(bytes);};},remove:function remove(start,end){return function(type,sourceUpdater){var sourceBuffer=sourceUpdater[type+"Buffer"];if(!inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)){return;}
sourceUpdater.logger_("Removing "+start+" to "+end+" from "+type+"Buffer");sourceBuffer.remove(start,end);};},timestampOffset:function timestampOffset(offset){return function(type,sourceUpdater){var sourceBuffer=sourceUpdater[type+"Buffer"];if(!inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)){return;}
sourceUpdater.logger_("Setting "+type+"timestampOffset to "+offset);sourceBuffer.timestampOffset=offset;};},callback:function callback(_callback){return function(type,sourceUpdater){_callback();};},endOfStream:function endOfStream(error){return function(sourceUpdater){if(sourceUpdater.mediaSource.readyState!=='open'){return;}
sourceUpdater.logger_("Calling mediaSource endOfStream("+(error||'')+")");try{sourceUpdater.mediaSource.endOfStream(error);}catch(e){videojs$1.log.warn('Failed to call media source endOfStream',e);}};},duration:function duration(_duration){return function(sourceUpdater){sourceUpdater.logger_("Setting mediaSource duration to "+_duration);try{sourceUpdater.mediaSource.duration=_duration;}catch(e){videojs$1.log.warn('Failed to set media source duration',e);}};},abort:function abort(){return function(type,sourceUpdater){if(sourceUpdater.mediaSource.readyState!=='open'){return;}
var sourceBuffer=sourceUpdater[type+"Buffer"];if(!inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)){return;}
sourceUpdater.logger_("calling abort on "+type+"Buffer");try{sourceBuffer.abort();}catch(e){videojs$1.log.warn("Failed to abort on "+type+"Buffer",e);}};},addSourceBuffer:function addSourceBuffer(type,codec){return function(sourceUpdater){var titleType=toTitleCase$1(type);var mime=codecs_5(codec);sourceUpdater.logger_("Adding "+type+"Buffer with codec "+codec+" to mediaSource");var sourceBuffer=sourceUpdater.mediaSource.addSourceBuffer(mime);sourceBuffer.addEventListener('updateend',sourceUpdater["on"+titleType+"UpdateEnd_"]);sourceBuffer.addEventListener('error',sourceUpdater["on"+titleType+"Error_"]);sourceUpdater.codecs[type]=codec;sourceUpdater[type+"Buffer"]=sourceBuffer;};},removeSourceBuffer:function removeSourceBuffer(type){return function(sourceUpdater){var sourceBuffer=sourceUpdater[type+"Buffer"];cleanupBuffer(type,sourceUpdater);if(!inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)){return;}
sourceUpdater.logger_("Removing "+type+"Buffer with codec "+sourceUpdater.codecs[type]+" from mediaSource");try{sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);}catch(e){videojs$1.log.warn("Failed to removeSourceBuffer "+type+"Buffer",e);}};},changeType:function changeType(codec){return function(type,sourceUpdater){var sourceBuffer=sourceUpdater[type+"Buffer"];var mime=codecs_5(codec);if(!inSourceBuffers(sourceUpdater.mediaSource,sourceBuffer)){return;}
if(sourceUpdater.codecs[type]===codec){return;}
sourceUpdater.logger_("changing "+type+"Buffer codec from "+sourceUpdater.codecs[type]+" to "+codec);sourceBuffer.changeType(mime);sourceUpdater.codecs[type]=codec;};}};var pushQueue=function pushQueue(_ref){var type=_ref.type,sourceUpdater=_ref.sourceUpdater,action=_ref.action,doneFn=_ref.doneFn,name=_ref.name;sourceUpdater.queue.push({type:type,action:action,doneFn:doneFn,name:name});shiftQueue(type,sourceUpdater);};var onUpdateend=function onUpdateend(type,sourceUpdater){return function(e){if(sourceUpdater.queuePending[type]){var doneFn=sourceUpdater.queuePending[type].doneFn;sourceUpdater.queuePending[type]=null;if(doneFn){doneFn(sourceUpdater[type+"Error_"]);}}
shiftQueue(type,sourceUpdater);};};var SourceUpdater=function(_videojs$EventTarget){inheritsLoose$1(SourceUpdater,_videojs$EventTarget);function SourceUpdater(mediaSource){var _this;_this=_videojs$EventTarget.call(this)||this;_this.mediaSource=mediaSource;_this.sourceopenListener_=function(){return shiftQueue('mediaSource',assertThisInitialized$1(_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_=false;_this.codecs={};_this.onVideoUpdateEnd_=onUpdateend('video',assertThisInitialized$1(_this));_this.onAudioUpdateEnd_=onUpdateend('audio',assertThisInitialized$1(_this));_this.onVideoError_=function(e){_this.videoError_=e;};_this.onAudioError_=function(e){_this.audioError_=e;};_this.createdSourceBuffers_=false;_this.initializedEme_=false;_this.triggeredReady_=false;return _this;}
var _proto=SourceUpdater.prototype;_proto.initializedEme=function initializedEme(){this.initializedEme_=true;this.triggerReady();};_proto.hasCreatedSourceBuffers=function hasCreatedSourceBuffers(){return this.createdSourceBuffers_;};_proto.hasInitializedAnyEme=function hasInitializedAnyEme(){return this.initializedEme_;};_proto.ready=function ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme();};_proto.createSourceBuffers=function createSourceBuffers(codecs){if(this.hasCreatedSourceBuffers()){return;}
this.addOrChangeSourceBuffers(codecs);this.createdSourceBuffers_=true;this.trigger('createdsourcebuffers');this.triggerReady();};_proto.triggerReady=function triggerReady(){if(this.ready()&&!this.triggeredReady_){this.triggeredReady_=true;this.trigger('ready');}};_proto.addSourceBuffer=function addSourceBuffer(type,codec){pushQueue({type:'mediaSource',sourceUpdater:this,action:actions.addSourceBuffer(type,codec),name:'addSourceBuffer'});};_proto.abort=function abort(type){pushQueue({type:type,sourceUpdater:this,action:actions.abort(type),name:'abort'});};_proto.removeSourceBuffer=function removeSourceBuffer(type){if(!this.canRemoveSourceBuffer()){videojs$1.log.error('removeSourceBuffer is not supported!');return;}
pushQueue({type:'mediaSource',sourceUpdater:this,action:actions.removeSourceBuffer(type),name:'removeSourceBuffer'});};_proto.canRemoveSourceBuffer=function canRemoveSourceBuffer(){return!videojs$1.browser.IE_VERSION&&!videojs$1.browser.IS_FIREFOX&&window_1$2.MediaSource&&window_1$2.MediaSource.prototype&&typeof window_1$2.MediaSource.prototype.removeSourceBuffer==='function';};SourceUpdater.canChangeType=function canChangeType(){return window_1$2.SourceBuffer&&window_1$2.SourceBuffer.prototype&&typeof window_1$2.SourceBuffer.prototype.changeType==='function';};_proto.canChangeType=function canChangeType(){return this.constructor.canChangeType();};_proto.changeType=function changeType(type,codec){if(!this.canChangeType()){videojs$1.log.error('changeType is not supported!');return;}
pushQueue({type:type,sourceUpdater:this,action:actions.changeType(codec),name:'changeType'});};_proto.addOrChangeSourceBuffers=function addOrChangeSourceBuffers(codecs){var _this2=this;if(!codecs||typeof codecs!=='object'||Object.keys(codecs).length===0){throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');}
Object.keys(codecs).forEach(function(type){var codec=codecs[type];if(!_this2.hasCreatedSourceBuffers()){return _this2.addSourceBuffer(type,codec);}
if(_this2.canChangeType()){_this2.changeType(type,codec);}});};_proto.appendBuffer=function appendBuffer(options,doneFn){var _this3=this;var segmentInfo=options.segmentInfo,type=options.type,bytes=options.bytes;this.processedAppend_=true;if(type==='audio'&&this.videoBuffer&&!this.videoAppendQueued_){this.delayedAudioAppendQueue_.push([options,doneFn]);this.logger_("delayed audio append of "+bytes.length+" until video append");return;}
pushQueue({type:type,sourceUpdater:this,action:actions.appendBuffer(bytes,segmentInfo||{mediaIndex:-1}),doneFn:doneFn,name:'appendBuffer'});if(type==='video'){this.videoAppendQueued_=true;if(!this.delayedAudioAppendQueue_.length){return;}
var queue=this.delayedAudioAppendQueue_.slice();this.logger_("queuing delayed audio "+queue.length+" appendBuffers");this.delayedAudioAppendQueue_.length=0;queue.forEach(function(que){_this3.appendBuffer.apply(_this3,que);});}};_proto.audioBuffered=function audioBuffered(){if(!inSourceBuffers(this.mediaSource,this.audioBuffer)){return videojs$1.createTimeRange();}
return this.audioBuffer.buffered?this.audioBuffer.buffered:videojs$1.createTimeRange();};_proto.videoBuffered=function videoBuffered(){if(!inSourceBuffers(this.mediaSource,this.videoBuffer)){return videojs$1.createTimeRange();}
return this.videoBuffer.buffered?this.videoBuffer.buffered:videojs$1.createTimeRange();};_proto.buffered=function buffered(){var video=inSourceBuffers(this.mediaSource,this.videoBuffer)?this.videoBuffer:null;var audio=inSourceBuffers(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;if(audio&&!video){return this.audioBuffered();}
if(video&&!audio){return this.videoBuffered();}
return bufferIntersection(this.audioBuffered(),this.videoBuffered());};_proto.setDuration=function setDuration(duration,doneFn){if(doneFn===void 0){doneFn=noop$1;}
pushQueue({type:'mediaSource',sourceUpdater:this,action:actions.duration(duration),name:'duration',doneFn:doneFn});};_proto.endOfStream=function endOfStream(error,doneFn){if(error===void 0){error=null;}
if(doneFn===void 0){doneFn=noop$1;}
if(typeof error!=='string'){error=undefined;}
pushQueue({type:'mediaSource',sourceUpdater:this,action:actions.endOfStream(error),name:'endOfStream',doneFn:doneFn});};_proto.removeAudio=function removeAudio(start,end,done){if(done===void 0){done=noop$1;}
if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){done();return;}
pushQueue({type:'audio',sourceUpdater:this,action:actions.remove(start,end),doneFn:done,name:'remove'});};_proto.removeVideo=function removeVideo(start,end,done){if(done===void 0){done=noop$1;}
if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){done();return;}
pushQueue({type:'video',sourceUpdater:this,action:actions.remove(start,end),doneFn:done,name:'remove'});};_proto.updating=function updating(){if(_updating('audio',this)||_updating('video',this)){return true;}
return false;};_proto.audioTimestampOffset=function audioTimestampOffset(offset){if(typeof offset!=='undefined'&&this.audioBuffer&&this.audioTimestampOffset_!==offset){pushQueue({type:'audio',sourceUpdater:this,action:actions.timestampOffset(offset),name:'timestampOffset'});this.audioTimestampOffset_=offset;}
return this.audioTimestampOffset_;};_proto.videoTimestampOffset=function videoTimestampOffset(offset){if(typeof offset!=='undefined'&&this.videoBuffer&&this.videoTimestampOffset!==offset){pushQueue({type:'video',sourceUpdater:this,action:actions.timestampOffset(offset),name:'timestampOffset'});this.videoTimestampOffset_=offset;}
return this.videoTimestampOffset_;};_proto.audioQueueCallback=function audioQueueCallback(callback){if(!this.audioBuffer){return;}
pushQueue({type:'audio',sourceUpdater:this,action:actions.callback(callback),name:'callback'});};_proto.videoQueueCallback=function videoQueueCallback(callback){if(!this.videoBuffer){return;}
pushQueue({type:'video',sourceUpdater:this,action:actions.callback(callback),name:'callback'});};_proto.dispose=function dispose(){var _this4=this;this.trigger('dispose');bufferTypes.forEach(function(type){_this4.abort(type);if(_this4.canRemoveSourceBuffer()){_this4.removeSourceBuffer(type);}else{_this4[type+"QueueCallback"](function(){return cleanupBuffer(type,_this4);});}});this.videoAppendQueued_=false;this.delayedAudioAppendQueue_.length=0;if(this.sourceopenListener_){this.mediaSource.removeEventListener('sourceopen',this.sourceopenListener_);}
this.off();};return SourceUpdater;}(videojs$1.EventTarget);var uint8ToUtf8=function uint8ToUtf8(uintArray){return decodeURIComponent(escape(String.fromCharCode.apply(null,uintArray)));};var VTT_LINE_TERMINATORS=new Uint8Array('\n\n'.split('').map(function(_char3){return _char3.charCodeAt(0);}));var VTTSegmentLoader=function(_SegmentLoader){inheritsLoose$1(VTTSegmentLoader,_SegmentLoader);function VTTSegmentLoader(settings,options){var _this;if(options===void 0){options={};}
_this=_SegmentLoader.call(this,settings,options)||this;_this.handlePartialData_=false;_this.mediaSource_=null;_this.subtitlesTrack_=null;_this.loaderType_='subtitle';_this.featuresNativeTextTracks_=settings.featuresNativeTextTracks;_this.shouldSaveSegmentTimingInfo_=false;return _this;}
var _proto=VTTSegmentLoader.prototype;_proto.createTransmuxer_=function createTransmuxer_(){return null;};_proto.buffered_=function buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues.length){return videojs$1.createTimeRanges();}
var cues=this.subtitlesTrack_.cues;var start=cues[0].startTime;var end=cues[cues.length-1].startTime;return videojs$1.createTimeRanges([[start,end]]);};_proto.initSegmentForMap=function initSegmentForMap(map,set){if(set===void 0){set=false;}
if(!map){return null;}
var id=initSegmentId(map);var storedMap=this.initSegments_[id];if(set&&!storedMap&&map.bytes){var combinedByteLength=VTT_LINE_TERMINATORS.byteLength+map.bytes.byteLength;var 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;};_proto.couldBeginLoading_=function couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused();};_proto.init_=function init_(){this.state='READY';this.resetEverything();return this.monitorBuffer_();};_proto.track=function track(_track){if(typeof _track==='undefined'){return this.subtitlesTrack_;}
this.subtitlesTrack_=_track;if(this.state==='INIT'&&this.couldBeginLoading_()){this.init_();}
return this.subtitlesTrack_;};_proto.remove=function remove(start,end){removeCuesFromTrack(start,end,this.subtitlesTrack_);};_proto.fillBuffer_=function fillBuffer_(){var _this2=this;if(!this.syncPoint_){this.syncPoint_=this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_());}
var segmentInfo=this.checkBuffer_(this.buffered_(),this.playlist_,this.mediaIndex,this.hasPlayed_(),this.currentTime_(),this.syncPoint_);segmentInfo=this.skipEmptySegments_(segmentInfo);if(!segmentInfo){return;}
if(this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline)===null){var checkTimestampOffset=function checkTimestampOffset(){_this2.state='READY';if(!_this2.paused()){_this2.monitorBuffer_();}};this.syncController_.one('timestampoffset',checkTimestampOffset);this.state='WAITING_ON_TIMELINE';return;}
this.loadSegment_(segmentInfo);};_proto.skipEmptySegments_=function skipEmptySegments_(segmentInfo){while(segmentInfo&&segmentInfo.segment.empty){segmentInfo=this.generateSegmentInfo_(segmentInfo.playlist,segmentInfo.mediaIndex+1,segmentInfo.startOfSegment+segmentInfo.duration,segmentInfo.isSyncRequest);}
return segmentInfo;};_proto.stopForError=function stopForError(error){this.error(error);this.state='READY';this.pause();this.trigger('error');};_proto.segmentRequestFinished_=function segmentRequestFinished_(error,simpleSegment,result){var _this3=this;if(!this.subtitlesTrack_){this.state='READY';return;}
this.saveTransferStats_(simpleSegment.stats);if(!this.pendingSegment_){this.state='READY';this.mediaRequestsAborted+=1;return;}
if(error){if(error.code===REQUEST_ERRORS.TIMEOUT){this.handleTimeout_();}
if(error.code===REQUEST_ERRORS.ABORTED){this.mediaRequestsAborted+=1;}else{this.mediaRequestsErrored+=1;}
this.stopForError(error);return;}
var segmentInfo=this.pendingSegment_;this.saveBandwidthRelatedStats_(segmentInfo.duration,simpleSegment.stats);this.state='APPENDING';this.trigger('appending');var segment=segmentInfo.segment;if(segment.map){segment.map.bytes=simpleSegment.map.bytes;}
segmentInfo.bytes=simpleSegment.bytes;if(typeof window_1$2.WebVTT!=='function'&&this.subtitlesTrack_&&this.subtitlesTrack_.tech_){var loadHandler;var errorHandler=function errorHandler(){_this3.subtitlesTrack_.tech_.off('vttjsloaded',loadHandler);_this3.stopForError({message:'Error loading vtt.js'});return;};loadHandler=function loadHandler(){_this3.subtitlesTrack_.tech_.off('vttjserror',errorHandler);_this3.segmentRequestFinished_(error,simpleSegment,result);};this.state='WAITING_ON_VTTJS';this.subtitlesTrack_.tech_.one('vttjsloaded',loadHandler);this.subtitlesTrack_.tech_.one('vttjserror',errorHandler);return;}
segment.requested=true;try{this.parseVTTCues_(segmentInfo);}catch(e){this.stopForError({message:e.message});return;}
this.updateTimeMapping_(segmentInfo,this.syncController_.timelines[segmentInfo.timeline],this.playlist_);if(segmentInfo.cues.length){segmentInfo.timingInfo={start:segmentInfo.cues[0].startTime,end:segmentInfo.cues[segmentInfo.cues.length-1].endTime};}else{segmentInfo.timingInfo={start:segmentInfo.startOfSegment,end:segmentInfo.startOfSegment+segmentInfo.duration};}
if(segmentInfo.isSyncRequest){this.trigger('syncinfoupdate');this.pendingSegment_=null;this.state='READY';return;}
segmentInfo.byteLength=segmentInfo.bytes.byteLength;this.mediaSecondsLoaded+=segment.duration;segmentInfo.cues.forEach(function(cue){_this3.subtitlesTrack_.addCue(_this3.featuresNativeTextTracks_?new window_1$2.VTTCue(cue.startTime,cue.endTime,cue.text):cue);});removeDuplicateCuesFromTrack(this.subtitlesTrack_);this.handleAppendsDone_();};_proto.handleData_=function handleData_(){};_proto.updateTimingInfoEnd_=function updateTimingInfoEnd_(){};_proto.parseVTTCues_=function parseVTTCues_(segmentInfo){var decoder;var decodeBytesToString=false;if(typeof window_1$2.TextDecoder==='function'){decoder=new window_1$2.TextDecoder('utf8');}else{decoder=window_1$2.WebVTT.StringDecoder();decodeBytesToString=true;}
var parser=new window_1$2.WebVTT.Parser(window_1$2,window_1$2.vttjs,decoder);segmentInfo.cues=[];segmentInfo.timestampmap={MPEGTS:0,LOCAL:0};parser.oncue=segmentInfo.cues.push.bind(segmentInfo.cues);parser.ontimestampmap=function(map){segmentInfo.timestampmap=map;};parser.onparsingerror=function(error){videojs$1.log.warn('Error encountered when parsing cues: '+error.message);};if(segmentInfo.segment.map){var mapData=segmentInfo.segment.map.bytes;if(decodeBytesToString){mapData=uint8ToUtf8(mapData);}
parser.parse(mapData);}
var segmentData=segmentInfo.bytes;if(decodeBytesToString){segmentData=uint8ToUtf8(segmentData);}
parser.parse(segmentData);parser.flush();};_proto.updateTimeMapping_=function updateTimeMapping_(segmentInfo,mappingObj,playlist){var segment=segmentInfo.segment;if(!mappingObj){return;}
if(!segmentInfo.cues.length){segment.empty=true;return;}
var timestampmap=segmentInfo.timestampmap;var diff=timestampmap.MPEGTS/clock_1-timestampmap.LOCAL+mappingObj.mapping;segmentInfo.cues.forEach(function(cue){cue.startTime+=diff;cue.endTime+=diff;});if(!playlist.syncInfo){var firstStart=segmentInfo.cues[0].startTime;var lastStart=segmentInfo.cues[segmentInfo.cues.length-1].startTime;playlist.syncInfo={mediaSequence:playlist.mediaSequence+segmentInfo.mediaIndex,time:Math.min(firstStart,lastStart-segment.duration)};}};return VTTSegmentLoader;}(SegmentLoader);var findAdCue=function findAdCue(track,mediaTime){var cues=track.cues;for(var i=0;i<cues.length;i++){var cue=cues[i];if(mediaTime>=cue.adStartTime&&mediaTime<=cue.adEndTime){return cue;}}
return null;};var updateAdCues=function updateAdCues(media,track,offset){if(offset===void 0){offset=0;}
if(!media.segments){return;}
var mediaTime=offset;var cue;for(var i=0;i<media.segments.length;i++){var segment=media.segments[i];if(!cue){cue=findAdCue(track,mediaTime+segment.duration/2);}
if(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_1$2.VTTCue(mediaTime,mediaTime+segment.duration,segment.cueOut);cue.adStartTime=mediaTime;cue.adEndTime=mediaTime+parseFloat(segment.cueOut);track.addCue(cue);}
if('cueOutCont'in segment){var _segment$cueOutCont$s=segment.cueOutCont.split('/').map(parseFloat),adOffset=_segment$cueOutCont$s[0],adTotal=_segment$cueOutCont$s[1];cue=new window_1$2.VTTCue(mediaTime,mediaTime+segment.duration,'');cue.adStartTime=mediaTime-adOffset;cue.adEndTime=cue.adStartTime+adTotal;track.addCue(cue);}}
mediaTime+=segment.duration;}};var syncPointStrategies=[{name:'VOD',run:function run(syncController,playlist,duration,currentTimeline,currentTime){if(duration!==Infinity){var syncPoint={time:0,segmentIndex:0};return syncPoint;}
return null;}},{name:'ProgramDateTime',run:function run(syncController,playlist,duration,currentTimeline,currentTime){if(!syncController.datetimeToDisplayTime){return null;}
var segments=playlist.segments||[];var syncPoint=null;var lastDistance=null;currentTime=currentTime||0;for(var i=0;i<segments.length;i++){var segment=segments[i];if(segment.dateTimeObject){var segmentTime=segment.dateTimeObject.getTime()/1000;var segmentStart=segmentTime+syncController.datetimeToDisplayTime;var distance=Math.abs(currentTime-segmentStart);if(lastDistance!==null&&(distance===0||lastDistance<distance)){break;}
lastDistance=distance;syncPoint={time:segmentStart,segmentIndex:i};}}
return syncPoint;}},{name:'Segment',run:function run(syncController,playlist,duration,currentTimeline,currentTime){var segments=playlist.segments||[];var syncPoint=null;var lastDistance=null;currentTime=currentTime||0;for(var i=0;i<segments.length;i++){var segment=segments[i];if(segment.timeline===currentTimeline&&typeof segment.start!=='undefined'){var distance=Math.abs(currentTime-segment.start);if(lastDistance!==null&&lastDistance<distance){break;}
if(!syncPoint||lastDistance===null||lastDistance>=distance){lastDistance=distance;syncPoint={time:segment.start,segmentIndex:i};}}}
return syncPoint;}},{name:'Discontinuity',run:function run(syncController,playlist,duration,currentTimeline,currentTime){var syncPoint=null;currentTime=currentTime||0;if(playlist.discontinuityStarts&&playlist.discontinuityStarts.length){var lastDistance=null;for(var i=0;i<playlist.discontinuityStarts.length;i++){var segmentIndex=playlist.discontinuityStarts[i];var discontinuity=playlist.discontinuitySequence+i+1;var discontinuitySync=syncController.discontinuities[discontinuity];if(discontinuitySync){var distance=Math.abs(currentTime-discontinuitySync.time);if(lastDistance!==null&&lastDistance<distance){break;}
if(!syncPoint||lastDistance===null||lastDistance>=distance){lastDistance=distance;syncPoint={time:discontinuitySync.time,segmentIndex:segmentIndex};}}}}
return syncPoint;}},{name:'Playlist',run:function run(syncController,playlist,duration,currentTimeline,currentTime){if(playlist.syncInfo){var syncPoint={time:playlist.syncInfo.time,segmentIndex:playlist.syncInfo.mediaSequence-playlist.mediaSequence};return syncPoint;}
return null;}}];var SyncController=function(_videojs$EventTarget){inheritsLoose$1(SyncController,_videojs$EventTarget);function SyncController(options){var _this;_this=_videojs$EventTarget.call(this)||this;_this.timelines=[];_this.discontinuities=[];_this.datetimeToDisplayTime=null;_this.logger_=logger('SyncController');return _this;}
var _proto=SyncController.prototype;_proto.getSyncPoint=function getSyncPoint(playlist,duration,currentTimeline,currentTime){var syncPoints=this.runStrategies_(playlist,duration,currentTimeline,currentTime);if(!syncPoints.length){return null;}
return this.selectSyncPoint_(syncPoints,{key:'time',value:currentTime});};_proto.getExpiredTime=function getExpiredTime(playlist,duration){if(!playlist||!playlist.segments){return null;}
var syncPoints=this.runStrategies_(playlist,duration,playlist.discontinuitySequence,0);if(!syncPoints.length){return null;}
var syncPoint=this.selectSyncPoint_(syncPoints,{key:'segmentIndex',value:0});if(syncPoint.segmentIndex>0){syncPoint.time*=-1;}
return Math.abs(syncPoint.time+sumDurations(playlist,syncPoint.segmentIndex,0));};_proto.runStrategies_=function runStrategies_(playlist,duration,currentTimeline,currentTime){var syncPoints=[];for(var i=0;i<syncPointStrategies.length;i++){var strategy=syncPointStrategies[i];var syncPoint=strategy.run(this,playlist,duration,currentTimeline,currentTime);if(syncPoint){syncPoint.strategy=strategy.name;syncPoints.push({strategy:strategy.name,syncPoint:syncPoint});}}
return syncPoints;};_proto.selectSyncPoint_=function selectSyncPoint_(syncPoints,target){var bestSyncPoint=syncPoints[0].syncPoint;var bestDistance=Math.abs(syncPoints[0].syncPoint[target.key]-target.value);var bestStrategy=syncPoints[0].strategy;for(var i=1;i<syncPoints.length;i++){var newDistance=Math.abs(syncPoints[i].syncPoint[target.key]-target.value);if(newDistance<bestDistance){bestDistance=newDistance;bestSyncPoint=syncPoints[i].syncPoint;bestStrategy=syncPoints[i].strategy;}}
this.logger_("syncPoint for ["+target.key+": "+target.value+"] chosen with strategy"+(" ["+bestStrategy+"]: [time:"+bestSyncPoint.time+",")+(" segmentIndex:"+bestSyncPoint.segmentIndex+"]"));return bestSyncPoint;};_proto.saveExpiredSegmentInfo=function saveExpiredSegmentInfo(oldPlaylist,newPlaylist){var mediaSequenceDiff=newPlaylist.mediaSequence-oldPlaylist.mediaSequence;for(var i=mediaSequenceDiff-1;i>=0;i--){var lastRemovedSegment=oldPlaylist.segments[i];if(lastRemovedSegment&&typeof lastRemovedSegment.start!=='undefined'){newPlaylist.syncInfo={mediaSequence:oldPlaylist.mediaSequence+i,time:lastRemovedSegment.start};this.logger_("playlist refresh sync: [time:"+newPlaylist.syncInfo.time+","+(" mediaSequence: "+newPlaylist.syncInfo.mediaSequence+"]"));this.trigger('syncinfoupdate');break;}}};_proto.setDateTimeMapping=function setDateTimeMapping(playlist){if(!this.datetimeToDisplayTime&&playlist.segments&&playlist.segments.length&&playlist.segments[0].dateTimeObject){var playlistTimestamp=playlist.segments[0].dateTimeObject.getTime()/1000;this.datetimeToDisplayTime=-playlistTimestamp;}};_proto.saveSegmentTimingInfo=function saveSegmentTimingInfo(_ref){var segmentInfo=_ref.segmentInfo,shouldSaveTimelineMapping=_ref.shouldSaveTimelineMapping;var didCalculateSegmentTimeMapping=this.calculateSegmentTimeMapping_(segmentInfo,segmentInfo.timingInfo,shouldSaveTimelineMapping);if(didCalculateSegmentTimeMapping){this.saveDiscontinuitySyncInfo_(segmentInfo);if(!segmentInfo.playlist.syncInfo){segmentInfo.playlist.syncInfo={mediaSequence:segmentInfo.playlist.mediaSequence+segmentInfo.mediaIndex,time:segmentInfo.segment.start};}}};_proto.timestampOffsetForTimeline=function timestampOffsetForTimeline(timeline){if(typeof this.timelines[timeline]==='undefined'){return null;}
return this.timelines[timeline].time;};_proto.mappingForTimeline=function mappingForTimeline(timeline){if(typeof this.timelines[timeline]==='undefined'){return null;}
return this.timelines[timeline].mapping;};_proto.calculateSegmentTimeMapping_=function calculateSegmentTimeMapping_(segmentInfo,timingInfo,shouldSaveTimelineMapping){var segment=segmentInfo.segment;var mappingObj=this.timelines[segmentInfo.timeline];if(segmentInfo.timestampOffset!==null){mappingObj={time:segmentInfo.startOfSegment,mapping:segmentInfo.startOfSegment-timingInfo.start};if(shouldSaveTimelineMapping){this.timelines[segmentInfo.timeline]=mappingObj;this.trigger('timestampoffset');this.logger_("time mapping for timeline "+segmentInfo.timeline+": "+("[time: "+mappingObj.time+"] [mapping: "+mappingObj.mapping+"]"));}
segment.start=segmentInfo.startOfSegment;segment.end=timingInfo.end+mappingObj.mapping;}else if(mappingObj){segment.start=timingInfo.start+mappingObj.mapping;segment.end=timingInfo.end+mappingObj.mapping;}else{return false;}
return true;};_proto.saveDiscontinuitySyncInfo_=function saveDiscontinuitySyncInfo_(segmentInfo){var playlist=segmentInfo.playlist;var segment=segmentInfo.segment;if(segment.discontinuity){this.discontinuities[segment.timeline]={time:segment.start,accuracy:0};}else if(playlist.discontinuityStarts&&playlist.discontinuityStarts.length){for(var i=0;i<playlist.discontinuityStarts.length;i++){var segmentIndex=playlist.discontinuityStarts[i];var discontinuity=playlist.discontinuitySequence+i+1;var mediaIndexDiff=segmentIndex-segmentInfo.mediaIndex;var accuracy=Math.abs(mediaIndexDiff);if(!this.discontinuities[discontinuity]||this.discontinuities[discontinuity].accuracy>accuracy){var time=void 0;if(mediaIndexDiff<0){time=segment.start-sumDurations(playlist,segmentInfo.mediaIndex,segmentIndex);}else{time=segment.end+sumDurations(playlist,segmentInfo.mediaIndex+1,segmentIndex);}
this.discontinuities[discontinuity]={time:time,accuracy:accuracy};}}}};_proto.dispose=function dispose(){this.trigger('dispose');this.off();};return SyncController;}(videojs$1.EventTarget);var TimelineChangeController=function(_videojs$EventTarget){inheritsLoose$1(TimelineChangeController,_videojs$EventTarget);function TimelineChangeController(){var _this;_this=_videojs$EventTarget.call(this)||this;_this.pendingTimelineChanges_={};_this.lastTimelineChanges_={};return _this;}
var _proto=TimelineChangeController.prototype;_proto.clearPendingTimelineChange=function clearPendingTimelineChange(type){this.pendingTimelineChanges_[type]=null;this.trigger('pendingtimelinechange');};_proto.pendingTimelineChange=function pendingTimelineChange(_ref){var type=_ref.type,from=_ref.from,to=_ref.to;if(typeof from==='number'&&typeof to==='number'){this.pendingTimelineChanges_[type]={type:type,from:from,to:to};this.trigger('pendingtimelinechange');}
return this.pendingTimelineChanges_[type];};_proto.lastTimelineChange=function lastTimelineChange(_ref2){var type=_ref2.type,from=_ref2.from,to=_ref2.to;if(typeof from==='number'&&typeof to==='number'){this.lastTimelineChanges_[type]={type:type,from:from,to:to};delete this.pendingTimelineChanges_[type];this.trigger('timelinechange');}
return this.lastTimelineChanges_[type];};_proto.dispose=function dispose(){this.trigger('dispose');this.pendingTimelineChanges_={};this.lastTimelineChanges_={};this.off();};return TimelineChangeController;}(videojs$1.EventTarget);var Decrypter=new shimWorker("./decrypter-worker.worker.js",function(window,document){var self=this;var decrypterWorker=function(){function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}
function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}
var createClass=_createClass;function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype);subClass.prototype.constructor=subClass;subClass.__proto__=superClass;}
var inheritsLoose=_inheritsLoose;var Stream=function(){function Stream(){this.listeners={};}
var _proto=Stream.prototype;_proto.on=function on(type,listener){if(!this.listeners[type]){this.listeners[type]=[];}
this.listeners[type].push(listener);};_proto.off=function off(type,listener){if(!this.listeners[type]){return false;}
var index=this.listeners[type].indexOf(listener);this.listeners[type]=this.listeners[type].slice(0);this.listeners[type].splice(index,1);return index>-1;};_proto.trigger=function trigger(type){var callbacks=this.listeners[type];if(!callbacks){return;}
if(arguments.length===2){var length=callbacks.length;for(var i=0;i<length;++i){callbacks[i].call(this,arguments[1]);}}else{var args=Array.prototype.slice.call(arguments,1);var _length=callbacks.length;for(var _i=0;_i<_length;++_i){callbacks[_i].apply(this,args);}}};_proto.dispose=function dispose(){this.listeners={};};_proto.pipe=function pipe(destination){this.on('data',function(data){destination.push(data);});};return Stream;}();var stream=Stream;function unpad(padded){return padded.subarray(0,padded.byteLength-padded[padded.byteLength-1]);}
var precompute=function precompute(){var tables=[[[],[],[],[],[]],[[],[],[],[],[]]];var encTable=tables[0];var decTable=tables[1];var sbox=encTable[4];var sboxInv=decTable[4];var i;var x;var xInv;var d=[];var th=[];var x2;var x4;var x8;var s;var tEnc;var tDec;for(i=0;i<256;i++){th[(d[i]=i<<1^(i>>7)*283)^i]=i;}
for(x=xInv=0;!sbox[x];x^=x2||1,xInv=th[xInv]||1){s=xInv^xInv<<1^xInv<<2^xInv<<3^xInv<<4;s=s>>8^s&255^99;sbox[x]=s;sboxInv[s]=x;x8=d[x4=d[x2=d[x]]];tDec=x8*0x1010101^x4*0x10001^x2*0x101^x*0x1010100;tEnc=d[s]*0x101^s*0x1010100;for(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;};var aesTables=null;var AES=function(){function AES(key){if(!aesTables){aesTables=precompute();}
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()]];var i;var j;var tmp;var sbox=this._tables[0][4];var decTable=this._tables[1];var keyLen=key.length;var rcon=1;if(keyLen!==4&&keyLen!==6&&keyLen!==8){throw new Error('Invalid aes key size');}
var encKey=key.slice(0);var decKey=[];this._key=[encKey,decKey];for(i=keyLen;i<4*keyLen+28;i++){tmp=encKey[i-1];if(i%keyLen===0||keyLen===8&&i%keyLen===4){tmp=sbox[tmp>>>24]<<24^sbox[tmp>>16&255]<<16^sbox[tmp>>8&255]<<8^sbox[tmp&255];if(i%keyLen===0){tmp=tmp<<8^tmp>>>24^rcon<<24;rcon=rcon<<1^(rcon>>7)*283;}}
encKey[i]=encKey[i-keyLen]^tmp;}
for(j=0;i;j++,i--){tmp=encKey[j&3?i:i-4];if(i<=4||j<4){decKey[j]=tmp;}else{decKey[j]=decTable[0][sbox[tmp>>>24]]^decTable[1][sbox[tmp>>16&255]]^decTable[2][sbox[tmp>>8&255]]^decTable[3][sbox[tmp&255]];}}}
var _proto=AES.prototype;_proto.decrypt=function decrypt(encrypted0,encrypted1,encrypted2,encrypted3,out,offset){var key=this._key[1];var a=encrypted0^key[0];var b=encrypted3^key[1];var c=encrypted2^key[2];var d=encrypted1^key[3];var a2;var b2;var c2;var nInnerRounds=key.length/4-2;var i;var kIndex=4;var table=this._tables[1];var table0=table[0];var table1=table[1];var table2=table[2];var table3=table[3];var sbox=table[4];for(i=0;i<nInnerRounds;i++){a2=table0[a>>>24]^table1[b>>16&255]^table2[c>>8&255]^table3[d&255]^key[kIndex];b2=table0[b>>>24]^table1[c>>16&255]^table2[d>>8&255]^table3[a&255]^key[kIndex+1];c2=table0[c>>>24]^table1[d>>16&255]^table2[a>>8&255]^table3[b&255]^key[kIndex+2];d=table0[d>>>24]^table1[a>>16&255]^table2[b>>8&255]^table3[c&255]^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[d&255]^key[kIndex++];a2=a;a=b;b=c;c=d;d=a2;}};return AES;}();var AsyncStream=function(_Stream){inheritsLoose(AsyncStream,_Stream);function AsyncStream(){var _this;_this=_Stream.call(this,stream)||this;_this.jobs=[];_this.delay=1;_this.timeout_=null;return _this;}
var _proto=AsyncStream.prototype;_proto.processJob_=function processJob_(){this.jobs.shift()();if(this.jobs.length){this.timeout_=setTimeout(this.processJob_.bind(this),this.delay);}else{this.timeout_=null;}};_proto.push=function push(job){this.jobs.push(job);if(!this.timeout_){this.timeout_=setTimeout(this.processJob_.bind(this),this.delay);}};return AsyncStream;}(stream);var ntoh=function ntoh(word){return word<<24|(word&0xff00)<<8|(word&0xff0000)>>8|word>>>24;};var decrypt=function decrypt(encrypted,key,initVector){var encrypted32=new Int32Array(encrypted.buffer,encrypted.byteOffset,encrypted.byteLength>>2);var decipher=new AES(Array.prototype.slice.call(key));var decrypted=new Uint8Array(encrypted.byteLength);var decrypted32=new Int32Array(decrypted.buffer);var init0;var init1;var init2;var init3;var encrypted0;var encrypted1;var encrypted2;var encrypted3;var wordIx;init0=initVector[0];init1=initVector[1];init2=initVector[2];init3=initVector[3];for(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;};var Decrypter=function(){function Decrypter(encrypted,key,initVector,done){var step=Decrypter.STEP;var encrypted32=new Int32Array(encrypted.buffer);var decrypted=new Uint8Array(encrypted.byteLength);var i=0;this.asyncStream_=new AsyncStream();this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i,i+step),key,initVector,decrypted));for(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(){done(null,unpad(decrypted));});}
var _proto=Decrypter.prototype;_proto.decryptChunk_=function decryptChunk_(encrypted,key,initVector,decrypted){return function(){var bytes=decrypt(encrypted,key,initVector);decrypted.set(bytes,encrypted.byteOffset);};};createClass(Decrypter,null,[{key:"STEP",get:function get(){return 32000;}}]);return Decrypter;}();var createTransferableMessage=function createTransferableMessage(message){var transferable={};Object.keys(message).forEach(function(key){var value=message[key];if(ArrayBuffer.isView(value)){transferable[key]={bytes:value.buffer,byteOffset:value.byteOffset,byteLength:value.byteLength};}else{transferable[key]=value;}});return transferable;};var DecrypterWorker=function DecrypterWorker(self){self.onmessage=function(event){var data=event.data;var encrypted=new Uint8Array(data.encrypted.bytes,data.encrypted.byteOffset,data.encrypted.byteLength);var key=new Uint32Array(data.key.bytes,data.key.byteOffset,data.key.byteLength/4);var 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 decrypterWorker=new DecrypterWorker(self);return decrypterWorker;}();});var audioTrackKind_=function audioTrackKind_(properties){var kind=properties["default"]?'main':'alternative';if(properties.characteristics&&properties.characteristics.indexOf('public.accessibility.describes-video')>=0){kind='main-desc';}
return kind;};var stopLoaders=function stopLoaders(segmentLoader,mediaType){segmentLoader.abort();segmentLoader.pause();if(mediaType&&mediaType.activePlaylistLoader){mediaType.activePlaylistLoader.pause();mediaType.activePlaylistLoader=null;}};var startLoaders=function startLoaders(playlistLoader,mediaType){mediaType.activePlaylistLoader=playlistLoader;playlistLoader.load();};var onGroupChanged=function onGroupChanged(type,settings){return function(){var _settings$segmentLoad=settings.segmentLoaders,segmentLoader=_settings$segmentLoad[type],mainSegmentLoader=_settings$segmentLoad.main,mediaType=settings.mediaTypes[type];var activeTrack=mediaType.activeTrack();var activeGroup=mediaType.activeGroup(activeTrack);var previousActiveLoader=mediaType.activePlaylistLoader;stopLoaders(segmentLoader,mediaType);if(!activeGroup){return;}
if(!activeGroup.playlistLoader){if(previousActiveLoader){mainSegmentLoader.resetEverything();}
return;}
segmentLoader.resyncLoader();startLoaders(activeGroup.playlistLoader,mediaType);};};var onGroupChanging=function onGroupChanging(type,settings){return function(){var segmentLoader=settings.segmentLoaders[type];segmentLoader.abort();segmentLoader.pause();};};var onTrackChanged=function onTrackChanged(type,settings){return function(){var _settings$segmentLoad2=settings.segmentLoaders,segmentLoader=_settings$segmentLoad2[type],mainSegmentLoader=_settings$segmentLoad2.main,mediaType=settings.mediaTypes[type];var activeTrack=mediaType.activeTrack();var activeGroup=mediaType.activeGroup(activeTrack);var previousActiveLoader=mediaType.activePlaylistLoader;stopLoaders(segmentLoader,mediaType);if(!activeGroup){return;}
if(type==='AUDIO'){if(!activeGroup.playlistLoader){mainSegmentLoader.setAudio(true);mainSegmentLoader.resetEverything();return;}
segmentLoader.setAudio(true);mainSegmentLoader.setAudio(false);}
if(previousActiveLoader===activeGroup.playlistLoader){startLoaders(activeGroup.playlistLoader,mediaType);return;}
if(segmentLoader.track){segmentLoader.track(activeTrack);}
segmentLoader.resetEverything();startLoaders(activeGroup.playlistLoader,mediaType);};};var onError={AUDIO:function AUDIO(type,settings){return function(){var segmentLoader=settings.segmentLoaders[type],mediaType=settings.mediaTypes[type],blacklistCurrentPlaylist=settings.blacklistCurrentPlaylist;stopLoaders(segmentLoader,mediaType);var activeTrack=mediaType.activeTrack();var activeGroup=mediaType.activeGroup();var id=(activeGroup.filter(function(group){return group["default"];})[0]||activeGroup[0]).id;var defaultTrack=mediaType.tracks[id];if(activeTrack===defaultTrack){blacklistCurrentPlaylist({message:'Problem encountered loading the default audio track.'});return;}
videojs$1.log.warn('Problem encountered loading the alternate audio track.'+'Switching back to default.');for(var trackId in mediaType.tracks){mediaType.tracks[trackId].enabled=mediaType.tracks[trackId]===defaultTrack;}
mediaType.onTrackChanged();};},SUBTITLES:function SUBTITLES(type,settings){return function(){var segmentLoader=settings.segmentLoaders[type],mediaType=settings.mediaTypes[type];videojs$1.log.warn('Problem encountered loading the subtitle track.'+'Disabling subtitle track.');stopLoaders(segmentLoader,mediaType);var track=mediaType.activeTrack();if(track){track.mode='disabled';}
mediaType.onTrackChanged();};}};var setupListeners={AUDIO:function AUDIO(type,playlistLoader,settings){if(!playlistLoader){return;}
var tech=settings.tech,requestOptions=settings.requestOptions,segmentLoader=settings.segmentLoaders[type];playlistLoader.on('loadedmetadata',function(){var media=playlistLoader.media();segmentLoader.playlist(media,requestOptions);if(!tech.paused()||media.endList&&tech.preload()!=='none'){segmentLoader.load();}});playlistLoader.on('loadedplaylist',function(){segmentLoader.playlist(playlistLoader.media(),requestOptions);if(!tech.paused()){segmentLoader.load();}});playlistLoader.on('error',onError[type](type,settings));},SUBTITLES:function SUBTITLES(type,playlistLoader,settings){var tech=settings.tech,requestOptions=settings.requestOptions,segmentLoader=settings.segmentLoaders[type],mediaType=settings.mediaTypes[type];playlistLoader.on('loadedmetadata',function(){var media=playlistLoader.media();segmentLoader.playlist(media,requestOptions);segmentLoader.track(mediaType.activeTrack());if(!tech.paused()||media.endList&&tech.preload()!=='none'){segmentLoader.load();}});playlistLoader.on('loadedplaylist',function(){segmentLoader.playlist(playlistLoader.media(),requestOptions);if(!tech.paused()){segmentLoader.load();}});playlistLoader.on('error',onError[type](type,settings));}};var initialize={'AUDIO':function AUDIO(type,settings){var vhs=settings.vhs,sourceType=settings.sourceType,segmentLoader=settings.segmentLoaders[type],requestOptions=settings.requestOptions,_settings$master=settings.master,mediaGroups=_settings$master.mediaGroups,playlists=_settings$master.playlists,_settings$mediaTypes$=settings.mediaTypes[type],groups=_settings$mediaTypes$.groups,tracks=_settings$mediaTypes$.tracks,masterPlaylistLoader=settings.masterPlaylistLoader;if(!mediaGroups[type]||Object.keys(mediaGroups[type]).length===0){mediaGroups[type]={main:{"default":{"default":true}}};}
var _loop=function _loop(groupId){if(!groups[groupId]){groups[groupId]=[];}
var groupPlaylists=playlists.filter(function(playlist){return playlist.attributes[type]===groupId;});var _loop2=function _loop2(variantLabel){var properties=mediaGroups[type][groupId][variantLabel];var unmatchingPlaylists=groupPlaylists.filter(function(playlist){return playlist.resolvedUri!==properties.resolvedUri;});if(!unmatchingPlaylists.length&&groupPlaylists.length){delete properties.resolvedUri;}
var playlistLoader=void 0;if(sourceType==='vhs-json'&&properties.playlists){playlistLoader=new PlaylistLoader(properties.playlists[0],vhs,requestOptions);}else if(properties.resolvedUri){playlistLoader=new PlaylistLoader(properties.resolvedUri,vhs,requestOptions);}else if(properties.playlists&&sourceType==='dash'){playlistLoader=new DashPlaylistLoader(properties.playlists[0],vhs,requestOptions,masterPlaylistLoader);}else{playlistLoader=null;}
properties=videojs$1.mergeOptions({id:variantLabel,playlistLoader:playlistLoader},properties);setupListeners[type](type,properties.playlistLoader,settings);groups[groupId].push(properties);if(typeof tracks[variantLabel]==='undefined'){var track=new videojs$1.AudioTrack({id:variantLabel,kind:audioTrackKind_(properties),enabled:false,language:properties.language,"default":properties["default"],label:variantLabel});tracks[variantLabel]=track;}};for(var variantLabel in mediaGroups[type][groupId]){_loop2(variantLabel);}};for(var groupId in mediaGroups[type]){_loop(groupId);}
segmentLoader.on('error',onError[type](type,settings));},'SUBTITLES':function SUBTITLES(type,settings){var tech=settings.tech,vhs=settings.vhs,sourceType=settings.sourceType,segmentLoader=settings.segmentLoaders[type],requestOptions=settings.requestOptions,mediaGroups=settings.master.mediaGroups,_settings$mediaTypes$2=settings.mediaTypes[type],groups=_settings$mediaTypes$2.groups,tracks=_settings$mediaTypes$2.tracks,masterPlaylistLoader=settings.masterPlaylistLoader;for(var groupId in mediaGroups[type]){if(!groups[groupId]){groups[groupId]=[];}
for(var variantLabel in mediaGroups[type][groupId]){if(mediaGroups[type][groupId][variantLabel].forced){continue;}
var properties=mediaGroups[type][groupId][variantLabel];var playlistLoader=void 0;if(sourceType==='hls'){playlistLoader=new PlaylistLoader(properties.resolvedUri,vhs,requestOptions);}else if(sourceType==='dash'){var playlists=properties.playlists.filter(function(p){return p.excludeUntil!==Infinity;});if(!playlists.length){return;}
playlistLoader=new DashPlaylistLoader(properties.playlists[0],vhs,requestOptions,masterPlaylistLoader);}else if(sourceType==='vhs-json'){playlistLoader=new PlaylistLoader(properties.playlists?properties.playlists[0]:properties.resolvedUri,vhs,requestOptions);}
properties=videojs$1.mergeOptions({id:variantLabel,playlistLoader:playlistLoader},properties);setupListeners[type](type,properties.playlistLoader,settings);groups[groupId].push(properties);if(typeof tracks[variantLabel]==='undefined'){var track=tech.addRemoteTextTrack({id:variantLabel,kind:'subtitles',"default":properties["default"]&&properties.autoselect,language:properties.language,label:variantLabel},false).track;tracks[variantLabel]=track;}}}
segmentLoader.on('error',onError[type](type,settings));},'CLOSED-CAPTIONS':function CLOSEDCAPTIONS(type,settings){var tech=settings.tech,mediaGroups=settings.master.mediaGroups,_settings$mediaTypes$3=settings.mediaTypes[type],groups=_settings$mediaTypes$3.groups,tracks=_settings$mediaTypes$3.tracks;for(var groupId in mediaGroups[type]){if(!groups[groupId]){groups[groupId]=[];}
for(var variantLabel in mediaGroups[type][groupId]){var properties=mediaGroups[type][groupId][variantLabel];if(!properties.instreamId.match(/CC\d/)){continue;}
groups[groupId].push(videojs$1.mergeOptions({id:variantLabel},properties));if(typeof tracks[variantLabel]==='undefined'){var track=tech.addRemoteTextTrack({id:properties.instreamId,kind:'captions',"default":properties["default"]&&properties.autoselect,language:properties.language,label:variantLabel},false).track;tracks[variantLabel]=track;}}}}};var activeGroup=function activeGroup(type,settings){return function(track){var masterPlaylistLoader=settings.masterPlaylistLoader,groups=settings.mediaTypes[type].groups;var media=masterPlaylistLoader.media();if(!media){return null;}
var variants=null;if(media.attributes[type]){variants=groups[media.attributes[type]];}
variants=variants||groups.main;if(typeof track==='undefined'){return variants;}
if(track===null){return null;}
return variants.filter(function(props){return props.id===track.id;})[0]||null;};};var activeTrack={AUDIO:function AUDIO(type,settings){return function(){var tracks=settings.mediaTypes[type].tracks;for(var id in tracks){if(tracks[id].enabled){return tracks[id];}}
return null;};},SUBTITLES:function SUBTITLES(type,settings){return function(){var tracks=settings.mediaTypes[type].tracks;for(var id in tracks){if(tracks[id].mode==='showing'||tracks[id].mode==='hidden'){return tracks[id];}}
return null;};}};var setupMediaGroups=function setupMediaGroups(settings){['AUDIO','SUBTITLES','CLOSED-CAPTIONS'].forEach(function(type){initialize[type](type,settings);});var mediaTypes=settings.mediaTypes,masterPlaylistLoader=settings.masterPlaylistLoader,tech=settings.tech,vhs=settings.vhs;['AUDIO','SUBTITLES'].forEach(function(type){mediaTypes[type].activeGroup=activeGroup(type,settings);mediaTypes[type].activeTrack=activeTrack[type](type,settings);mediaTypes[type].onGroupChanged=onGroupChanged(type,settings);mediaTypes[type].onGroupChanging=onGroupChanging(type,settings);mediaTypes[type].onTrackChanged=onTrackChanged(type,settings);});var audioGroup=mediaTypes.AUDIO.activeGroup();if(audioGroup){var groupId=(audioGroup.filter(function(group){return group["default"];})[0]||audioGroup[0]).id;mediaTypes.AUDIO.tracks[groupId].enabled=true;mediaTypes.AUDIO.onTrackChanged();}
masterPlaylistLoader.on('mediachange',function(){['AUDIO','SUBTITLES'].forEach(function(type){return mediaTypes[type].onGroupChanged();});});masterPlaylistLoader.on('mediachanging',function(){['AUDIO','SUBTITLES'].forEach(function(type){return mediaTypes[type].onGroupChanging();});});var onAudioTrackChanged=function onAudioTrackChanged(){mediaTypes.AUDIO.onTrackChanged();tech.trigger({type:'usage',name:'vhs-audio-change'});tech.trigger({type:'usage',name:'hls-audio-change'});};tech.audioTracks().addEventListener('change',onAudioTrackChanged);tech.remoteTextTracks().addEventListener('change',mediaTypes.SUBTITLES.onTrackChanged);vhs.on('dispose',function(){tech.audioTracks().removeEventListener('change',onAudioTrackChanged);tech.remoteTextTracks().removeEventListener('change',mediaTypes.SUBTITLES.onTrackChanged);});tech.clearTracks('audio');for(var id in mediaTypes.AUDIO.tracks){tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);}};var createMediaTypes=function createMediaTypes(){var mediaTypes={};['AUDIO','SUBTITLES','CLOSED-CAPTIONS'].forEach(function(type){mediaTypes[type]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:noop$1,activeTrack:noop$1,onGroupChanged:noop$1,onTrackChanged:noop$1};});return mediaTypes;};var ABORT_EARLY_BLACKLIST_SECONDS=60*2;var Vhs;var loaderStats=['mediaRequests','mediaRequestsAborted','mediaRequestsTimedout','mediaRequestsErrored','mediaTransferDuration','mediaBytesTransferred'];var sumLoaderStat=function sumLoaderStat(stat){return this.audioSegmentLoader_[stat]+this.mainSegmentLoader_[stat];};var shouldSwitchToMedia=function shouldSwitchToMedia(_ref){var currentPlaylist=_ref.currentPlaylist,nextPlaylist=_ref.nextPlaylist,forwardBuffer=_ref.forwardBuffer,bufferLowWaterLine=_ref.bufferLowWaterLine,bufferHighWaterLine=_ref.bufferHighWaterLine,duration=_ref.duration,experimentalBufferBasedABR=_ref.experimentalBufferBasedABR,log=_ref.log;if(!nextPlaylist){videojs$1.log.warn('We received no playlist to switch to. Please check your stream.');return false;}
var sharedLogLine="allowing switch "+(currentPlaylist&&currentPlaylist.id||'null')+" -> "+nextPlaylist.id;if(!currentPlaylist||!currentPlaylist.endList){log(sharedLogLine+" as current playlist "+(!currentPlaylist?'is not set':'is live'));return true;}
if(nextPlaylist.id===currentPlaylist.id){return false;}
var maxBufferLowWaterLine=experimentalBufferBasedABR?Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:Config.MAX_BUFFER_LOW_WATER_LINE;if(duration<maxBufferLowWaterLine){log(sharedLogLine+" as duration < max low water line ("+duration+" < "+maxBufferLowWaterLine+")");return true;}
var nextBandwidth=nextPlaylist.attributes.BANDWIDTH;var currBandwidth=currentPlaylist.attributes.BANDWIDTH;if(nextBandwidth<currBandwidth&&(!experimentalBufferBasedABR||forwardBuffer<bufferHighWaterLine)){var logLine=sharedLogLine+" as next bandwidth < current bandwidth ("+nextBandwidth+" < "+currBandwidth+")";if(experimentalBufferBasedABR){logLine+=" and forwardBuffer < bufferHighWaterLine ("+forwardBuffer+" < "+bufferHighWaterLine+")";}
log(logLine);return true;}
if((!experimentalBufferBasedABR||nextBandwidth>currBandwidth)&&forwardBuffer>=bufferLowWaterLine){var _logLine=sharedLogLine+" as forwardBuffer >= bufferLowWaterLine ("+forwardBuffer+" >= "+bufferLowWaterLine+")";if(experimentalBufferBasedABR){_logLine+=" and next bandwidth > current bandwidth ("+nextBandwidth+" > "+currBandwidth+")";}
log(_logLine);return true;}
log("not "+sharedLogLine+" as no switching criteria met");return false;};var MasterPlaylistController=function(_videojs$EventTarget){inheritsLoose$1(MasterPlaylistController,_videojs$EventTarget);function MasterPlaylistController(options){var _this;_this=_videojs$EventTarget.call(this)||this;var src=options.src,handleManifestRedirects=options.handleManifestRedirects,withCredentials=options.withCredentials,tech=options.tech,bandwidth=options.bandwidth,externVhs=options.externVhs,useCueTags=options.useCueTags,blacklistDuration=options.blacklistDuration,enableLowInitialPlaylist=options.enableLowInitialPlaylist,sourceType=options.sourceType,cacheEncryptionKeys=options.cacheEncryptionKeys,handlePartialData=options.handlePartialData,experimentalBufferBasedABR=options.experimentalBufferBasedABR;if(!src){throw new Error('A non-empty playlist URL or JSON manifest string is required');}
Vhs=externVhs;_this.experimentalBufferBasedABR=Boolean(experimentalBufferBasedABR);_this.withCredentials=withCredentials;_this.tech_=tech;_this.vhs_=tech.vhs;_this.sourceType_=sourceType;_this.useCueTags_=useCueTags;_this.blacklistDuration=blacklistDuration;_this.enableLowInitialPlaylist=enableLowInitialPlaylist;if(_this.useCueTags_){_this.cueTagsTrack_=_this.tech_.addTextTrack('metadata','ad-cues');_this.cueTagsTrack_.inBandMetadataTrackDispatchType='';}
_this.requestOptions_={withCredentials:withCredentials,handleManifestRedirects:handleManifestRedirects,timeout:null};_this.on('error',_this.pauseLoading);_this.mediaTypes_=createMediaTypes();_this.mediaSource=new window_1$2.MediaSource();_this.handleDurationChange_=_this.handleDurationChange_.bind(assertThisInitialized$1(_this));_this.handleSourceOpen_=_this.handleSourceOpen_.bind(assertThisInitialized$1(_this));_this.handleSourceEnded_=_this.handleSourceEnded_.bind(assertThisInitialized$1(_this));_this.mediaSource.addEventListener('durationchange',_this.handleDurationChange_);_this.mediaSource.addEventListener('sourceopen',_this.handleSourceOpen_);_this.mediaSource.addEventListener('sourceended',_this.handleSourceEnded_);_this.seekable_=videojs$1.createTimeRanges();_this.hasPlayed_=false;_this.syncController_=new SyncController(options);_this.segmentMetadataTrack_=tech.addRemoteTextTrack({kind:'metadata',label:'segment-metadata'},false).track;_this.decrypter_=new Decrypter();_this.sourceUpdater_=new SourceUpdater(_this.mediaSource);_this.inbandTextTracks_={};_this.timelineChangeController_=new TimelineChangeController();var segmentLoaderSettings={vhs:_this.vhs_,mediaSource:_this.mediaSource,currentTime:_this.tech_.currentTime.bind(_this.tech_),seekable:function seekable(){return _this.seekable();},seeking:function seeking(){return _this.tech_.seeking();},duration:function duration(){return _this.duration();},hasPlayed:function hasPlayed(){return _this.hasPlayed_;},goalBufferLength:function goalBufferLength(){return _this.goalBufferLength();},bandwidth:bandwidth,syncController:_this.syncController_,decrypter:_this.decrypter_,sourceType:_this.sourceType_,inbandTextTracks:_this.inbandTextTracks_,cacheEncryptionKeys:cacheEncryptionKeys,handlePartialData:handlePartialData,sourceUpdater:_this.sourceUpdater_,timelineChangeController:_this.timelineChangeController_};_this.masterPlaylistLoader_=_this.sourceType_==='dash'?new DashPlaylistLoader(src,_this.vhs_,_this.requestOptions_):new PlaylistLoader(src,_this.vhs_,_this.requestOptions_);_this.setupMasterPlaylistLoaderListeners_();_this.mainSegmentLoader_=new SegmentLoader(videojs$1.mergeOptions(segmentLoaderSettings,{segmentMetadataTrack:_this.segmentMetadataTrack_,loaderType:'main'}),options);_this.audioSegmentLoader_=new SegmentLoader(videojs$1.mergeOptions(segmentLoaderSettings,{loaderType:'audio'}),options);_this.subtitleSegmentLoader_=new VTTSegmentLoader(videojs$1.mergeOptions(segmentLoaderSettings,{loaderType:'vtt',featuresNativeTextTracks:_this.tech_.featuresNativeTextTracks}),options);_this.setupSegmentLoaderListeners_();if(_this.experimentalBufferBasedABR){_this.masterPlaylistLoader_.one('loadedplaylist',function(){return _this.startABRTimer_();});_this.tech_.on('pause',function(){return _this.stopABRTimer_();});_this.tech_.on('play',function(){return _this.startABRTimer_();});}
loaderStats.forEach(function(stat){_this[stat+'_']=sumLoaderStat.bind(assertThisInitialized$1(_this),stat);});_this.logger_=logger('MPC');_this.triggeredFmp4Usage=false;_this.masterPlaylistLoader_.load();return _this;}
var _proto=MasterPlaylistController.prototype;_proto.checkABR_=function checkABR_(){var nextPlaylist=this.selectPlaylist();if(this.shouldSwitchToMedia_(nextPlaylist)){this.masterPlaylistLoader_.media(nextPlaylist);}};_proto.startABRTimer_=function startABRTimer_(){var _this2=this;this.stopABRTimer_();this.abrTimer_=window_1$2.setInterval(function(){return _this2.checkABR_();},250);};_proto.stopABRTimer_=function stopABRTimer_(){if(this.tech_.scrubbing&&this.tech_.scrubbing()){return;}
window_1$2.clearInterval(this.abrTimer_);this.abrTimer_=null;};_proto.setupMasterPlaylistLoaderListeners_=function setupMasterPlaylistLoaderListeners_(){var _this3=this;this.masterPlaylistLoader_.on('loadedmetadata',function(){var media=_this3.masterPlaylistLoader_.media();var requestTimeout=media.targetDuration*1.5*1000;if(isLowestEnabledRendition(_this3.masterPlaylistLoader_.master,_this3.masterPlaylistLoader_.media())){_this3.requestOptions_.timeout=0;}else{_this3.requestOptions_.timeout=requestTimeout;}
if(media.endList&&_this3.tech_.preload()!=='none'){_this3.mainSegmentLoader_.playlist(media,_this3.requestOptions_);_this3.mainSegmentLoader_.load();}
setupMediaGroups({sourceType:_this3.sourceType_,segmentLoaders:{AUDIO:_this3.audioSegmentLoader_,SUBTITLES:_this3.subtitleSegmentLoader_,main:_this3.mainSegmentLoader_},tech:_this3.tech_,requestOptions:_this3.requestOptions_,masterPlaylistLoader:_this3.masterPlaylistLoader_,vhs:_this3.vhs_,master:_this3.master(),mediaTypes:_this3.mediaTypes_,blacklistCurrentPlaylist:_this3.blacklistCurrentPlaylist.bind(_this3)});_this3.triggerPresenceUsage_(_this3.master(),media);_this3.setupFirstPlay();if(!_this3.mediaTypes_.AUDIO.activePlaylistLoader||_this3.mediaTypes_.AUDIO.activePlaylistLoader.media()){_this3.trigger('selectedinitialmedia');}else{_this3.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata',function(){_this3.trigger('selectedinitialmedia');});}});this.masterPlaylistLoader_.on('loadedplaylist',function(){var updatedPlaylist=_this3.masterPlaylistLoader_.media();if(!updatedPlaylist){_this3.excludeUnsupportedVariants_();var selectedMedia;if(_this3.enableLowInitialPlaylist){selectedMedia=_this3.selectInitialPlaylist();}
if(!selectedMedia){selectedMedia=_this3.selectPlaylist();}
if(!selectedMedia||!_this3.shouldSwitchToMedia_(selectedMedia)){return;}
_this3.initialMedia_=selectedMedia;_this3.masterPlaylistLoader_.media(_this3.initialMedia_);var haveJsonSource=_this3.sourceType_==='vhs-json'&&_this3.initialMedia_.segments;if(!haveJsonSource){return;}
updatedPlaylist=_this3.initialMedia_;}
_this3.handleUpdatedMediaPlaylist(updatedPlaylist);});this.masterPlaylistLoader_.on('error',function(){_this3.blacklistCurrentPlaylist(_this3.masterPlaylistLoader_.error);});this.masterPlaylistLoader_.on('mediachanging',function(){_this3.mainSegmentLoader_.abort();_this3.mainSegmentLoader_.pause();});this.masterPlaylistLoader_.on('mediachange',function(){var media=_this3.masterPlaylistLoader_.media();var requestTimeout=media.targetDuration*1.5*1000;if(isLowestEnabledRendition(_this3.masterPlaylistLoader_.master,_this3.masterPlaylistLoader_.media())){_this3.requestOptions_.timeout=0;}else{_this3.requestOptions_.timeout=requestTimeout;}
_this3.mainSegmentLoader_.playlist(media,_this3.requestOptions_);_this3.mainSegmentLoader_.load();_this3.tech_.trigger({type:'mediachange',bubbles:true});});this.masterPlaylistLoader_.on('playlistunchanged',function(){var updatedPlaylist=_this3.masterPlaylistLoader_.media();var playlistOutdated=_this3.stuckAtPlaylistEnd_(updatedPlaylist);if(playlistOutdated){_this3.blacklistCurrentPlaylist({message:'Playlist no longer updating.'});_this3.tech_.trigger('playliststuck');}});this.masterPlaylistLoader_.on('renditiondisabled',function(){_this3.tech_.trigger({type:'usage',name:'vhs-rendition-disabled'});_this3.tech_.trigger({type:'usage',name:'hls-rendition-disabled'});});this.masterPlaylistLoader_.on('renditionenabled',function(){_this3.tech_.trigger({type:'usage',name:'vhs-rendition-enabled'});_this3.tech_.trigger({type:'usage',name:'hls-rendition-enabled'});});};_proto.handleUpdatedMediaPlaylist=function handleUpdatedMediaPlaylist(updatedPlaylist){if(this.useCueTags_){this.updateAdCues_(updatedPlaylist);}
this.mainSegmentLoader_.playlist(updatedPlaylist,this.requestOptions_);this.updateDuration(!updatedPlaylist.endList);if(!this.tech_.paused()){this.mainSegmentLoader_.load();if(this.audioSegmentLoader_){this.audioSegmentLoader_.load();}}};_proto.triggerPresenceUsage_=function triggerPresenceUsage_(master,media){var mediaGroups=master.mediaGroups||{};var defaultDemuxed=true;var audioGroupKeys=Object.keys(mediaGroups.AUDIO);for(var mediaGroup in mediaGroups.AUDIO){for(var label in mediaGroups.AUDIO[mediaGroup]){var properties=mediaGroups.AUDIO[mediaGroup][label];if(!properties.uri){defaultDemuxed=false;}}}
if(defaultDemuxed){this.tech_.trigger({type:'usage',name:'vhs-demuxed'});this.tech_.trigger({type:'usage',name:'hls-demuxed'});}
if(Object.keys(mediaGroups.SUBTITLES).length){this.tech_.trigger({type:'usage',name:'vhs-webvtt'});this.tech_.trigger({type:'usage',name:'hls-webvtt'});}
if(Vhs.Playlist.isAes(media)){this.tech_.trigger({type:'usage',name:'vhs-aes'});this.tech_.trigger({type:'usage',name:'hls-aes'});}
if(audioGroupKeys.length&&Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length>1){this.tech_.trigger({type:'usage',name:'vhs-alternate-audio'});this.tech_.trigger({type:'usage',name:'hls-alternate-audio'});}
if(this.useCueTags_){this.tech_.trigger({type:'usage',name:'vhs-playlist-cue-tags'});this.tech_.trigger({type:'usage',name:'hls-playlist-cue-tags'});}};_proto.shouldSwitchToMedia_=function shouldSwitchToMedia_(nextPlaylist){var currentPlaylist=this.masterPlaylistLoader_.media();var buffered=this.tech_.buffered();var forwardBuffer=buffered.length?buffered.end(buffered.length-1)-this.tech_.currentTime():0;var bufferLowWaterLine=this.bufferLowWaterLine();var bufferHighWaterLine=this.bufferHighWaterLine();return shouldSwitchToMedia({currentPlaylist:currentPlaylist,nextPlaylist:nextPlaylist,forwardBuffer:forwardBuffer,bufferLowWaterLine:bufferLowWaterLine,bufferHighWaterLine:bufferHighWaterLine,duration:this.duration(),experimentalBufferBasedABR:this.experimentalBufferBasedABR,log:this.logger_});};_proto.setupSegmentLoaderListeners_=function setupSegmentLoaderListeners_(){var _this4=this;if(!this.experimentalBufferBasedABR){this.mainSegmentLoader_.on('bandwidthupdate',function(){var nextPlaylist=_this4.selectPlaylist();if(_this4.shouldSwitchToMedia_(nextPlaylist)){_this4.masterPlaylistLoader_.media(nextPlaylist);}
_this4.tech_.trigger('bandwidthupdate');});this.mainSegmentLoader_.on('progress',function(){_this4.trigger('progress');});}
this.mainSegmentLoader_.on('error',function(){_this4.blacklistCurrentPlaylist(_this4.mainSegmentLoader_.error());});this.mainSegmentLoader_.on('appenderror',function(){_this4.error=_this4.mainSegmentLoader_.error_;_this4.trigger('error');});this.mainSegmentLoader_.on('syncinfoupdate',function(){_this4.onSyncInfoUpdate_();});this.mainSegmentLoader_.on('timestampoffset',function(){_this4.tech_.trigger({type:'usage',name:'vhs-timestamp-offset'});_this4.tech_.trigger({type:'usage',name:'hls-timestamp-offset'});});this.audioSegmentLoader_.on('syncinfoupdate',function(){_this4.onSyncInfoUpdate_();});this.audioSegmentLoader_.on('appenderror',function(){_this4.error=_this4.audioSegmentLoader_.error_;_this4.trigger('error');});this.mainSegmentLoader_.on('ended',function(){_this4.logger_('main segment loader ended');_this4.onEndOfStream();});this.mainSegmentLoader_.on('earlyabort',function(event){if(_this4.experimentalBufferBasedABR){return;}
_this4.delegateLoaders_('all',['abort']);_this4.blacklistCurrentPlaylist({message:'Aborted early because there isn\'t enough bandwidth to complete the '+'request without rebuffering.'},ABORT_EARLY_BLACKLIST_SECONDS);});var updateCodecs=function updateCodecs(){if(!_this4.sourceUpdater_.hasCreatedSourceBuffers()){return _this4.tryToCreateSourceBuffers_();}
var codecs=_this4.getCodecsOrExclude_();if(!codecs){return;}
_this4.sourceUpdater_.addOrChangeSourceBuffers(codecs);};this.mainSegmentLoader_.on('trackinfo',updateCodecs);this.audioSegmentLoader_.on('trackinfo',updateCodecs);this.mainSegmentLoader_.on('fmp4',function(){if(!_this4.triggeredFmp4Usage){_this4.tech_.trigger({type:'usage',name:'vhs-fmp4'});_this4.tech_.trigger({type:'usage',name:'hls-fmp4'});_this4.triggeredFmp4Usage=true;}});this.audioSegmentLoader_.on('fmp4',function(){if(!_this4.triggeredFmp4Usage){_this4.tech_.trigger({type:'usage',name:'vhs-fmp4'});_this4.tech_.trigger({type:'usage',name:'hls-fmp4'});_this4.triggeredFmp4Usage=true;}});this.audioSegmentLoader_.on('ended',function(){_this4.logger_('audioSegmentLoader ended');_this4.onEndOfStream();});};_proto.mediaSecondsLoaded_=function mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded);};_proto.load=function load(){this.mainSegmentLoader_.load();if(this.mediaTypes_.AUDIO.activePlaylistLoader){this.audioSegmentLoader_.load();}
if(this.mediaTypes_.SUBTITLES.activePlaylistLoader){this.subtitleSegmentLoader_.load();}};_proto.smoothQualityChange_=function smoothQualityChange_(media){if(media===void 0){media=this.selectPlaylist();}
if(media===this.masterPlaylistLoader_.media()){return;}
this.masterPlaylistLoader_.media(media);this.mainSegmentLoader_.resetLoader();};_proto.fastQualityChange_=function fastQualityChange_(media){var _this5=this;if(media===void 0){media=this.selectPlaylist();}
if(media===this.masterPlaylistLoader_.media()){return;}
this.masterPlaylistLoader_.media(media);this.mainSegmentLoader_.resetEverything(function(){if(videojs$1.browser.IE_VERSION||videojs$1.browser.IS_EDGE){_this5.tech_.setCurrentTime(_this5.tech_.currentTime()+0.04);}else{_this5.tech_.setCurrentTime(_this5.tech_.currentTime());}});};_proto.play=function play(){if(this.setupFirstPlay()){return;}
if(this.tech_.ended()){this.tech_.setCurrentTime(0);}
if(this.hasPlayed_){this.load();}
var seekable=this.tech_.seekable();if(this.tech_.duration()===Infinity){if(this.tech_.currentTime()<seekable.start(0)){return this.tech_.setCurrentTime(seekable.end(seekable.length-1));}}};_proto.setupFirstPlay=function setupFirstPlay(){var _this6=this;var media=this.masterPlaylistLoader_.media();if(!media||this.tech_.paused()||this.hasPlayed_){return false;}
if(!media.endList){var seekable=this.seekable();if(!seekable.length){return false;}
if(videojs$1.browser.IE_VERSION&&this.tech_.readyState()===0){this.tech_.one('loadedmetadata',function(){_this6.trigger('firstplay');_this6.tech_.setCurrentTime(seekable.end(0));_this6.hasPlayed_=true;});return false;}
this.trigger('firstplay');this.tech_.setCurrentTime(seekable.end(0));}
this.hasPlayed_=true;this.load();return true;};_proto.handleSourceOpen_=function handleSourceOpen_(){this.tryToCreateSourceBuffers_();if(this.tech_.autoplay()){var playPromise=this.tech_.play();if(typeof playPromise!=='undefined'&&typeof playPromise.then==='function'){playPromise.then(null,function(e){});}}
this.trigger('sourceopen');};_proto.handleSourceEnded_=function handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_){return;}
var cues=this.inbandTextTracks_.metadataTrack_.cues;if(!cues||!cues.length){return;}
var duration=this.duration();cues[cues.length-1].endTime=isNaN(duration)||Math.abs(duration)===Infinity?Number.MAX_VALUE:duration;};_proto.handleDurationChange_=function handleDurationChange_(){this.tech_.trigger('durationchange');};_proto.onEndOfStream=function onEndOfStream(){var isEndOfStream=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){if(!this.mainSegmentLoader_.currentMediaInfo_||this.mainSegmentLoader_.currentMediaInfo_.hasVideo){isEndOfStream=isEndOfStream&&this.audioSegmentLoader_.ended_;}else{isEndOfStream=this.audioSegmentLoader_.ended_;}}
if(!isEndOfStream){return;}
this.stopABRTimer_();this.sourceUpdater_.endOfStream();};_proto.stuckAtPlaylistEnd_=function stuckAtPlaylistEnd_(playlist){var seekable=this.seekable();if(!seekable.length){return false;}
var expired=this.syncController_.getExpiredTime(playlist,this.duration());if(expired===null){return false;}
var absolutePlaylistEnd=Vhs.Playlist.playlistEnd(playlist,expired);var currentTime=this.tech_.currentTime();var buffered=this.tech_.buffered();if(!buffered.length){return absolutePlaylistEnd-currentTime<=SAFE_TIME_DELTA;}
var bufferedEnd=buffered.end(buffered.length-1);return bufferedEnd-currentTime<=SAFE_TIME_DELTA&&absolutePlaylistEnd-bufferedEnd<=SAFE_TIME_DELTA;};_proto.blacklistCurrentPlaylist=function blacklistCurrentPlaylist(error,blacklistDuration){if(error===void 0){error={};}
var currentPlaylist=error.playlist||this.masterPlaylistLoader_.media();blacklistDuration=blacklistDuration||error.blacklistDuration||this.blacklistDuration;if(!currentPlaylist){this.error=error;if(this.mediaSource.readyState!=='open'){this.trigger('error');}else{this.sourceUpdater_.endOfStream('network');}
return;}
var playlists=this.masterPlaylistLoader_.master.playlists;var enabledPlaylists=playlists.filter(isEnabled);var isFinalRendition=enabledPlaylists.length===1&&enabledPlaylists[0]===currentPlaylist;if(playlists.length===1&&blacklistDuration!==Infinity){videojs$1.log.warn("Problem encountered with playlist "+currentPlaylist.id+". "+'Trying again since it is the only playlist.');this.tech_.trigger('retryplaylist');return this.masterPlaylistLoader_.load(isFinalRendition);}
if(isFinalRendition){var reincluded=false;playlists.forEach(function(playlist){if(playlist===currentPlaylist){return;}
var excludeUntil=playlist.excludeUntil;if(typeof excludeUntil!=='undefined'&&excludeUntil!==Infinity){reincluded=true;delete playlist.excludeUntil;}});if(reincluded){videojs$1.log.warn('Removing other playlists from the exclusion list because the last '+'rendition is about to be excluded.');this.tech_.trigger('retryplaylist');}}
currentPlaylist.excludeUntil=Date.now()+blacklistDuration*1000;this.tech_.trigger('blacklistplaylist');this.tech_.trigger({type:'usage',name:'vhs-rendition-blacklisted'});this.tech_.trigger({type:'usage',name:'hls-rendition-blacklisted'});var nextPlaylist=this.selectPlaylist();if(!nextPlaylist){this.error='Playback cannot continue. No available working or supported playlists.';this.trigger('error');return;}
var logFn=error.internal?this.logger_:videojs$1.log.warn;var errorMessage=error.message?' '+error.message:'';logFn((error.internal?'Internal problem':'Problem')+" encountered with playlist "+currentPlaylist.id+"."+(errorMessage+" Switching to playlist "+nextPlaylist.id+"."));if(nextPlaylist.attributes.AUDIO!==currentPlaylist.attributes.AUDIO){this.delegateLoaders_('audio',['abort','pause']);}
if(nextPlaylist.attributes.SUBTITLES!==currentPlaylist.attributes.SUBTITLES){this.delegateLoaders_('subtitle',['abort','pause']);}
this.delegateLoaders_('main',['abort','pause']);var delayDuration=nextPlaylist.targetDuration/2*1000||5*1000;var shouldDelay=typeof nextPlaylist.lastRequest==='number'&&Date.now()-nextPlaylist.lastRequest<=delayDuration;return this.masterPlaylistLoader_.media(nextPlaylist,isFinalRendition||shouldDelay);};_proto.pauseLoading=function pauseLoading(){this.delegateLoaders_('all',['abort','pause']);this.stopABRTimer_();};_proto.delegateLoaders_=function delegateLoaders_(filter,fnNames){var _this7=this;var loaders=[];var dontFilterPlaylist=filter==='all';if(dontFilterPlaylist||filter==='main'){loaders.push(this.masterPlaylistLoader_);}
var mediaTypes=[];if(dontFilterPlaylist||filter==='audio'){mediaTypes.push('AUDIO');}
if(dontFilterPlaylist||filter==='subtitle'){mediaTypes.push('CLOSED-CAPTIONS');mediaTypes.push('SUBTITLES');}
mediaTypes.forEach(function(mediaType){var loader=_this7.mediaTypes_[mediaType]&&_this7.mediaTypes_[mediaType].activePlaylistLoader;if(loader){loaders.push(loader);}});['main','audio','subtitle'].forEach(function(name){var loader=_this7[name+"SegmentLoader_"];if(loader&&(filter===name||filter==='all')){loaders.push(loader);}});loaders.forEach(function(loader){return fnNames.forEach(function(fnName){if(typeof loader[fnName]==='function'){loader[fnName]();}});});};_proto.setCurrentTime=function setCurrentTime(currentTime){var buffered=findRange(this.tech_.buffered(),currentTime);if(!(this.masterPlaylistLoader_&&this.masterPlaylistLoader_.media())){return 0;}
if(!this.masterPlaylistLoader_.media().segments){return 0;}
if(buffered&&buffered.length){return currentTime;}
this.mainSegmentLoader_.resetEverything();this.mainSegmentLoader_.abort();if(this.mediaTypes_.AUDIO.activePlaylistLoader){this.audioSegmentLoader_.resetEverything();this.audioSegmentLoader_.abort();}
if(this.mediaTypes_.SUBTITLES.activePlaylistLoader){this.subtitleSegmentLoader_.resetEverything();this.subtitleSegmentLoader_.abort();}
this.load();};_proto.duration=function duration(){if(!this.masterPlaylistLoader_){return 0;}
var media=this.masterPlaylistLoader_.media();if(!media){return 0;}
if(!media.endList){return Infinity;}
if(this.mediaSource){return this.mediaSource.duration;}
return Vhs.Playlist.duration(media);};_proto.seekable=function seekable(){return this.seekable_;};_proto.onSyncInfoUpdate_=function onSyncInfoUpdate_(){var audioSeekable;if(!this.masterPlaylistLoader_){return;}
var media=this.masterPlaylistLoader_.media();if(!media){return;}
var expired=this.syncController_.getExpiredTime(media,this.duration());if(expired===null){return;}
var suggestedPresentationDelay=this.masterPlaylistLoader_.master.suggestedPresentationDelay;var mainSeekable=Vhs.Playlist.seekable(media,expired,suggestedPresentationDelay);if(mainSeekable.length===0){return;}
if(this.mediaTypes_.AUDIO.activePlaylistLoader){media=this.mediaTypes_.AUDIO.activePlaylistLoader.media();expired=this.syncController_.getExpiredTime(media,this.duration());if(expired===null){return;}
audioSeekable=Vhs.Playlist.seekable(media,expired,suggestedPresentationDelay);if(audioSeekable.length===0){return;}}
var oldEnd;var oldStart;if(this.seekable_&&this.seekable_.length){oldEnd=this.seekable_.end(0);oldStart=this.seekable_.start(0);}
if(!audioSeekable){this.seekable_=mainSeekable;}else if(audioSeekable.start(0)>mainSeekable.end(0)||mainSeekable.start(0)>audioSeekable.end(0)){this.seekable_=mainSeekable;}else{this.seekable_=videojs$1.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)]]);}
if(this.seekable_&&this.seekable_.length){if(this.seekable_.end(0)===oldEnd&&this.seekable_.start(0)===oldStart){return;}}
this.logger_("seekable updated ["+printableRange(this.seekable_)+"]");this.tech_.trigger('seekablechanged');};_proto.updateDuration=function updateDuration(isLive){if(this.updateDuration_){this.mediaSource.removeEventListener('sourceopen',this.updateDuration_);this.updateDuration_=null;}
if(this.mediaSource.readyState!=='open'){this.updateDuration_=this.updateDuration.bind(this,isLive);this.mediaSource.addEventListener('sourceopen',this.updateDuration_);return;}
if(isLive){var seekable=this.seekable();if(!seekable.length){return;}
if(isNaN(this.mediaSource.duration)||this.mediaSource.duration<seekable.end(seekable.length-1)){this.sourceUpdater_.setDuration(seekable.end(seekable.length-1));}
return;}
var buffered=this.tech_.buffered();var duration=Vhs.Playlist.duration(this.masterPlaylistLoader_.media());if(buffered.length>0){duration=Math.max(duration,buffered.end(buffered.length-1));}
if(this.mediaSource.duration!==duration){this.sourceUpdater_.setDuration(duration);}};_proto.dispose=function dispose(){var _this8=this;this.trigger('dispose');this.decrypter_.terminate();this.masterPlaylistLoader_.dispose();this.mainSegmentLoader_.dispose();['AUDIO','SUBTITLES'].forEach(function(type){var groups=_this8.mediaTypes_[type].groups;for(var id in groups){groups[id].forEach(function(group){if(group.playlistLoader){group.playlistLoader.dispose();}});}});this.audioSegmentLoader_.dispose();this.subtitleSegmentLoader_.dispose();this.sourceUpdater_.dispose();this.timelineChangeController_.dispose();this.stopABRTimer_();if(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();};_proto.master=function master(){return this.masterPlaylistLoader_.master;};_proto.media=function media(){return this.masterPlaylistLoader_.media()||this.initialMedia_;};_proto.areMediaTypesKnown_=function areMediaTypesKnown_(){var usingAudioLoader=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(!this.mainSegmentLoader_.currentMediaInfo_||usingAudioLoader&&!this.audioSegmentLoader_.currentMediaInfo_){return false;}
return true;};_proto.getCodecsOrExclude_=function getCodecsOrExclude_(){var _this9=this;var media={main:this.mainSegmentLoader_.currentMediaInfo_||{},audio:this.audioSegmentLoader_.currentMediaInfo_||{}};media.video=media.main;var playlistCodecs=codecsForPlaylist(this.master(),this.media());var codecs={};var usingAudioLoader=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(media.main.hasVideo){codecs.video=playlistCodecs.video||media.main.videoCodec||codecs_2;}
if(media.main.isMuxed){codecs.video+=","+(playlistCodecs.audio||media.main.audioCodec||codecs_1);}
if(media.main.hasAudio&&!media.main.isMuxed||media.audio.hasAudio||usingAudioLoader){codecs.audio=playlistCodecs.audio||media.main.audioCodec||media.audio.audioCodec||codecs_1;media.audio.isFmp4=media.main.hasAudio&&!media.main.isMuxed?media.main.isFmp4:media.audio.isFmp4;}
if(!codecs.audio&&!codecs.video){this.blacklistCurrentPlaylist({playlist:this.media(),message:'Could not determine codecs for playlist.',blacklistDuration:Infinity});return;}
var supportFunction=function supportFunction(isFmp4,codec){return isFmp4?codecs_3(codec):codecs_10(codec);};var unsupportedCodecs={};var unsupportedAudio;['video','audio'].forEach(function(type){if(codecs.hasOwnProperty(type)&&!supportFunction(media[type].isFmp4,codecs[type])){var supporter=media[type].isFmp4?'browser':'muxer';unsupportedCodecs[supporter]=unsupportedCodecs[supporter]||[];unsupportedCodecs[supporter].push(codecs[type]);if(type==='audio'){unsupportedAudio=supporter;}}});if(usingAudioLoader&&unsupportedAudio&&this.media().attributes.AUDIO){var audioGroup=this.media().attributes.AUDIO;this.master().playlists.forEach(function(variant){var variantAudioGroup=variant.attributes&&variant.attributes.AUDIO;if(variantAudioGroup===audioGroup&&variant!==_this9.media()){variant.excludeUntil=Infinity;}});this.logger_("excluding audio group "+audioGroup+" as "+unsupportedAudio+" does not support codec(s): \""+codecs.audio+"\"");}
if(Object.keys(unsupportedCodecs).length){var message=Object.keys(unsupportedCodecs).reduce(function(acc,supporter){if(acc){acc+=', ';}
acc+=supporter+" does not support codec(s): \""+unsupportedCodecs[supporter].join(',')+"\"";return acc;},'')+'.';this.blacklistCurrentPlaylist({playlist:this.media(),internal:true,message:message,blacklistDuration:Infinity});return;}
if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){var switchMessages=[];['video','audio'].forEach(function(type){var newCodec=(codecs_11(_this9.sourceUpdater_.codecs[type]||'')[type]||{}).type;var oldCodec=(codecs_11(codecs[type]||'')[type]||{}).type;if(newCodec&&oldCodec&&newCodec.toLowerCase()!==oldCodec.toLowerCase()){switchMessages.push("\""+_this9.sourceUpdater_.codecs[type]+"\" -> \""+codecs[type]+"\"");}});if(switchMessages.length){this.blacklistCurrentPlaylist({playlist:this.media(),message:"Codec switching not supported: "+switchMessages.join(', ')+".",blacklistDuration:Infinity,internal:true});return;}}
return codecs;};_proto.tryToCreateSourceBuffers_=function tryToCreateSourceBuffers_(){if(this.mediaSource.readyState!=='open'||this.sourceUpdater_.hasCreatedSourceBuffers()){return;}
if(!this.areMediaTypesKnown_()){return;}
var codecs=this.getCodecsOrExclude_();if(!codecs){return;}
this.sourceUpdater_.createSourceBuffers(codecs);var codecString=[codecs.video,codecs.audio].filter(Boolean).join(',');this.excludeIncompatibleVariants_(codecString);};_proto.excludeUnsupportedVariants_=function excludeUnsupportedVariants_(){var _this10=this;var playlists=this.master().playlists;var ids=[];Object.keys(playlists).forEach(function(key){var variant=playlists[key];if(ids.indexOf(variant.id)!==-1){return;}
ids.push(variant.id);var codecs=codecsForPlaylist(_this10.master,variant);var unsupported=[];if(codecs.audio&&!codecs_10(codecs.audio)&&!codecs_3(codecs.audio)){variant.excludeUntil=Infinity;unsupported.push("audio codec "+codecs.audio);}
if(codecs.video&&!codecs_10(codecs.video)&&!codecs_3(codecs.video)){variant.excludeUntil=Infinity;unsupported.push("video codec "+codecs.video);}
if(codecs.text&&codecs.text==='stpp.ttml.im1t'){variant.excludeUntil=Infinity;unsupported.push("text codec "+codecs.text);}
if(unsupported.length){_this10.logger_("excluding "+variant.id+" as codecs "+unsupported.join(', ')+" are unsupported");}});};_proto.excludeIncompatibleVariants_=function excludeIncompatibleVariants_(codecString){var _this11=this;var codecs=codecs_11(codecString);var codecCount=Object.keys(codecs).length;this.master().playlists.forEach(function(variant){if(variant.excludeUntil===Infinity){return;}
var variantCodecs={};var variantCodecCount=2;var blacklistReasons=[];var variantCodecStrings=codecsForPlaylist(_this11.masterPlaylistLoader_.master,variant);if(variantCodecStrings.audio||variantCodecStrings.video){var variantCodecString=[variantCodecStrings.video,variantCodecStrings.audio].filter(Boolean).join(',');variantCodecs=codecs_11(variantCodecString);variantCodecCount=Object.keys(variantCodecs).length;}
if(variantCodecCount!==codecCount){blacklistReasons.push("codec count \""+variantCodecCount+"\" !== \""+codecCount+"\"");variant.excludeUntil=Infinity;}
if(!_this11.sourceUpdater_.canChangeType()){if(variantCodecs.video&&codecs.video&&variantCodecs.video.type.toLowerCase()!==codecs.video.type.toLowerCase()){blacklistReasons.push("video codec \""+variantCodecs.video.type+"\" !== \""+codecs.video.type+"\"");variant.excludeUntil=Infinity;}
if(variantCodecs.audio&&codecs.audio&&variantCodecs.audio.type.toLowerCase()!==codecs.audio.type.toLowerCase()){variant.excludeUntil=Infinity;blacklistReasons.push("audio codec \""+variantCodecs.audio.type+"\" !== \""+codecs.audio.type+"\"");}}
if(blacklistReasons.length){_this11.logger_("blacklisting "+variant.id+": "+blacklistReasons.join(' && '));}});};_proto.updateAdCues_=function updateAdCues_(media){var offset=0;var seekable=this.seekable();if(seekable.length){offset=seekable.start(0);}
updateAdCues(media,this.cueTagsTrack_,offset);};_proto.goalBufferLength=function goalBufferLength(){var currentTime=this.tech_.currentTime();var initial=Config.GOAL_BUFFER_LENGTH;var rate=Config.GOAL_BUFFER_LENGTH_RATE;var max=Math.max(initial,Config.MAX_GOAL_BUFFER_LENGTH);return Math.min(initial+currentTime*rate,max);};_proto.bufferLowWaterLine=function bufferLowWaterLine(){var currentTime=this.tech_.currentTime();var initial=Config.BUFFER_LOW_WATER_LINE;var rate=Config.BUFFER_LOW_WATER_LINE_RATE;var max=Math.max(initial,Config.MAX_BUFFER_LOW_WATER_LINE);var newMax=Math.max(initial,Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(initial+currentTime*rate,this.experimentalBufferBasedABR?newMax:max);};_proto.bufferHighWaterLine=function bufferHighWaterLine(){return Config.BUFFER_HIGH_WATER_LINE;};return MasterPlaylistController;}(videojs$1.EventTarget);var enableFunction=function enableFunction(loader,playlistID,changePlaylistFn){return function(enable){var playlist=loader.master.playlists[playlistID];var incompatible=isIncompatible(playlist);var currentlyEnabled=isEnabled(playlist);if(typeof enable==='undefined'){return currentlyEnabled;}
if(enable){delete playlist.disabled;}else{playlist.disabled=true;}
if(enable!==currentlyEnabled&&!incompatible){changePlaylistFn();if(enable){loader.trigger('renditionenabled');}else{loader.trigger('renditiondisabled');}}
return enable;};};var Representation=function Representation(vhsHandler,playlist,id){var mpc=vhsHandler.masterPlaylistController_,smoothQualityChange=vhsHandler.options_.smoothQualityChange;var changeType=smoothQualityChange?'smooth':'fast';var qualityChangeFunction=mpc[changeType+"QualityChange_"].bind(mpc);if(playlist.attributes.RESOLUTION){var resolution=playlist.attributes.RESOLUTION;this.width=resolution.width;this.height=resolution.height;}
this.bandwidth=playlist.attributes.BANDWIDTH;this.codecs=codecsForPlaylist(mpc.master(),playlist);this.playlist=playlist;this.id=id;this.enabled=enableFunction(vhsHandler.playlists,playlist.id,qualityChangeFunction);};var renditionSelectionMixin=function renditionSelectionMixin(vhsHandler){var playlists=vhsHandler.playlists;vhsHandler.representations=function(){if(!playlists||!playlists.master||!playlists.master.playlists){return[];}
return playlists.master.playlists.filter(function(media){return!isIncompatible(media);}).map(function(e,i){return new Representation(vhsHandler,e,e.id);});};};var timerCancelEvents=['seeking','seeked','pause','playing','error'];var closeToBufferedContent=function closeToBufferedContent(_ref){var buffered=_ref.buffered,targetDuration=_ref.targetDuration,currentTime=_ref.currentTime;if(!buffered.length){return false;}
if(buffered.end(0)-buffered.start(0)<targetDuration*2){return false;}
if(currentTime>buffered.start(0)){return false;}
return buffered.start(0)-currentTime<targetDuration;};var PlaybackWatcher=function(){function PlaybackWatcher(options){var _this=this;this.masterPlaylistController_=options.masterPlaylistController;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.timer_=null;this.checkCurrentTimeTimeout_=null;this.logger_=logger('PlaybackWatcher');this.logger_('initialize');var canPlayHandler=function canPlayHandler(){return _this.monitorCurrentTime_();};var waitingHandler=function waitingHandler(){return _this.techWaiting_();};var cancelTimerHandler=function cancelTimerHandler(){return _this.cancelTimer_();};var fixesBadSeeksHandler=function fixesBadSeeksHandler(){return _this.fixesBadSeeks_();};var mpc=this.masterPlaylistController_;var loaderTypes=['main','subtitle','audio'];var loaderChecks={};loaderTypes.forEach(function(type){loaderChecks[type]={reset:function reset(){return _this.resetSegmentDownloads_(type);},updateend:function updateend(){return _this.checkSegmentDownloads_(type);}};mpc[type+"SegmentLoader_"].on('appendsdone',loaderChecks[type].updateend);mpc[type+"SegmentLoader_"].on('playlistupdate',loaderChecks[type].reset);_this.tech_.on(['seeked','seeking'],loaderChecks[type].reset);});this.tech_.on('seekablechanged',fixesBadSeeksHandler);this.tech_.on('waiting',waitingHandler);this.tech_.on(timerCancelEvents,cancelTimerHandler);this.tech_.on('canplay',canPlayHandler);this.dispose=function(){_this.logger_('dispose');_this.tech_.off('seekablechanged',fixesBadSeeksHandler);_this.tech_.off('waiting',waitingHandler);_this.tech_.off(timerCancelEvents,cancelTimerHandler);_this.tech_.off('canplay',canPlayHandler);loaderTypes.forEach(function(type){mpc[type+"SegmentLoader_"].off('appendsdone',loaderChecks[type].updateend);mpc[type+"SegmentLoader_"].off('playlistupdate',loaderChecks[type].reset);_this.tech_.off(['seeked','seeking'],loaderChecks[type].reset);});if(_this.checkCurrentTimeTimeout_){window_1$2.clearTimeout(_this.checkCurrentTimeTimeout_);}
_this.cancelTimer_();};}
var _proto=PlaybackWatcher.prototype;_proto.monitorCurrentTime_=function monitorCurrentTime_(){this.checkCurrentTime_();if(this.checkCurrentTimeTimeout_){window_1$2.clearTimeout(this.checkCurrentTimeTimeout_);}
this.checkCurrentTimeTimeout_=window_1$2.setTimeout(this.monitorCurrentTime_.bind(this),250);};_proto.resetSegmentDownloads_=function resetSegmentDownloads_(type){var loader=this.masterPlaylistController_[type+"SegmentLoader_"];if(this[type+"StalledDownloads_"]>0){this.logger_("resetting possible stalled download count for "+type+" loader");}
this[type+"StalledDownloads_"]=0;this[type+"Buffered_"]=loader.buffered_();};_proto.checkSegmentDownloads_=function checkSegmentDownloads_(type){var mpc=this.masterPlaylistController_;var loader=mpc[type+"SegmentLoader_"];var buffered=loader.buffered_();var isBufferedDifferent=isRangeDifferent(this[type+"Buffered_"],buffered);this[type+"Buffered_"]=buffered;if(isBufferedDifferent){this.resetSegmentDownloads_(type);return;}
this[type+"StalledDownloads_"]++;this.logger_("found #"+this[type+"StalledDownloads_"]+" "+type+" appends that did not increase buffer (possible stalled download)",{playlistId:loader.playlist_&&loader.playlist_.id,buffered:timeRangesToArray(buffered)});if(this[type+"StalledDownloads_"]<10){return;}
this.logger_(type+" loader stalled download exclusion");this.resetSegmentDownloads_(type);this.tech_.trigger({type:'usage',name:"vhs-"+type+"-download-exclusion"});if(type==='subtitle'){return;}
mpc.blacklistCurrentPlaylist({message:"Excessive "+type+" segment downloading detected."},Infinity);};_proto.checkCurrentTime_=function checkCurrentTime_(){if(this.tech_.seeking()&&this.fixesBadSeeks_()){this.consecutiveUpdates=0;this.lastRecordedTime=this.tech_.currentTime();return;}
if(this.tech_.paused()||this.tech_.seeking()){return;}
var currentTime=this.tech_.currentTime();var buffered=this.tech_.buffered();if(this.lastRecordedTime===currentTime&&(!buffered.length||currentTime+SAFE_TIME_DELTA>=buffered.end(buffered.length-1))){return this.techWaiting_();}
if(this.consecutiveUpdates>=5&&currentTime===this.lastRecordedTime){this.consecutiveUpdates++;this.waiting_();}else if(currentTime===this.lastRecordedTime){this.consecutiveUpdates++;}else{this.consecutiveUpdates=0;this.lastRecordedTime=currentTime;}};_proto.cancelTimer_=function cancelTimer_(){this.consecutiveUpdates=0;if(this.timer_){this.logger_('cancelTimer_');clearTimeout(this.timer_);}
this.timer_=null;};_proto.fixesBadSeeks_=function fixesBadSeeks_(){var seeking=this.tech_.seeking();if(!seeking){return false;}
var seekable=this.seekable();var currentTime=this.tech_.currentTime();var isAfterSeekableRange=this.afterSeekableWindow_(seekable,currentTime,this.media(),this.allowSeeksWithinUnsafeLiveWindow);var seekTo;if(isAfterSeekableRange){var seekableEnd=seekable.end(seekable.length-1);seekTo=seekableEnd;}
if(this.beforeSeekableWindow_(seekable,currentTime)){var seekableStart=seekable.start(0);seekTo=seekableStart+(seekableStart===seekable.end(0)?0:SAFE_TIME_DELTA);}
if(typeof seekTo!=='undefined'){this.logger_("Trying to seek outside of seekable at time "+currentTime+" with "+("seekable range "+printableRange(seekable)+". Seeking to ")+(seekTo+"."));this.tech_.setCurrentTime(seekTo);return true;}
var buffered=this.tech_.buffered();if(closeToBufferedContent({buffered:buffered,targetDuration:this.media().targetDuration,currentTime:currentTime})){seekTo=buffered.start(0)+SAFE_TIME_DELTA;this.logger_("Buffered region starts ("+buffered.start(0)+") "+(" just beyond seek point ("+currentTime+"). Seeking to "+seekTo+"."));this.tech_.setCurrentTime(seekTo);return true;}
return false;};_proto.waiting_=function waiting_(){if(this.techWaiting_()){return;}
var currentTime=this.tech_.currentTime();var buffered=this.tech_.buffered();var currentRange=findRange(buffered,currentTime);if(currentRange.length&&currentTime+3<=currentRange.end(0)){this.cancelTimer_();this.tech_.setCurrentTime(currentTime);this.logger_("Stopped at "+currentTime+" while inside a buffered region "+("["+currentRange.start(0)+" -> "+currentRange.end(0)+"]. Attempting to resume ")+'playback by seeking to the current time.');this.tech_.trigger({type:'usage',name:'vhs-unknown-waiting'});this.tech_.trigger({type:'usage',name:'hls-unknown-waiting'});return;}};_proto.techWaiting_=function techWaiting_(){var seekable=this.seekable();var currentTime=this.tech_.currentTime();if(this.tech_.seeking()&&this.fixesBadSeeks_()){return true;}
if(this.tech_.seeking()||this.timer_!==null){return true;}
if(this.beforeSeekableWindow_(seekable,currentTime)){var livePoint=seekable.end(seekable.length-1);this.logger_("Fell out of live window at time "+currentTime+". Seeking to "+("live point (seekable end) "+livePoint));this.cancelTimer_();this.tech_.setCurrentTime(livePoint);this.tech_.trigger({type:'usage',name:'vhs-live-resync'});this.tech_.trigger({type:'usage',name:'hls-live-resync'});return true;}
var sourceUpdater=this.tech_.vhs.masterPlaylistController_.sourceUpdater_;var buffered=this.tech_.buffered();var videoUnderflow=this.videoUnderflow_({audioBuffered:sourceUpdater.audioBuffered(),videoBuffered:sourceUpdater.videoBuffered(),currentTime:currentTime});if(videoUnderflow){this.cancelTimer_();this.tech_.setCurrentTime(currentTime);this.tech_.trigger({type:'usage',name:'vhs-video-underflow'});this.tech_.trigger({type:'usage',name:'hls-video-underflow'});return true;}
var nextRange=findNextRange(buffered,currentTime);if(nextRange.length>0){var difference=nextRange.start(0)-currentTime;this.logger_("Stopped at "+currentTime+", setting timer for "+difference+", seeking "+("to "+nextRange.start(0)));this.cancelTimer_();this.timer_=setTimeout(this.skipTheGap_.bind(this),difference*1000,currentTime);return true;}
return false;};_proto.afterSeekableWindow_=function afterSeekableWindow_(seekable,currentTime,playlist,allowSeeksWithinUnsafeLiveWindow){if(allowSeeksWithinUnsafeLiveWindow===void 0){allowSeeksWithinUnsafeLiveWindow=false;}
if(!seekable.length){return false;}
var allowedEnd=seekable.end(seekable.length-1)+SAFE_TIME_DELTA;var isLive=!playlist.endList;if(isLive&&allowSeeksWithinUnsafeLiveWindow){allowedEnd=seekable.end(seekable.length-1)+playlist.targetDuration*3;}
if(currentTime>allowedEnd){return true;}
return false;};_proto.beforeSeekableWindow_=function beforeSeekableWindow_(seekable,currentTime){if(seekable.length&&seekable.start(0)>0&&currentTime<seekable.start(0)-this.liveRangeSafeTimeDelta){return true;}
return false;};_proto.videoUnderflow_=function videoUnderflow_(_ref2){var videoBuffered=_ref2.videoBuffered,audioBuffered=_ref2.audioBuffered,currentTime=_ref2.currentTime;if(!videoBuffered){return;}
var gap;if(videoBuffered.length&&audioBuffered.length){var lastVideoRange=findRange(videoBuffered,currentTime-3);var videoRange=findRange(videoBuffered,currentTime);var audioRange=findRange(audioBuffered,currentTime);if(audioRange.length&&!videoRange.length&&lastVideoRange.length){gap={start:lastVideoRange.end(0),end:audioRange.end(0)};}}else{var nextRange=findNextRange(videoBuffered,currentTime);if(!nextRange.length){gap=this.gapFromVideoUnderflow_(videoBuffered,currentTime);}}
if(gap){this.logger_("Encountered a gap in video from "+gap.start+" to "+gap.end+". "+("Seeking to current time "+currentTime));return true;}
return false;};_proto.skipTheGap_=function skipTheGap_(scheduledCurrentTime){var buffered=this.tech_.buffered();var currentTime=this.tech_.currentTime();var nextRange=findNextRange(buffered,currentTime);this.cancelTimer_();if(nextRange.length===0||currentTime!==scheduledCurrentTime){return;}
this.logger_('skipTheGap_:','currentTime:',currentTime,'scheduled currentTime:',scheduledCurrentTime,'nextRange start:',nextRange.start(0));this.tech_.setCurrentTime(nextRange.start(0)+TIME_FUDGE_FACTOR);this.tech_.trigger({type:'usage',name:'vhs-gap-skip'});this.tech_.trigger({type:'usage',name:'hls-gap-skip'});};_proto.gapFromVideoUnderflow_=function gapFromVideoUnderflow_(buffered,currentTime){var gaps=findGaps(buffered);for(var i=0;i<gaps.length;i++){var start=gaps.start(i);var end=gaps.end(i);if(currentTime-start<4&&currentTime-start>2){return{start:start,end:end};}}
return null;};return PlaybackWatcher;}();var defaultOptions={errorInterval:30,getSource:function getSource(next){var tech=this.tech({IWillNotUseThisInPlugins:true});var sourceObj=tech.currentSource_||this.currentSource();return next(sourceObj);}};var initPlugin=function initPlugin(player,options){var lastCalled=0;var seekTo=0;var localOptions=videojs$1.mergeOptions(defaultOptions,options);player.ready(function(){player.trigger({type:'usage',name:'vhs-error-reload-initialized'});player.trigger({type:'usage',name:'hls-error-reload-initialized'});});var loadedMetadataHandler=function loadedMetadataHandler(){if(seekTo){player.currentTime(seekTo);}};var setSource=function setSource(sourceObj){if(sourceObj===null||sourceObj===undefined){return;}
seekTo=player.duration()!==Infinity&&player.currentTime()||0;player.one('loadedmetadata',loadedMetadataHandler);player.src(sourceObj);player.trigger({type:'usage',name:'vhs-error-reload'});player.trigger({type:'usage',name:'hls-error-reload'});player.play();};var errorHandler=function errorHandler(){if(Date.now()-lastCalled<localOptions.errorInterval*1000){player.trigger({type:'usage',name:'vhs-error-reload-canceled'});player.trigger({type:'usage',name:'hls-error-reload-canceled'});return;}
if(!localOptions.getSource||typeof localOptions.getSource!=='function'){videojs$1.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');return;}
lastCalled=Date.now();return localOptions.getSource.call(player,setSource);};var cleanupEvents=function cleanupEvents(){player.off('loadedmetadata',loadedMetadataHandler);player.off('error',errorHandler);player.off('dispose',cleanupEvents);};var reinitPlugin=function reinitPlugin(newOptions){cleanupEvents();initPlugin(player,newOptions);};player.on('error',errorHandler);player.on('dispose',cleanupEvents);player.reloadSourceOnError=reinitPlugin;};var reloadSourceOnError=function reloadSourceOnError(options){initPlugin(this,options);};var version$1="2.4.2";var version$1$1="5.8.0";var version$2="0.15.0";var version$3="4.5.0";var version$4="3.1.0";var Vhs$1={PlaylistLoader:PlaylistLoader,Playlist:Playlist,utils:utils$1,STANDARD_PLAYLIST_SELECTOR:lastBandwidthSelector,INITIAL_PLAYLIST_SELECTOR:lowestBitrateCompatibleVariantSelector,lastBandwidthSelector:lastBandwidthSelector,movingAverageBandwidthSelector:movingAverageBandwidthSelector,comparePlaylistBandwidth:comparePlaylistBandwidth,comparePlaylistResolution:comparePlaylistResolution,xhr:xhrFactory()};Object.keys(Config).forEach(function(prop){Object.defineProperty(Vhs$1,prop,{get:function get(){videojs$1.log.warn("using Vhs."+prop+" is UNSAFE be sure you know what you are doing");return Config[prop];},set:function set(value){videojs$1.log.warn("using Vhs."+prop+" is UNSAFE be sure you know what you are doing");if(typeof value!=='number'||value<0){videojs$1.log.warn("value of Vhs."+prop+" must be greater than or equal to 0");return;}
Config[prop]=value;}});});var LOCAL_STORAGE_KEY$1='videojs-vhs';var handleVhsMediaChange=function handleVhsMediaChange(qualityLevels,playlistLoader){var newPlaylist=playlistLoader.media();var selectedIndex=-1;for(var i=0;i<qualityLevels.length;i++){if(qualityLevels[i].id===newPlaylist.id){selectedIndex=i;break;}}
qualityLevels.selectedIndex_=selectedIndex;qualityLevels.trigger({selectedIndex:selectedIndex,type:'change'});};var handleVhsLoadedMetadata=function handleVhsLoadedMetadata(qualityLevels,vhs){vhs.representations().forEach(function(rep){qualityLevels.addQualityLevel(rep);});handleVhsMediaChange(qualityLevels,vhs.playlists);};Vhs$1.canPlaySource=function(){return videojs$1.log.warn('HLS is no longer a tech. Please remove it from '+'your player\'s techOrder.');};var emeKeySystems=function emeKeySystems(keySystemOptions,videoPlaylist,audioPlaylist){if(!keySystemOptions){return keySystemOptions;}
var codecs={video:videoPlaylist&&videoPlaylist.attributes&&videoPlaylist.attributes.CODECS,audio:audioPlaylist&&audioPlaylist.attributes&&audioPlaylist.attributes.CODECS};if(!codecs.audio&&codecs.video&&codecs.video.split(',').length>1){codecs.video.split(',').forEach(function(codec){codec=codec.trim();if(codecs_6(codec)){codecs.audio=codec;}else if(codecs_8(codec)){codecs.video=codec;}});}
var videoContentType=codecs.video?"video/mp4;codecs=\""+codecs.video+"\"":null;var audioContentType=codecs.audio?"audio/mp4;codecs=\""+codecs.audio+"\"":null;var keySystemContentTypes={};for(var keySystem in keySystemOptions){keySystemContentTypes[keySystem]={audioContentType:audioContentType,videoContentType:videoContentType};if(videoPlaylist.contentProtection&&videoPlaylist.contentProtection[keySystem]&&videoPlaylist.contentProtection[keySystem].pssh){keySystemContentTypes[keySystem].pssh=videoPlaylist.contentProtection[keySystem].pssh;}
if(typeof keySystemOptions[keySystem]==='string'){keySystemContentTypes[keySystem].url=keySystemOptions[keySystem];}}
return videojs$1.mergeOptions(keySystemOptions,keySystemContentTypes);};var getAllPsshKeySystemsOptions=function getAllPsshKeySystemsOptions(playlists,keySystems){return playlists.reduce(function(keySystemsArr,playlist){if(!playlist.contentProtection){return keySystemsArr;}
var keySystemsOptions=keySystems.reduce(function(keySystemsObj,keySystem){var keySystemOptions=playlist.contentProtection[keySystem];if(keySystemOptions&&keySystemOptions.pssh){keySystemsObj[keySystem]={pssh:keySystemOptions.pssh};}
return keySystemsObj;},{});if(Object.keys(keySystemsOptions).length){keySystemsArr.push(keySystemsOptions);}
return keySystemsArr;},[]);};var waitForKeySessionCreation=function waitForKeySessionCreation(_ref){var player=_ref.player,sourceKeySystems=_ref.sourceKeySystems,audioMedia=_ref.audioMedia,mainPlaylists=_ref.mainPlaylists;if(!player.eme.initializeMediaKeys){return Promise.resolve();}
var playlists=audioMedia?mainPlaylists.concat([audioMedia]):mainPlaylists;var keySystemsOptionsArr=getAllPsshKeySystemsOptions(playlists,Object.keys(sourceKeySystems));var initializationFinishedPromises=[];var keySessionCreatedPromises=[];keySystemsOptionsArr.forEach(function(keySystemsOptions){keySessionCreatedPromises.push(new Promise(function(resolve,reject){player.tech_.one('keysessioncreated',resolve);}));initializationFinishedPromises.push(new Promise(function(resolve,reject){player.eme.initializeMediaKeys({keySystems:keySystemsOptions},function(err){if(err){reject(err);return;}
resolve();});}));});return Promise.race([Promise.all(initializationFinishedPromises),Promise.race(keySessionCreatedPromises)]);};var setupEmeOptions=function setupEmeOptions(_ref2){var player=_ref2.player,sourceKeySystems=_ref2.sourceKeySystems,media=_ref2.media,audioMedia=_ref2.audioMedia;var sourceOptions=emeKeySystems(sourceKeySystems,media,audioMedia);if(!sourceOptions){return false;}
player.currentSource().keySystems=sourceOptions;if(sourceOptions&&!player.eme){videojs$1.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');return false;}
return true;};var getVhsLocalStorage=function getVhsLocalStorage(){if(!window_1$2.localStorage){return null;}
var storedObject=window_1$2.localStorage.getItem(LOCAL_STORAGE_KEY$1);if(!storedObject){return null;}
try{return JSON.parse(storedObject);}catch(e){return null;}};var updateVhsLocalStorage=function updateVhsLocalStorage(options){if(!window_1$2.localStorage){return false;}
var objectToStore=getVhsLocalStorage();objectToStore=objectToStore?videojs$1.mergeOptions(objectToStore,options):options;try{window_1$2.localStorage.setItem(LOCAL_STORAGE_KEY$1,JSON.stringify(objectToStore));}catch(e){return false;}
return objectToStore;};var expandDataUri=function expandDataUri(dataUri){if(dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,')===0){return JSON.parse(dataUri.substring(dataUri.indexOf(',')+1));}
return dataUri;};Vhs$1.supportsNativeHls=function(){if(!document_1$1||!document_1$1.createElement){return false;}
var video=document_1$1.createElement('video');if(!videojs$1.getTech('Html5').isSupported()){return false;}
var canPlay=['application/vnd.apple.mpegurl','audio/mpegurl','audio/x-mpegurl','application/x-mpegurl','video/x-mpegurl','video/mpegurl','application/mpegurl'];return canPlay.some(function(canItPlay){return/maybe|probably/i.test(video.canPlayType(canItPlay));});}();Vhs$1.supportsNativeDash=function(){if(!document_1$1||!document_1$1.createElement||!videojs$1.getTech('Html5').isSupported()){return false;}
return/maybe|probably/i.test(document_1$1.createElement('video').canPlayType('application/dash+xml'));}();Vhs$1.supportsTypeNatively=function(type){if(type==='hls'){return Vhs$1.supportsNativeHls;}
if(type==='dash'){return Vhs$1.supportsNativeDash;}
return false;};Vhs$1.isSupported=function(){return videojs$1.log.warn('HLS is no longer a tech. Please remove it from '+'your player\'s techOrder.');};var Component$1=videojs$1.getComponent('Component');var VhsHandler=function(_Component){inheritsLoose$1(VhsHandler,_Component);function VhsHandler(source,tech,options){var _this;_this=_Component.call(this,tech,videojs$1.mergeOptions(options.hls,options.vhs))||this;if(options.hls&&Object.keys(options.hls).length){videojs$1.log.warn('Using hls options is deprecated. Use vhs instead.');}
_this.logger_=logger('VhsHandler');if(tech.options_&&tech.options_.playerId){var _player=videojs$1(tech.options_.playerId);if(!_player.hasOwnProperty('hls')){Object.defineProperty(_player,'hls',{get:function get(){videojs$1.log.warn('player.hls is deprecated. Use player.tech().vhs instead.');tech.trigger({type:'usage',name:'hls-player-access'});return assertThisInitialized$1(_this);},configurable:true});}
if(!_player.hasOwnProperty('vhs')){Object.defineProperty(_player,'vhs',{get:function get(){videojs$1.log.warn('player.vhs is deprecated. Use player.tech().vhs instead.');tech.trigger({type:'usage',name:'vhs-player-access'});return assertThisInitialized$1(_this);},configurable:true});}
if(!_player.hasOwnProperty('dash')){Object.defineProperty(_player,'dash',{get:function get(){videojs$1.log.warn('player.dash is deprecated. Use player.tech().vhs instead.');return assertThisInitialized$1(_this);},configurable:true});}
_this.player_=_player;}
_this.tech_=tech;_this.source_=source;_this.stats={};_this.ignoreNextSeekingEvent_=false;_this.setOptions_();if(_this.options_.overrideNative&&tech.overrideNativeAudioTracks&&tech.overrideNativeVideoTracks){tech.overrideNativeAudioTracks(true);tech.overrideNativeVideoTracks(true);}else if(_this.options_.overrideNative&&(tech.featuresNativeVideoTracks||tech.featuresNativeAudioTracks)){throw new Error('Overriding native HLS requires emulated tracks. '+'See https://git.io/vMpjB');}
_this.on(document_1$1,['fullscreenchange','webkitfullscreenchange','mozfullscreenchange','MSFullscreenChange'],function(event){var fullscreenElement=document_1$1.fullscreenElement||document_1$1.webkitFullscreenElement||document_1$1.mozFullScreenElement||document_1$1.msFullscreenElement;if(fullscreenElement&&fullscreenElement.contains(_this.tech_.el())){_this.masterPlaylistController_.smoothQualityChange_();}});_this.on(_this.tech_,'seeking',function(){if(this.ignoreNextSeekingEvent_){this.ignoreNextSeekingEvent_=false;return;}
this.setCurrentTime(this.tech_.currentTime());});_this.on(_this.tech_,'error',function(){if(this.tech_.error()&&this.masterPlaylistController_){this.masterPlaylistController_.pauseLoading();}});_this.on(_this.tech_,'play',_this.play);return _this;}
var _proto=VhsHandler.prototype;_proto.setOptions_=function setOptions_(){var _this2=this;this.options_.withCredentials=this.options_.withCredentials||false;this.options_.handleManifestRedirects=this.options_.handleManifestRedirects===false?false:true;this.options_.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions===false?false:true;this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||false;this.options_.smoothQualityChange=this.options_.smoothQualityChange||false;this.options_.useBandwidthFromLocalStorage=typeof this.source_.useBandwidthFromLocalStorage!=='undefined'?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||false;this.options_.customTagParsers=this.options_.customTagParsers||[];this.options_.customTagMappers=this.options_.customTagMappers||[];this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||false;this.options_.handlePartialData=this.options_.handlePartialData||false;if(typeof this.options_.blacklistDuration!=='number'){this.options_.blacklistDuration=5*60;}
if(typeof this.options_.bandwidth!=='number'){if(this.options_.useBandwidthFromLocalStorage){var storedObject=getVhsLocalStorage();if(storedObject&&storedObject.bandwidth){this.options_.bandwidth=storedObject.bandwidth;this.tech_.trigger({type:'usage',name:'vhs-bandwidth-from-local-storage'});this.tech_.trigger({type:'usage',name:'hls-bandwidth-from-local-storage'});}
if(storedObject&&storedObject.throughput){this.options_.throughput=storedObject.throughput;this.tech_.trigger({type:'usage',name:'vhs-throughput-from-local-storage'});this.tech_.trigger({type:'usage',name:'hls-throughput-from-local-storage'});}}}
if(typeof this.options_.bandwidth!=='number'){this.options_.bandwidth=Config.INITIAL_BANDWIDTH;}
this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===Config.INITIAL_BANDWIDTH;['withCredentials','useDevicePixelRatio','limitRenditionByPlayerDimensions','bandwidth','smoothQualityChange','customTagParsers','customTagMappers','handleManifestRedirects','cacheEncryptionKeys','handlePartialData','playlistSelector','initialPlaylistSelector','experimentalBufferBasedABR','liveRangeSafeTimeDelta'].forEach(function(option){if(typeof _this2.source_[option]!=='undefined'){_this2.options_[option]=_this2.source_[option];}});this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions;this.useDevicePixelRatio=this.options_.useDevicePixelRatio;};_proto.src=function src(_src,type){var _this3=this;if(!_src){return;}
this.setOptions_();this.options_.src=expandDataUri(this.source_.src);this.options_.tech=this.tech_;this.options_.externVhs=Vhs$1;this.options_.sourceType=mediaTypes_1(type);this.options_.seekTo=function(time){_this3.tech_.setCurrentTime(time);};this.masterPlaylistController_=new MasterPlaylistController(this.options_);var playbackWatcherOptions=videojs$1.mergeOptions({liveRangeSafeTimeDelta:SAFE_TIME_DELTA},this.options_,{seekable:function seekable(){return _this3.seekable();},media:function media(){return _this3.masterPlaylistController_.media();},masterPlaylistController:this.masterPlaylistController_});this.playbackWatcher_=new PlaybackWatcher(playbackWatcherOptions);this.masterPlaylistController_.on('error',function(){var player=videojs$1.players[_this3.tech_.options_.playerId];var error=_this3.masterPlaylistController_.error;if(typeof error==='object'&&!error.code){error.code=3;}else if(typeof error==='string'){error={message:error,code:3};}
player.error(error);});var defaultSelector=this.options_.experimentalBufferBasedABR?Vhs$1.movingAverageBandwidthSelector(0.55):Vhs$1.STANDARD_PLAYLIST_SELECTOR;this.masterPlaylistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):defaultSelector.bind(this);this.masterPlaylistController_.selectInitialPlaylist=Vhs$1.INITIAL_PLAYLIST_SELECTOR.bind(this);this.playlists=this.masterPlaylistController_.masterPlaylistLoader_;this.mediaSource=this.masterPlaylistController_.mediaSource;Object.defineProperties(this,{selectPlaylist:{get:function get(){return this.masterPlaylistController_.selectPlaylist;},set:function set(selectPlaylist){this.masterPlaylistController_.selectPlaylist=selectPlaylist.bind(this);}},throughput:{get:function get(){return this.masterPlaylistController_.mainSegmentLoader_.throughput.rate;},set:function set(throughput){this.masterPlaylistController_.mainSegmentLoader_.throughput.rate=throughput;this.masterPlaylistController_.mainSegmentLoader_.throughput.count=1;}},bandwidth:{get:function get(){return this.masterPlaylistController_.mainSegmentLoader_.bandwidth;},set:function set(bandwidth){this.masterPlaylistController_.mainSegmentLoader_.bandwidth=bandwidth;this.masterPlaylistController_.mainSegmentLoader_.throughput={rate:0,count:0};}},systemBandwidth:{get:function get(){var invBandwidth=1/(this.bandwidth||1);var invThroughput;if(this.throughput>0){invThroughput=1/this.throughput;}else{invThroughput=0;}
var systemBitrate=Math.floor(1/(invBandwidth+invThroughput));return systemBitrate;},set:function set(){videojs$1.log.error('The "systemBandwidth" property is read-only');}}});if(this.options_.bandwidth){this.bandwidth=this.options_.bandwidth;}
if(this.options_.throughput){this.throughput=this.options_.throughput;}
Object.defineProperties(this.stats,{bandwidth:{get:function get(){return _this3.bandwidth||0;},enumerable:true},mediaRequests:{get:function get(){return _this3.masterPlaylistController_.mediaRequests_()||0;},enumerable:true},mediaRequestsAborted:{get:function get(){return _this3.masterPlaylistController_.mediaRequestsAborted_()||0;},enumerable:true},mediaRequestsTimedout:{get:function get(){return _this3.masterPlaylistController_.mediaRequestsTimedout_()||0;},enumerable:true},mediaRequestsErrored:{get:function get(){return _this3.masterPlaylistController_.mediaRequestsErrored_()||0;},enumerable:true},mediaTransferDuration:{get:function get(){return _this3.masterPlaylistController_.mediaTransferDuration_()||0;},enumerable:true},mediaBytesTransferred:{get:function get(){return _this3.masterPlaylistController_.mediaBytesTransferred_()||0;},enumerable:true},mediaSecondsLoaded:{get:function get(){return _this3.masterPlaylistController_.mediaSecondsLoaded_()||0;},enumerable:true},buffered:{get:function get(){return timeRangesToArray(_this3.tech_.buffered());},enumerable:true},currentTime:{get:function get(){return _this3.tech_.currentTime();},enumerable:true},currentSource:{get:function get(){return _this3.tech_.currentSource_;},enumerable:true},currentTech:{get:function get(){return _this3.tech_.name_;},enumerable:true},duration:{get:function get(){return _this3.tech_.duration();},enumerable:true},master:{get:function get(){return _this3.playlists.master;},enumerable:true},playerDimensions:{get:function get(){return _this3.tech_.currentDimensions();},enumerable:true},seekable:{get:function get(){return timeRangesToArray(_this3.tech_.seekable());},enumerable:true},timestamp:{get:function get(){return Date.now();},enumerable:true},videoPlaybackQuality:{get:function get(){return _this3.tech_.getVideoPlaybackQuality();},enumerable:true}});this.tech_.one('canplay',this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));this.tech_.on('bandwidthupdate',function(){if(_this3.options_.useBandwidthFromLocalStorage){updateVhsLocalStorage({bandwidth:_this3.bandwidth,throughput:Math.round(_this3.throughput)});}});this.masterPlaylistController_.on('selectedinitialmedia',function(){renditionSelectionMixin(_this3);});this.masterPlaylistController_.sourceUpdater_.on('createdsourcebuffers',function(){_this3.setupEme_();});this.on(this.masterPlaylistController_,'progress',function(){this.tech_.trigger('progress');});this.on(this.masterPlaylistController_,'firstplay',function(){this.ignoreNextSeekingEvent_=true;});this.setupQualityLevels_();if(!this.tech_.el()){return;}
this.mediaSourceUrl_=window_1$2.URL.createObjectURL(this.masterPlaylistController_.mediaSource);this.tech_.src(this.mediaSourceUrl_);};_proto.setupEme_=function setupEme_(){var _this4=this;var audioPlaylistLoader=this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;var didSetupEmeOptions=setupEmeOptions({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:audioPlaylistLoader&&audioPlaylistLoader.media()});if(videojs$1.browser.IE_VERSION===11||!didSetupEmeOptions){this.masterPlaylistController_.sourceUpdater_.initializedEme();return;}
this.logger_('waiting for EME key session creation');waitForKeySessionCreation({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:audioPlaylistLoader&&audioPlaylistLoader.media(),mainPlaylists:this.playlists.master.playlists}).then(function(){_this4.logger_('created EME key session');_this4.masterPlaylistController_.sourceUpdater_.initializedEme();})["catch"](function(err){_this4.logger_('error while creating EME key session',err);_this4.player_.error({message:'Failed to initialize media keys for EME',code:3});});};_proto.setupQualityLevels_=function setupQualityLevels_(){var _this5=this;var player=videojs$1.players[this.tech_.options_.playerId];if(!player||!player.qualityLevels||this.qualityLevels_){return;}
this.qualityLevels_=player.qualityLevels();this.masterPlaylistController_.on('selectedinitialmedia',function(){handleVhsLoadedMetadata(_this5.qualityLevels_,_this5);});this.playlists.on('mediachange',function(){handleVhsMediaChange(_this5.qualityLevels_,_this5.playlists);});};VhsHandler.version=function version$5(){return{'@videojs/http-streaming':version$1,'mux.js':version$1$1,'mpd-parser':version$2,'m3u8-parser':version$3,'aes-decrypter':version$4};};_proto.version=function version(){return this.constructor.version();};_proto.canChangeType=function canChangeType(){return SourceUpdater.canChangeType();};_proto.play=function play(){this.masterPlaylistController_.play();};_proto.setCurrentTime=function setCurrentTime(currentTime){this.masterPlaylistController_.setCurrentTime(currentTime);};_proto.duration=function duration(){return this.masterPlaylistController_.duration();};_proto.seekable=function seekable(){return this.masterPlaylistController_.seekable();};_proto.dispose=function dispose(){if(this.playbackWatcher_){this.playbackWatcher_.dispose();}
if(this.masterPlaylistController_){this.masterPlaylistController_.dispose();}
if(this.qualityLevels_){this.qualityLevels_.dispose();}
if(this.player_){delete this.player_.vhs;delete this.player_.dash;delete this.player_.hls;}
if(this.tech_&&this.tech_.vhs){delete this.tech_.vhs;}
if(this.tech_){delete this.tech_.hls;}
if(this.mediaSourceUrl_&&window_1$2.URL.revokeObjectURL){window_1$2.URL.revokeObjectURL(this.mediaSourceUrl_);this.mediaSourceUrl_=null;}
_Component.prototype.dispose.call(this);};_proto.convertToProgramTime=function convertToProgramTime(time,callback){return getProgramTime({playlist:this.masterPlaylistController_.media(),time:time,callback:callback});};_proto.seekToProgramTime=function seekToProgramTime$1(programTime,callback,pauseAfterSeek,retryCount){if(pauseAfterSeek===void 0){pauseAfterSeek=true;}
if(retryCount===void 0){retryCount=2;}
return seekToProgramTime({programTime:programTime,playlist:this.masterPlaylistController_.media(),retryCount:retryCount,pauseAfterSeek:pauseAfterSeek,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:callback});};return VhsHandler;}(Component$1);var VhsSourceHandler={name:'videojs-http-streaming',VERSION:version$1,canHandleSource:function canHandleSource(srcObj,options){if(options===void 0){options={};}
var localOptions=videojs$1.mergeOptions(videojs$1.options,options);return VhsSourceHandler.canPlayType(srcObj.type,localOptions);},handleSource:function handleSource(source,tech,options){if(options===void 0){options={};}
var localOptions=videojs$1.mergeOptions(videojs$1.options,options);tech.vhs=new VhsHandler(source,tech,localOptions);if(!videojs$1.hasOwnProperty('hls')){Object.defineProperty(tech,'hls',{get:function get(){videojs$1.log.warn('player.tech().hls is deprecated. Use player.tech().vhs instead.');return tech.vhs;},configurable:true});}
tech.vhs.xhr=xhrFactory();tech.vhs.src(source.src,source.type);return tech.vhs;},canPlayType:function canPlayType(type,options){if(options===void 0){options={};}
var _videojs$mergeOptions=videojs$1.mergeOptions(videojs$1.options,options),_videojs$mergeOptions2=_videojs$mergeOptions.vhs.overrideNative,overrideNative=_videojs$mergeOptions2===void 0?!videojs$1.browser.IS_ANY_SAFARI:_videojs$mergeOptions2;var supportedType=mediaTypes_1(type);var canUseMsePlayback=supportedType&&(!Vhs$1.supportsTypeNatively(supportedType)||overrideNative);return canUseMsePlayback?'maybe':'';}};var supportsNativeMediaSources=function supportsNativeMediaSources(){return codecs_3('avc1.4d400d,mp4a.40.2');};if(supportsNativeMediaSources()){videojs$1.getTech('Html5').registerSourceHandler(VhsSourceHandler,0);}
videojs$1.VhsHandler=VhsHandler;Object.defineProperty(videojs$1,'HlsHandler',{get:function get(){videojs$1.log.warn('videojs.HlsHandler is deprecated. Use videojs.VhsHandler instead.');return VhsHandler;},configurable:true});videojs$1.VhsSourceHandler=VhsSourceHandler;Object.defineProperty(videojs$1,'HlsSourceHandler',{get:function get(){videojs$1.log.warn('videojs.HlsSourceHandler is deprecated. '+'Use videojs.VhsSourceHandler instead.');return VhsSourceHandler;},configurable:true});videojs$1.Vhs=Vhs$1;Object.defineProperty(videojs$1,'Hls',{get:function get(){videojs$1.log.warn('videojs.Hls is deprecated. Use videojs.Vhs instead.');return Vhs$1;},configurable:true});if(!videojs$1.use){videojs$1.registerComponent('Hls',Vhs$1);videojs$1.registerComponent('Vhs',Vhs$1);}
videojs$1.options.vhs=videojs$1.options.vhs||{};videojs$1.options.hls=videojs$1.options.hls||{};if(videojs$1.registerPlugin){videojs$1.registerPlugin('reloadSourceOnError',reloadSourceOnError);}else{videojs$1.plugin('reloadSourceOnError',reloadSourceOnError);}
return videojs$1;})));!function(){!function(a){var b=a&&a.videojs;b&&(b.CDN_VERSION="7.11.4")}(window)}();