",b.$dots=a(d).appendTo(b.options.appendDots),b.$dots.find("li").first().addClass("slick-active").attr("aria-hidden","false")}},b.prototype.buildOut=function(){var b=this;b.$slides=b.$slider.children(b.options.slide+":not(.slick-cloned)").addClass("slick-slide"),b.slideCount=b.$slides.length,b.$slides.each(function(b,c){a(c).attr("data-slick-index",b).data("originalStyling",a(c).attr("style")||"")}),b.$slider.addClass("slick-slider"),b.$slideTrack=0===b.slideCount?a('').appendTo(b.$slider):b.$slides.wrapAll('').parent(),b.$list=b.$slideTrack.wrap('').parent(),b.$slideTrack.css("opacity",0),(b.options.centerMode===!0||b.options.swipeToSlide===!0)&&(b.options.slidesToScroll=1),a("img[data-lazy]",b.$slider).not("[src]").addClass("slick-loading"),b.setupInfinite(),b.buildArrows(),b.buildDots(),b.updateDots(),b.setSlideClasses("number"==typeof b.currentSlide?b.currentSlide:0),b.options.draggable===!0&&b.$list.addClass("draggable")},b.prototype.buildRows=function(){var b,c,d,e,f,g,h,a=this;if(e=document.createDocumentFragment(),g=a.$slider.children(),a.options.rows>1){for(h=a.options.slidesPerRow*a.options.rows,f=Math.ceil(g.length/h),b=0;f>b;b++){var i=document.createElement("div");for(c=0;cd.breakpoints[e]&&(f=d.breakpoints[e]));null!==f?null!==d.activeBreakpoint?(f!==d.activeBreakpoint||c)&&(d.activeBreakpoint=f,"unslick"===d.breakpointSettings[f]?d.unslick(f):(d.options=a.extend({},d.originalSettings,d.breakpointSettings[f]),b===!0&&(d.currentSlide=d.options.initialSlide),d.refresh(b)),h=f):(d.activeBreakpoint=f,"unslick"===d.breakpointSettings[f]?d.unslick(f):(d.options=a.extend({},d.originalSettings,d.breakpointSettings[f]),b===!0&&(d.currentSlide=d.options.initialSlide),d.refresh(b)),h=f):null!==d.activeBreakpoint&&(d.activeBreakpoint=null,d.options=d.originalSettings,b===!0&&(d.currentSlide=d.options.initialSlide),d.refresh(b),h=f),b||h===!1||d.$slider.trigger("breakpoint",[d,h])}},b.prototype.changeSlide=function(b,c){var f,g,h,d=this,e=a(b.target);switch(e.is("a")&&b.preventDefault(),e.is("li")||(e=e.closest("li")),h=d.slideCount%d.options.slidesToScroll!==0,f=h?0:(d.slideCount-d.currentSlide)%d.options.slidesToScroll,b.data.message){case"previous":g=0===f?d.options.slidesToScroll:d.options.slidesToShow-f,d.slideCount>d.options.slidesToShow&&d.slideHandler(d.currentSlide-g,!1,c);break;case"next":g=0===f?d.options.slidesToScroll:f,d.slideCount>d.options.slidesToShow&&d.slideHandler(d.currentSlide+g,!1,c);break;case"index":var i=0===b.data.index?0:b.data.index||e.index()*d.options.slidesToScroll;d.slideHandler(d.checkNavigable(i),!1,c),e.children().trigger("focus");break;default:return}},b.prototype.checkNavigable=function(a){var c,d,b=this;if(c=b.getNavigableIndexes(),d=0,a>c[c.length-1])a=c[c.length-1];else for(var e in c){if(ab.options.slidesToShow&&(b.$prevArrow&&b.$prevArrow.off("click.slick",b.changeSlide),b.$nextArrow&&b.$nextArrow.off("click.slick",b.changeSlide)),b.$list.off("touchstart.slick mousedown.slick",b.swipeHandler),b.$list.off("touchmove.slick mousemove.slick",b.swipeHandler),b.$list.off("touchend.slick mouseup.slick",b.swipeHandler),b.$list.off("touchcancel.slick mouseleave.slick",b.swipeHandler),b.$list.off("click.slick",b.clickHandler),a(document).off(b.visibilityChange,b.visibility),b.$list.off("mouseenter.slick",a.proxy(b.setPaused,b,!0)),b.$list.off("mouseleave.slick",a.proxy(b.setPaused,b,!1)),b.options.accessibility===!0&&b.$list.off("keydown.slick",b.keyHandler),b.options.focusOnSelect===!0&&a(b.$slideTrack).children().off("click.slick",b.selectHandler),a(window).off("orientationchange.slick.slick-"+b.instanceUid,b.orientationChange),a(window).off("resize.slick.slick-"+b.instanceUid,b.resize),a("[draggable!=true]",b.$slideTrack).off("dragstart",b.preventDefault),a(window).off("load.slick.slick-"+b.instanceUid,b.setPosition),a(document).off("ready.slick.slick-"+b.instanceUid,b.setPosition)},b.prototype.cleanUpRows=function(){var b,a=this;a.options.rows>1&&(b=a.$slides.children().children(),b.removeAttr("style"),a.$slider.html(b))},b.prototype.clickHandler=function(a){var b=this;b.shouldClick===!1&&(a.stopImmediatePropagation(),a.stopPropagation(),a.preventDefault())},b.prototype.destroy=function(b){var c=this;c.autoPlayClear(),c.touchObject={},c.cleanUpEvents(),a(".slick-cloned",c.$slider).detach(),c.$dots&&c.$dots.remove(),c.$prevArrow&&c.$prevArrow.length&&(c.$prevArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),c.htmlExpr.test(c.options.prevArrow)&&c.$prevArrow.remove()),c.$nextArrow&&c.$nextArrow.length&&(c.$nextArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),c.htmlExpr.test(c.options.nextArrow)&&c.$nextArrow.remove()),c.$slides&&(c.$slides.removeClass("slick-slide slick-active slick-center slick-visible slick-current").removeAttr("aria-hidden").removeAttr("data-slick-index").each(function(){a(this).attr("style",a(this).data("originalStyling"))}),c.$slideTrack.children(this.options.slide).detach(),c.$slideTrack.detach(),c.$list.detach(),c.$slider.append(c.$slides)),c.cleanUpRows(),c.$slider.removeClass("slick-slider"),c.$slider.removeClass("slick-initialized"),c.unslicked=!0,b||c.$slider.trigger("destroy",[c])},b.prototype.disableTransition=function(a){var b=this,c={};c[b.transitionType]="",b.options.fade===!1?b.$slideTrack.css(c):b.$slides.eq(a).css(c)},b.prototype.fadeSlide=function(a,b){var c=this;c.cssTransitions===!1?(c.$slides.eq(a).css({zIndex:c.options.zIndex}),c.$slides.eq(a).animate({opacity:1},c.options.speed,c.options.easing,b)):(c.applyTransition(a),c.$slides.eq(a).css({opacity:1,zIndex:c.options.zIndex}),b&&setTimeout(function(){c.disableTransition(a),b.call()},c.options.speed))},b.prototype.fadeSlideOut=function(a){var b=this;b.cssTransitions===!1?b.$slides.eq(a).animate({opacity:0,zIndex:b.options.zIndex-2},b.options.speed,b.options.easing):(b.applyTransition(a),b.$slides.eq(a).css({opacity:0,zIndex:b.options.zIndex-2}))},b.prototype.filterSlides=b.prototype.slickFilter=function(a){var b=this;null!==a&&(b.$slidesCache=b.$slides,b.unload(),b.$slideTrack.children(this.options.slide).detach(),b.$slidesCache.filter(a).appendTo(b.$slideTrack),b.reinit())},b.prototype.getCurrent=b.prototype.slickCurrentSlide=function(){var a=this;return a.currentSlide},b.prototype.getDotCount=function(){var a=this,b=0,c=0,d=0;if(a.options.infinite===!0)for(;bb.options.slidesToShow&&(b.slideOffset=b.slideWidth*b.options.slidesToShow*-1,e=d*b.options.slidesToShow*-1),b.slideCount%b.options.slidesToScroll!==0&&a+b.options.slidesToScroll>b.slideCount&&b.slideCount>b.options.slidesToShow&&(a>b.slideCount?(b.slideOffset=(b.options.slidesToShow-(a-b.slideCount))*b.slideWidth*-1,e=(b.options.slidesToShow-(a-b.slideCount))*d*-1):(b.slideOffset=b.slideCount%b.options.slidesToScroll*b.slideWidth*-1,e=b.slideCount%b.options.slidesToScroll*d*-1))):a+b.options.slidesToShow>b.slideCount&&(b.slideOffset=(a+b.options.slidesToShow-b.slideCount)*b.slideWidth,e=(a+b.options.slidesToShow-b.slideCount)*d),b.slideCount<=b.options.slidesToShow&&(b.slideOffset=0,e=0),b.options.centerMode===!0&&b.options.infinite===!0?b.slideOffset+=b.slideWidth*Math.floor(b.options.slidesToShow/2)-b.slideWidth:b.options.centerMode===!0&&(b.slideOffset=0,b.slideOffset+=b.slideWidth*Math.floor(b.options.slidesToShow/2)),c=b.options.vertical===!1?a*b.slideWidth*-1+b.slideOffset:a*d*-1+e,b.options.variableWidth===!0&&(f=b.slideCount<=b.options.slidesToShow||b.options.infinite===!1?b.$slideTrack.children(".slick-slide").eq(a):b.$slideTrack.children(".slick-slide").eq(a+b.options.slidesToShow),c=b.options.rtl===!0?f[0]?-1*(b.$slideTrack.width()-f[0].offsetLeft-f.width()):0:f[0]?-1*f[0].offsetLeft:0,b.options.centerMode===!0&&(f=b.slideCount<=b.options.slidesToShow||b.options.infinite===!1?b.$slideTrack.children(".slick-slide").eq(a):b.$slideTrack.children(".slick-slide").eq(a+b.options.slidesToShow+1),c=b.options.rtl===!0?f[0]?-1*(b.$slideTrack.width()-f[0].offsetLeft-f.width()):0:f[0]?-1*f[0].offsetLeft:0,c+=(b.$list.width()-f.outerWidth())/2)),c},b.prototype.getOption=b.prototype.slickGetOption=function(a){var b=this;return b.options[a]},b.prototype.getNavigableIndexes=function(){var e,a=this,b=0,c=0,d=[];for(a.options.infinite===!1?e=a.slideCount:(b=-1*a.options.slidesToScroll,c=-1*a.options.slidesToScroll,e=2*a.slideCount);e>b;)d.push(b),b=c+a.options.slidesToScroll,c+=a.options.slidesToScroll<=a.options.slidesToShow?a.options.slidesToScroll:a.options.slidesToShow;return d},b.prototype.getSlick=function(){return this},b.prototype.getSlideCount=function(){var c,d,e,b=this;return e=b.options.centerMode===!0?b.slideWidth*Math.floor(b.options.slidesToShow/2):0,b.options.swipeToSlide===!0?(b.$slideTrack.find(".slick-slide").each(function(c,f){return f.offsetLeft-e+a(f).outerWidth()/2>-1*b.swipeLeft?(d=f,!1):void 0}),c=Math.abs(a(d).attr("data-slick-index")-b.currentSlide)||1):b.options.slidesToScroll},b.prototype.goTo=b.prototype.slickGoTo=function(a,b){var c=this;c.changeSlide({data:{message:"index",index:parseInt(a)}},b)},b.prototype.init=function(b){var c=this;a(c.$slider).hasClass("slick-initialized")||(a(c.$slider).addClass("slick-initialized"),c.buildRows(),c.buildOut(),c.setProps(),c.startLoad(),c.loadSlider(),c.initializeEvents(),c.updateArrows(),c.updateDots()),b&&c.$slider.trigger("init",[c]),c.options.accessibility===!0&&c.initADA()},b.prototype.initArrowEvents=function(){var a=this;a.options.arrows===!0&&a.slideCount>a.options.slidesToShow&&(a.$prevArrow.on("click.slick",{message:"previous"},a.changeSlide),a.$nextArrow.on("click.slick",{message:"next"},a.changeSlide))},b.prototype.initDotEvents=function(){var b=this;b.options.dots===!0&&b.slideCount>b.options.slidesToShow&&a("li",b.$dots).on("click.slick",{message:"index"},b.changeSlide),b.options.dots===!0&&b.options.pauseOnDotsHover===!0&&b.options.autoplay===!0&&a("li",b.$dots).on("mouseenter.slick",a.proxy(b.setPaused,b,!0)).on("mouseleave.slick",a.proxy(b.setPaused,b,!1))},b.prototype.initializeEvents=function(){var b=this;b.initArrowEvents(),b.initDotEvents(),b.$list.on("touchstart.slick mousedown.slick",{action:"start"},b.swipeHandler),b.$list.on("touchmove.slick mousemove.slick",{action:"move"},b.swipeHandler),b.$list.on("touchend.slick mouseup.slick",{action:"end"},b.swipeHandler),b.$list.on("touchcancel.slick mouseleave.slick",{action:"end"},b.swipeHandler),b.$list.on("click.slick",b.clickHandler),a(document).on(b.visibilityChange,a.proxy(b.visibility,b)),b.$list.on("mouseenter.slick",a.proxy(b.setPaused,b,!0)),b.$list.on("mouseleave.slick",a.proxy(b.setPaused,b,!1)),b.options.accessibility===!0&&b.$list.on("keydown.slick",b.keyHandler),b.options.focusOnSelect===!0&&a(b.$slideTrack).children().on("click.slick",b.selectHandler),a(window).on("orientationchange.slick.slick-"+b.instanceUid,a.proxy(b.orientationChange,b)),a(window).on("resize.slick.slick-"+b.instanceUid,a.proxy(b.resize,b)),a("[draggable!=true]",b.$slideTrack).on("dragstart",b.preventDefault),a(window).on("load.slick.slick-"+b.instanceUid,b.setPosition),a(document).on("ready.slick.slick-"+b.instanceUid,b.setPosition)},b.prototype.initUI=function(){var a=this;a.options.arrows===!0&&a.slideCount>a.options.slidesToShow&&(a.$prevArrow.show(),a.$nextArrow.show()),a.options.dots===!0&&a.slideCount>a.options.slidesToShow&&a.$dots.show(),a.options.autoplay===!0&&a.autoPlay()},b.prototype.keyHandler=function(a){var b=this;a.target.tagName.match("TEXTAREA|INPUT|SELECT")||(37===a.keyCode&&b.options.accessibility===!0?b.changeSlide({data:{message:"previous"}}):39===a.keyCode&&b.options.accessibility===!0&&b.changeSlide({data:{message:"next"}}))},b.prototype.lazyLoad=function(){function g(b){a("img[data-lazy]",b).each(function(){var b=a(this),c=a(this).attr("data-lazy"),d=document.createElement("img");d.onload=function(){b.animate({opacity:0},100,function(){b.attr("src",c).animate({opacity:1},200,function(){b.removeAttr("data-lazy").removeClass("slick-loading")})})},d.src=c})}var c,d,e,f,b=this;b.options.centerMode===!0?b.options.infinite===!0?(e=b.currentSlide+(b.options.slidesToShow/2+1),f=e+b.options.slidesToShow+2):(e=Math.max(0,b.currentSlide-(b.options.slidesToShow/2+1)),f=2+(b.options.slidesToShow/2+1)+b.currentSlide):(e=b.options.infinite?b.options.slidesToShow+b.currentSlide:b.currentSlide,f=e+b.options.slidesToShow,b.options.fade===!0&&(e>0&&e--,f<=b.slideCount&&f++)),c=b.$slider.find(".slick-slide").slice(e,f),g(c),b.slideCount<=b.options.slidesToShow?(d=b.$slider.find(".slick-slide"),g(d)):b.currentSlide>=b.slideCount-b.options.slidesToShow?(d=b.$slider.find(".slick-cloned").slice(0,b.options.slidesToShow),g(d)):0===b.currentSlide&&(d=b.$slider.find(".slick-cloned").slice(-1*b.options.slidesToShow),g(d))},b.prototype.loadSlider=function(){var a=this;a.setPosition(),a.$slideTrack.css({opacity:1}),a.$slider.removeClass("slick-loading"),a.initUI(),"progressive"===a.options.lazyLoad&&a.progressiveLazyLoad()},b.prototype.next=b.prototype.slickNext=function(){var a=this;a.changeSlide({data:{message:"next"}})},b.prototype.orientationChange=function(){var a=this;a.checkResponsive(),a.setPosition()},b.prototype.pause=b.prototype.slickPause=function(){var a=this;a.autoPlayClear(),a.paused=!0},b.prototype.play=b.prototype.slickPlay=function(){var a=this;a.paused=!1,a.autoPlay()},b.prototype.postSlide=function(a){var b=this;b.$slider.trigger("afterChange",[b,a]),b.animating=!1,b.setPosition(),b.swipeLeft=null,b.options.autoplay===!0&&b.paused===!1&&b.autoPlay(),b.options.accessibility===!0&&b.initADA()},b.prototype.prev=b.prototype.slickPrev=function(){var a=this;a.changeSlide({data:{message:"previous"}})},b.prototype.preventDefault=function(a){a.preventDefault()},b.prototype.progressiveLazyLoad=function(){var c,d,b=this;c=a("img[data-lazy]",b.$slider).length,c>0&&(d=a("img[data-lazy]",b.$slider).first(),d.attr("src",null),d.attr("src",d.attr("data-lazy")).removeClass("slick-loading").load(function(){d.removeAttr("data-lazy"),b.progressiveLazyLoad(),b.options.adaptiveHeight===!0&&b.setPosition()}).error(function(){d.removeAttr("data-lazy"),b.progressiveLazyLoad()}))},b.prototype.refresh=function(b){var d,e,c=this;e=c.slideCount-c.options.slidesToShow,c.options.infinite||(c.slideCount<=c.options.slidesToShow?c.currentSlide=0:c.currentSlide>e&&(c.currentSlide=e)),d=c.currentSlide,c.destroy(!0),a.extend(c,c.initials,{currentSlide:d}),c.init(),b||c.changeSlide({data:{message:"index",index:d}},!1)},b.prototype.registerBreakpoints=function(){var c,d,e,b=this,f=b.options.responsive||null;if("array"===a.type(f)&&f.length){b.respondTo=b.options.respondTo||"window";for(c in f)if(e=b.breakpoints.length-1,d=f[c].breakpoint,f.hasOwnProperty(c)){for(;e>=0;)b.breakpoints[e]&&b.breakpoints[e]===d&&b.breakpoints.splice(e,1),e--;b.breakpoints.push(d),b.breakpointSettings[d]=f[c].settings}b.breakpoints.sort(function(a,c){return b.options.mobileFirst?a-c:c-a})}},b.prototype.reinit=function(){var b=this;b.$slides=b.$slideTrack.children(b.options.slide).addClass("slick-slide"),b.slideCount=b.$slides.length,b.currentSlide>=b.slideCount&&0!==b.currentSlide&&(b.currentSlide=b.currentSlide-b.options.slidesToScroll),b.slideCount<=b.options.slidesToShow&&(b.currentSlide=0),b.registerBreakpoints(),b.setProps(),b.setupInfinite(),b.buildArrows(),b.updateArrows(),b.initArrowEvents(),b.buildDots(),b.updateDots(),b.initDotEvents(),b.checkResponsive(!1,!0),b.options.focusOnSelect===!0&&a(b.$slideTrack).children().on("click.slick",b.selectHandler),b.setSlideClasses(0),b.setPosition(),b.$slider.trigger("reInit",[b]),b.options.autoplay===!0&&b.focusHandler()},b.prototype.resize=function(){var b=this;a(window).width()!==b.windowWidth&&(clearTimeout(b.windowDelay),b.windowDelay=window.setTimeout(function(){b.windowWidth=a(window).width(),b.checkResponsive(),b.unslicked||b.setPosition()},50))},b.prototype.removeSlide=b.prototype.slickRemove=function(a,b,c){var d=this;return"boolean"==typeof a?(b=a,a=b===!0?0:d.slideCount-1):a=b===!0?--a:a,d.slideCount<1||0>a||a>d.slideCount-1?!1:(d.unload(),c===!0?d.$slideTrack.children().remove():d.$slideTrack.children(this.options.slide).eq(a).remove(),d.$slides=d.$slideTrack.children(this.options.slide),d.$slideTrack.children(this.options.slide).detach(),d.$slideTrack.append(d.$slides),d.$slidesCache=d.$slides,void d.reinit())},b.prototype.setCSS=function(a){var d,e,b=this,c={};b.options.rtl===!0&&(a=-a),d="left"==b.positionProp?Math.ceil(a)+"px":"0px",e="top"==b.positionProp?Math.ceil(a)+"px":"0px",c[b.positionProp]=a,b.transformsEnabled===!1?b.$slideTrack.css(c):(c={},b.cssTransitions===!1?(c[b.animType]="translate("+d+", "+e+")",b.$slideTrack.css(c)):(c[b.animType]="translate3d("+d+", "+e+", 0px)",b.$slideTrack.css(c)))},b.prototype.setDimensions=function(){var a=this;a.options.vertical===!1?a.options.centerMode===!0&&a.$list.css({padding:"0px "+a.options.centerPadding}):(a.$list.height(a.$slides.first().outerHeight(!0)*a.options.slidesToShow),a.options.centerMode===!0&&a.$list.css({padding:a.options.centerPadding+" 0px"})),a.listWidth=a.$list.width(),a.listHeight=a.$list.height(),a.options.vertical===!1&&a.options.variableWidth===!1?(a.slideWidth=Math.ceil(a.listWidth/a.options.slidesToShow),a.$slideTrack.width(Math.ceil(a.slideWidth*a.$slideTrack.children(".slick-slide").length))):a.options.variableWidth===!0?a.$slideTrack.width(5e3*a.slideCount):(a.slideWidth=Math.ceil(a.listWidth),a.$slideTrack.height(Math.ceil(a.$slides.first().outerHeight(!0)*a.$slideTrack.children(".slick-slide").length)));var b=a.$slides.first().outerWidth(!0)-a.$slides.first().width();a.options.variableWidth===!1&&a.$slideTrack.children(".slick-slide").width(a.slideWidth-b)},b.prototype.setFade=function(){var c,b=this;b.$slides.each(function(d,e){c=b.slideWidth*d*-1,b.options.rtl===!0?a(e).css({position:"relative",right:c,top:0,zIndex:b.options.zIndex-2,opacity:0}):a(e).css({position:"relative",left:c,top:0,zIndex:b.options.zIndex-2,opacity:0})}),b.$slides.eq(b.currentSlide).css({zIndex:b.options.zIndex-1,opacity:1})},b.prototype.setHeight=function(){var a=this;if(1===a.options.slidesToShow&&a.options.adaptiveHeight===!0&&a.options.vertical===!1){var b=a.$slides.eq(a.currentSlide).outerHeight(!0);a.$list.css("height",b)}},b.prototype.setOption=b.prototype.slickSetOption=function(b,c,d){var f,g,e=this;if("responsive"===b&&"array"===a.type(c))for(g in c)if("array"!==a.type(e.options.responsive))e.options.responsive=[c[g]];else{for(f=e.options.responsive.length-1;f>=0;)e.options.responsive[f].breakpoint===c[g].breakpoint&&e.options.responsive.splice(f,1),f--;e.options.responsive.push(c[g])}else e.options[b]=c;d===!0&&(e.unload(),e.reinit())},b.prototype.setPosition=function(){var a=this;a.setDimensions(),a.setHeight(),a.options.fade===!1?a.setCSS(a.getLeft(a.currentSlide)):a.setFade(),a.$slider.trigger("setPosition",[a])},b.prototype.setProps=function(){var a=this,b=document.body.style;a.positionProp=a.options.vertical===!0?"top":"left","top"===a.positionProp?a.$slider.addClass("slick-vertical"):a.$slider.removeClass("slick-vertical"),(void 0!==b.WebkitTransition||void 0!==b.MozTransition||void 0!==b.msTransition)&&a.options.useCSS===!0&&(a.cssTransitions=!0),a.options.fade&&("number"==typeof a.options.zIndex?a.options.zIndex<3&&(a.options.zIndex=3):a.options.zIndex=a.defaults.zIndex),void 0!==b.OTransform&&(a.animType="OTransform",a.transformType="-o-transform",a.transitionType="OTransition",void 0===b.perspectiveProperty&&void 0===b.webkitPerspective&&(a.animType=!1)),void 0!==b.MozTransform&&(a.animType="MozTransform",a.transformType="-moz-transform",a.transitionType="MozTransition",void 0===b.perspectiveProperty&&void 0===b.MozPerspective&&(a.animType=!1)),void 0!==b.webkitTransform&&(a.animType="webkitTransform",a.transformType="-webkit-transform",a.transitionType="webkitTransition",void 0===b.perspectiveProperty&&void 0===b.webkitPerspective&&(a.animType=!1)),void 0!==b.msTransform&&(a.animType="msTransform",a.transformType="-ms-transform",a.transitionType="msTransition",void 0===b.msTransform&&(a.animType=!1)),void 0!==b.transform&&a.animType!==!1&&(a.animType="transform",a.transformType="transform",a.transitionType="transition"),a.transformsEnabled=a.options.useTransform&&null!==a.animType&&a.animType!==!1},b.prototype.setSlideClasses=function(a){var c,d,e,f,b=this;d=b.$slider.find(".slick-slide").removeClass("slick-active slick-center slick-current").attr("aria-hidden","true"),b.$slides.eq(a).addClass("slick-current"),b.options.centerMode===!0?(c=Math.floor(b.options.slidesToShow/2),b.options.infinite===!0&&(a>=c&&a<=b.slideCount-1-c?b.$slides.slice(a-c,a+c+1).addClass("slick-active").attr("aria-hidden","false"):(e=b.options.slidesToShow+a,d.slice(e-c+1,e+c+2).addClass("slick-active").attr("aria-hidden","false")),0===a?d.eq(d.length-1-b.options.slidesToShow).addClass("slick-center"):a===b.slideCount-1&&d.eq(b.options.slidesToShow).addClass("slick-center")),b.$slides.eq(a).addClass("slick-center")):a>=0&&a<=b.slideCount-b.options.slidesToShow?b.$slides.slice(a,a+b.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"):d.length<=b.options.slidesToShow?d.addClass("slick-active").attr("aria-hidden","false"):(f=b.slideCount%b.options.slidesToShow,e=b.options.infinite===!0?b.options.slidesToShow+a:a,b.options.slidesToShow==b.options.slidesToScroll&&b.slideCount-ab.options.slidesToShow)){for(e=b.options.centerMode===!0?b.options.slidesToShow+1:b.options.slidesToShow,c=b.slideCount;c>b.slideCount-e;c-=1)d=c-1,a(b.$slides[d]).clone(!0).attr("id","").attr("data-slick-index",d-b.slideCount).prependTo(b.$slideTrack).addClass("slick-cloned");for(c=0;e>c;c+=1)d=c,a(b.$slides[d]).clone(!0).attr("id","").attr("data-slick-index",d+b.slideCount).appendTo(b.$slideTrack).addClass("slick-cloned");b.$slideTrack.find(".slick-cloned").find("[id]").each(function(){a(this).attr("id","")})}},b.prototype.setPaused=function(a){var b=this;b.options.autoplay===!0&&b.options.pauseOnHover===!0&&(b.paused=a,a?b.autoPlayClear():b.autoPlay())},b.prototype.selectHandler=function(b){var c=this,d=a(b.target).is(".slick-slide")?a(b.target):a(b.target).parents(".slick-slide"),e=parseInt(d.attr("data-slick-index"));return e||(e=0),c.slideCount<=c.options.slidesToShow?(c.setSlideClasses(e),void c.asNavFor(e)):void c.slideHandler(e)},b.prototype.slideHandler=function(a,b,c){var d,e,f,g,h=null,i=this;return b=b||!1,i.animating===!0&&i.options.waitForAnimate===!0||i.options.fade===!0&&i.currentSlide===a||i.slideCount<=i.options.slidesToShow?void 0:(b===!1&&i.asNavFor(a),d=a,h=i.getLeft(d),g=i.getLeft(i.currentSlide),i.currentLeft=null===i.swipeLeft?g:i.swipeLeft,i.options.infinite===!1&&i.options.centerMode===!1&&(0>a||a>i.getDotCount()*i.options.slidesToScroll)?void(i.options.fade===!1&&(d=i.currentSlide,c!==!0?i.animateSlide(g,function(){i.postSlide(d);
}):i.postSlide(d))):i.options.infinite===!1&&i.options.centerMode===!0&&(0>a||a>i.slideCount-i.options.slidesToScroll)?void(i.options.fade===!1&&(d=i.currentSlide,c!==!0?i.animateSlide(g,function(){i.postSlide(d)}):i.postSlide(d))):(i.options.autoplay===!0&&clearInterval(i.autoPlayTimer),e=0>d?i.slideCount%i.options.slidesToScroll!==0?i.slideCount-i.slideCount%i.options.slidesToScroll:i.slideCount+d:d>=i.slideCount?i.slideCount%i.options.slidesToScroll!==0?0:d-i.slideCount:d,i.animating=!0,i.$slider.trigger("beforeChange",[i,i.currentSlide,e]),f=i.currentSlide,i.currentSlide=e,i.setSlideClasses(i.currentSlide),i.updateDots(),i.updateArrows(),i.options.fade===!0?(c!==!0?(i.fadeSlideOut(f),i.fadeSlide(e,function(){i.postSlide(e)})):i.postSlide(e),void i.animateHeight()):void(c!==!0?i.animateSlide(h,function(){i.postSlide(e)}):i.postSlide(e))))},b.prototype.startLoad=function(){var a=this;a.options.arrows===!0&&a.slideCount>a.options.slidesToShow&&(a.$prevArrow.hide(),a.$nextArrow.hide()),a.options.dots===!0&&a.slideCount>a.options.slidesToShow&&a.$dots.hide(),a.$slider.addClass("slick-loading")},b.prototype.swipeDirection=function(){var a,b,c,d,e=this;return a=e.touchObject.startX-e.touchObject.curX,b=e.touchObject.startY-e.touchObject.curY,c=Math.atan2(b,a),d=Math.round(180*c/Math.PI),0>d&&(d=360-Math.abs(d)),45>=d&&d>=0?e.options.rtl===!1?"left":"right":360>=d&&d>=315?e.options.rtl===!1?"left":"right":d>=135&&225>=d?e.options.rtl===!1?"right":"left":e.options.verticalSwiping===!0?d>=35&&135>=d?"left":"right":"vertical"},b.prototype.swipeEnd=function(a){var c,b=this;if(b.dragging=!1,b.shouldClick=b.touchObject.swipeLength>10?!1:!0,void 0===b.touchObject.curX)return!1;if(b.touchObject.edgeHit===!0&&b.$slider.trigger("edge",[b,b.swipeDirection()]),b.touchObject.swipeLength>=b.touchObject.minSwipe)switch(b.swipeDirection()){case"left":c=b.options.swipeToSlide?b.checkNavigable(b.currentSlide+b.getSlideCount()):b.currentSlide+b.getSlideCount(),b.slideHandler(c),b.currentDirection=0,b.touchObject={},b.$slider.trigger("swipe",[b,"left"]);break;case"right":c=b.options.swipeToSlide?b.checkNavigable(b.currentSlide-b.getSlideCount()):b.currentSlide-b.getSlideCount(),b.slideHandler(c),b.currentDirection=1,b.touchObject={},b.$slider.trigger("swipe",[b,"right"])}else b.touchObject.startX!==b.touchObject.curX&&(b.slideHandler(b.currentSlide),b.touchObject={})},b.prototype.swipeHandler=function(a){var b=this;if(!(b.options.swipe===!1||"ontouchend"in document&&b.options.swipe===!1||b.options.draggable===!1&&-1!==a.type.indexOf("mouse")))switch(b.touchObject.fingerCount=a.originalEvent&&void 0!==a.originalEvent.touches?a.originalEvent.touches.length:1,b.touchObject.minSwipe=b.listWidth/b.options.touchThreshold,b.options.verticalSwiping===!0&&(b.touchObject.minSwipe=b.listHeight/b.options.touchThreshold),a.data.action){case"start":b.swipeStart(a);break;case"move":b.swipeMove(a);break;case"end":b.swipeEnd(a)}},b.prototype.swipeMove=function(a){var d,e,f,g,h,b=this;return h=void 0!==a.originalEvent?a.originalEvent.touches:null,!b.dragging||h&&1!==h.length?!1:(d=b.getLeft(b.currentSlide),b.touchObject.curX=void 0!==h?h[0].pageX:a.clientX,b.touchObject.curY=void 0!==h?h[0].pageY:a.clientY,b.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(b.touchObject.curX-b.touchObject.startX,2))),b.options.verticalSwiping===!0&&(b.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(b.touchObject.curY-b.touchObject.startY,2)))),e=b.swipeDirection(),"vertical"!==e?(void 0!==a.originalEvent&&b.touchObject.swipeLength>4&&a.preventDefault(),g=(b.options.rtl===!1?1:-1)*(b.touchObject.curX>b.touchObject.startX?1:-1),b.options.verticalSwiping===!0&&(g=b.touchObject.curY>b.touchObject.startY?1:-1),f=b.touchObject.swipeLength,b.touchObject.edgeHit=!1,b.options.infinite===!1&&(0===b.currentSlide&&"right"===e||b.currentSlide>=b.getDotCount()&&"left"===e)&&(f=b.touchObject.swipeLength*b.options.edgeFriction,b.touchObject.edgeHit=!0),b.options.vertical===!1?b.swipeLeft=d+f*g:b.swipeLeft=d+f*(b.$list.height()/b.listWidth)*g,b.options.verticalSwiping===!0&&(b.swipeLeft=d+f*g),b.options.fade===!0||b.options.touchMove===!1?!1:b.animating===!0?(b.swipeLeft=null,!1):void b.setCSS(b.swipeLeft)):void 0)},b.prototype.swipeStart=function(a){var c,b=this;return 1!==b.touchObject.fingerCount||b.slideCount<=b.options.slidesToShow?(b.touchObject={},!1):(void 0!==a.originalEvent&&void 0!==a.originalEvent.touches&&(c=a.originalEvent.touches[0]),b.touchObject.startX=b.touchObject.curX=void 0!==c?c.pageX:a.clientX,b.touchObject.startY=b.touchObject.curY=void 0!==c?c.pageY:a.clientY,void(b.dragging=!0))},b.prototype.unfilterSlides=b.prototype.slickUnfilter=function(){var a=this;null!==a.$slidesCache&&(a.unload(),a.$slideTrack.children(this.options.slide).detach(),a.$slidesCache.appendTo(a.$slideTrack),a.reinit())},b.prototype.unload=function(){var b=this;a(".slick-cloned",b.$slider).remove(),b.$dots&&b.$dots.remove(),b.$prevArrow&&b.htmlExpr.test(b.options.prevArrow)&&b.$prevArrow.remove(),b.$nextArrow&&b.htmlExpr.test(b.options.nextArrow)&&b.$nextArrow.remove(),b.$slides.removeClass("slick-slide slick-active slick-visible slick-current").attr("aria-hidden","true").css("width","")},b.prototype.unslick=function(a){var b=this;b.$slider.trigger("unslick",[b,a]),b.destroy()},b.prototype.updateArrows=function(){var b,a=this;b=Math.floor(a.options.slidesToShow/2),a.options.arrows===!0&&a.slideCount>a.options.slidesToShow&&!a.options.infinite&&(a.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false"),a.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false"),0===a.currentSlide?(a.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true"),a.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false")):a.currentSlide>=a.slideCount-a.options.slidesToShow&&a.options.centerMode===!1?(a.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),a.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")):a.currentSlide>=a.slideCount-1&&a.options.centerMode===!0&&(a.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),a.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")))},b.prototype.updateDots=function(){var a=this;null!==a.$dots&&(a.$dots.find("li").removeClass("slick-active").attr("aria-hidden","true"),a.$dots.find("li").eq(Math.floor(a.currentSlide/a.options.slidesToScroll)).addClass("slick-active").attr("aria-hidden","false"))},b.prototype.visibility=function(){var a=this;document[a.hidden]?(a.paused=!0,a.autoPlayClear()):a.options.autoplay===!0&&(a.paused=!1,a.autoPlay())},b.prototype.initADA=function(){var b=this;b.$slides.add(b.$slideTrack.find(".slick-cloned")).attr({"aria-hidden":"true",tabindex:"-1"}).find("a, input, button, select").attr({tabindex:"-1"}),b.$slideTrack.attr("role","listbox"),b.$slides.not(b.$slideTrack.find(".slick-cloned")).each(function(c){a(this).attr({role:"option","aria-describedby":"slick-slide"+b.instanceUid+c})}),null!==b.$dots&&b.$dots.attr("role","tablist").find("li").each(function(c){a(this).attr({role:"presentation","aria-selected":"false","aria-controls":"navigation"+b.instanceUid+c,id:"slick-slide"+b.instanceUid+c})}).first().attr("aria-selected","true").end().find("button").attr("role","button").end().closest("div").attr("role","toolbar"),b.activateADA()},b.prototype.activateADA=function(){var a=this;a.$slideTrack.find(".slick-active").attr({"aria-hidden":"false"}).find("a, input, button, select").attr({tabindex:"0"})},b.prototype.focusHandler=function(){var b=this;b.$slider.on("focus.slick blur.slick","*",function(c){c.stopImmediatePropagation();var d=a(this);setTimeout(function(){b.isPlay&&(d.is(":focus")?(b.autoPlayClear(),b.paused=!0):(b.paused=!1,b.autoPlay()))},0)})},a.fn.slick=function(){var f,g,a=this,c=arguments[0],d=Array.prototype.slice.call(arguments,1),e=a.length;for(f=0;e>f;f++)if("object"==typeof c||"undefined"==typeof c?a[f].slick=new b(a[f],c):g=a[f].slick[c].apply(a[f].slick,d),"undefined"!=typeof g)return g;return a}});;
var prodcat=prodcat||{},generic=generic||{};prodcat.ui=prodcat.ui||{},prodcat.data=prodcat.data||{},function(e){Drupal.behaviors.regimenBuilder={attached:!1,isDesktop:!1,nodes:{},selectors:{regimenBuilderBlock:".js-elc-regimen-builder-block-v1",product:".js-product",productCarousel:".js-elc-regimen-product-carousel",productItemHeadline:".js-elc-regimen-product-item-headline",productItemContent:".js-elc-regimen-product-item-content",productCheckbox:".js-elc-regimen-product-checkbox",productImage:".js-elc-regimen-product-image",productTitle:".js-elc-regimen-product-title",productSkuLabel:".js-elc-regimen-product-size-label, .js-elc-regimen-product-shade-label",productSizeDropdown:".js-elc-regimen-product-sizes-dropdown",productShadeDropdown:".js-elc-regimen-product-shades-dropdown",productShadeDropdownSelector:".js-elc-regimen-product-shades-dropdown-selector",productShadeDropdownColor:".js-elc-regimen-product-shades-dropdown-color",productRating:".js-elc-regimen-product-rating",productRatingAverage:".js-elc-regimen-product-rating-average",productRatingStars:".js-elc-regimen-product-rating-stars",productRatingTotal:".js-elc-regimen-product-rating-total",productPrice:".js-formatted-price",productPrice2:".js-formatted-price2",productUnitPrice:".js-formatted-unit-price",productInventoryStatus:".js-elc-regimen-product-inventory-status",totalPrice:".js-elc-regimen-total-price .js-mantle-custom-text",atbCta:".js-elc-regimen-atb-cta .js-elc-button",atbCtaSingular:".js-elc-regimen-atb-cta-singular .js-elc-button",atbCtaNoItems:".js-elc-regimen-atb-cta-no-items .js-elc-button"},productShadeDropdownSelectboxClasses:{classSelector:"js-elc-regimen-product-shades-dropdown-selector",classColorSpan:"elc-regimen-builder-block__product-sku-select-shades-color js-elc-regimen-product-shades-dropdown-color"},attach:function(t){var o=this;o.attached||(o.attached=!0,o.updateIsDesktop(),e(o.selectors.regimenBuilderBlock,t).each((function(){o.setup(e(this))})))},setup:function(e){var t=this;t.getDom(e),t.setEvents(e),t.init(e)},getDom:function(t){var o=this;t.nodes={},t.nodes.$product=e(o.selectors.product,t),t.nodes.$selectedProducts=t.nodes.$product,t.nodes.$productCarousel=e(o.selectors.productCarousel,t),t.nodes.$productItemHeadline=e(o.selectors.productItemHeadline,t),t.nodes.$productItemContent=e(o.selectors.productItemContent,t),t.nodes.$productCheckbox=e(o.selectors.productCheckbox,t),t.nodes.$productImage=e(o.selectors.productImage,t),t.nodes.$productTitle=e(o.selectors.productTitle,t),t.nodes.$productSkuLabel=e(o.selectors.productSkuLabel,t),t.nodes.$productSizeDropdown=e(o.selectors.productSizeDropdown,t),t.nodes.$productShadeDropdown=e(o.selectors.productShadeDropdown,t),t.nodes.$productRating=e(o.selectors.productRating,t),t.nodes.$totalPrice=e(o.selectors.totalPrice,t),t.nodes.$atbCta=e(o.selectors.atbCta,t),t.nodes.$atbCtaSingular=e(o.selectors.atbCtaSingular,t),t.nodes.$atbCtaNoItems=e(o.selectors.atbCtaNoItems,t),t.totalPriceText=t.nodes.$totalPrice.text(),t.atbCtaText=t.nodes.$atbCta.text(),t.atbCtaSingularText=t.nodes.$atbCtaSingular.text(),t.atbCtaNoItemsText=t.nodes.$atbCtaNoItems.text()},setEvents:function(t){var o=this;t.nodes.$productCheckbox.once().on("change",(function(){t.nodes.$selectedProducts=t.nodes.$productCheckbox.filter(":checked").closest(o.selectors.product),o.updateTotalPrice(t),o.updateSelectedProductsCount(t)})),t.nodes.$productImage.once().on("click",(function(t){var r=e(this).closest(o.selectors.product).find(o.selectors.productCheckbox);o.isDesktop||(t.preventDefault(),r.prop("checked",!r.prop("checked")).trigger("change"))})),t.nodes.$productSkuLabel.once().on("click",(function(e){e.preventDefault()})),t.nodes.$atbCta.once().on("click",(function(e){e.preventDefault(),o.addSelectedProductsToBag(t)})),t.nodes.$atbCtaSingular.once().on("click",(function(e){e.preventDefault(),o.addSelectedProductsToBag(t)})),t.nodes.$atbCtaNoItems.once().on("click",(function(e){e.preventDefault()})),e(window).on("resize",_.debounce((function(){o.updateIsDesktop(),o.isDesktop?(o.equalHeights(t.nodes.$productItemHeadline),o.equalHeights(t.nodes.$productItemContent),o.equalHeights(t.nodes.$productTitle),o.equalHeights(t.nodes.$productRating),o.initCarousel(t)):(t.nodes.$productTitle.height("auto"),t.nodes.$productRating.height("auto"),t.nodes.$productCarousel.filter(".slick-initialized").slick("destroy"))}),100))},init:function(t){var o=this;t.nodes.$product.each((function(){var r=e(this);o.updateProductInventoryStatus(r),o.initProductPrices(t,r),o.initProductSelectbox(t,r)})),o.initProductsRating(t),o.updateProductsCount(t),o.updateSelectedProductsCount(t),o.updateTotalPrice(t),o.initCarousel(t),o.isDesktop&&(o.equalHeights(t.nodes.$productItemHeadline),o.equalHeights(t.nodes.$productItemContent),o.equalHeights(t.nodes.$productTitle)),t.nodes.$atbCtaNoItems.addClass("elc-button--disabled"),t.addClass("elc-regimen-block-initialized")},initCarousel:function(t){var o=t.nodes.$product.length,r={rtl:site.direction.isRTL,infinite:!1,slidesToShow:4,slidesToScroll:4};this.isDesktop&&o>4&&t.nodes.$productCarousel.filter(":not(.slick-initialized)").each((function(){e(this).slick(r)}))},initProductPrices:function(e,t){var o=this,r=t.find(o.selectors.productPrice),a=t.find(o.selectors.productPrice2),s=t.find(o.selectors.productUnitPrice),d=r.attr("data-sku-price"),c=a.attr("data-sku-price2");r.text(o.getFormattedPrice(e,d)),a.text(c?o.getFormattedPrice(e,c):""),a.text()&&a.removeClass("hidden"),Drupal.settings&&!Drupal.settings.hide_product_price_per_unit&&s.text()&&s.removeClass("hidden")},initProductsRating:function(t){var o=this;new Promise(((o,r)=>{var a=Drupal.settings.power_reviews.snippet_url,s=Drupal.settings.power_reviews.api_key,d=Drupal.settings.power_reviews.merchant_id,c=Drupal.settings.power_reviews.locale,n=t.nodes.$product.toArray().map((t=>e(t).attr("data-prod-id"))).join(",").replaceAll("PROD","");a=a.replace("MERCHANT_ID",d).replace("PRODUCT_IDS",n).replace("API_KEY",s).replace("LOCALE_LANGUAGE",c),e.ajax(a).done((function(e){o(e)})).fail((function(e){r(e)}))})).then((r=>{t.nodes.$product.each((function(){var t=e(this),a=t.find(o.selectors.productRatingAverage),s=t.find(o.selectors.productRatingStars),d=t.find(o.selectors.productRatingTotal),c=t.attr("data-prod-id").replaceAll("PROD",""),n=r.results.filter((e=>parseInt(e.page_id)===parseInt(c)&&e.rollup)),i=0,u=0;n.length>0&&(i=n[0].rollup.average_rating||0,u=Math.round(i/5*100),s.css("width",`${u}%`),a.attr("data-rating-average",i),d.text(`(${n[0].rollup.review_count})`)),a.attr("data-rating-average")||(a.addClass("hidden"),d.addClass("hidden"))})),o.isDesktop&&o.equalHeights(t.nodes.$productRating)}))},initProductSelectbox:function(t,o){var r=this,a=o.find(r.selectors.productSizeDropdown),s=o.find(r.selectors.productShadeDropdown);a.selectbox({onOpen:function(){t.nodes.$productSizeDropdown.not(a).selectbox("close"),t.nodes.$productShadeDropdown.selectbox("close")},onChange:function(o){var a=e(this).find(`option[value='${o}']`);r.updateProductSku(t,a),r.updateTotalPrice(t)},loopOptions:!0,keepInViewport:!0,effect:"slide"}),s.selectbox({classSelector:`sbSelector ${r.productShadeDropdownSelectboxClasses.classSelector}`,onOpen:function(){var o=e("li a",s.next());o.find(r.selectors.productShadeDropdownColor).length<=0&&o.each((function(){var t=e(this),o=e("").addClass(r.productShadeDropdownSelectboxClasses.classColorSpan),a=s.find(`option[value='${t.attr("rel")}']`).attr("data-sku-color");t.prepend(o.css("background-color",a))})),t.nodes.$productSizeDropdown.selectbox("close"),t.nodes.$productShadeDropdown.not(s).selectbox("close")},onChange:function(o){var a=e(this).find(`option[value='${o}']`);r.updateProductShadeDropdownSelectorColor(s),r.updateProductSku(t,a),r.updateTotalPrice(t)},loopOptions:!0,keepInViewport:!0,effect:"slide"}),r.updateProductShadeDropdownSelectorColor(s)},updateProductInventoryStatus:function(e){var t=e.find(this.selectors.productCheckbox),o=e.find(this.selectors.productInventoryStatus),r=e.attr("data-inventory-status"),a=e.attr("data-is-orderable");switch(0===parseInt(a,10)?t.attr("disabled","disabled").prop("checked",!1).trigger("change"):t.attr("disabled")&&t.removeAttr("disabled").prop("checked",!0).trigger("change"),parseInt(r,10)){case 2:o.removeClass("hidden").text(site.translations.elc_product.item_is_temp_out_of_stock);break;case 3:o.removeClass("hidden").text(site.translations.elc_product.item_is_coming_soon_notify_me);break;case 7:o.removeClass("hidden").text(site.translations.elc_product.item_is_sold_out);break;default:o.addClass("hidden").text("")}},updateProductShadeDropdownSelectorColor:function(t){var o=t.next().find(this.selectors.productShadeDropdownSelector),r=t.find(":selected"),a=e("").addClass(this.productShadeDropdownSelectboxClasses.classColorSpan),s=r.attr("data-sku-color");o.prepend(a.css("background-color",s))},updateProductSku:function(e,t){var o=this,r=t.closest(o.selectors.product),a=r.find(o.selectors.productImage),s=r.find(o.selectors.productPrice),d=r.find(o.selectors.productPrice2),c=r.find(o.selectors.productUnitPrice),n=t.attr("data-sku-base-id"),i=t.attr("data-sku-inventory-status"),u=t.attr("data-sku-is-orderable"),l=t.attr("data-sku-image"),p=t.attr("data-sku-price"),g=t.attr("data-sku-price2"),h=t.attr("data-sku-formatted-price"),m=t.attr("data-sku-formatted-unit-price");r.attr("data-sku-base-id",n).attr("data-inventory-status",i).attr("data-is-orderable",u).attr("data-price",p).attr("data-price2",g).attr("data-formatted-price",h),a.attr("src",l),s.attr("data-sku-price",p).text(o.getFormattedPrice(e,p)),d.attr("data-sku-price2",g).text(g?o.getFormattedPrice(e,g):""),d.text()?d.removeClass("hidden"):d.addClass("hidden"),Drupal.settings&&!Drupal.settings.hide_product_price_per_unit&&(m?c.removeClass("hidden").text(m):c.addClass("hidden").text("")),o.updateProductInventoryStatus(r)},updateTotalPrice:function(t){var o,r=0;t.nodes.$selectedProducts.each((function(){r+=parseFloat(e(this).attr("data-price"))})),o=t.totalPriceText.replace("{total_price}",this.getFormattedPrice(t,r)),t.nodes.$totalPrice.text(o)},updateProductsCount:function(e){var t=e.nodes.$product.length;e.attr("data-products-count",t)},updateSelectedProductsCount:function(e){var t=e.nodes.$selectedProducts.length,o=e.atbCtaText.replace("{selected_count}",t),r=e.atbCtaSingularText.replace("{selected_count}",t),a=e.atbCtaNoItemsText.replace("{selected_count}",t);switch(t){case 0:e.nodes.$atbCtaNoItems.text(a),e.nodes.$atbCtaNoItems.parent().removeClass("hidden"),e.nodes.$atbCtaSingular.parent().addClass("hidden"),e.nodes.$atbCta.parent().addClass("hidden");break;case 1:e.nodes.$atbCtaSingular.text(r),e.nodes.$atbCtaNoItems.parent().addClass("hidden"),e.nodes.$atbCtaSingular.parent().removeClass("hidden"),e.nodes.$atbCta.parent().addClass("hidden");break;default:e.nodes.$atbCta.text(o),e.nodes.$atbCtaNoItems.parent().addClass("hidden"),e.nodes.$atbCta.parent().removeClass("hidden"),e.nodes.$atbCtaSingular.parent().addClass("hidden")}},equalHeights:function(t){var o;t.length<1||(t.height("auto"),(o=e(_.max(t,(function(t){return e(t).height()})))).length>0&&t.css("height",o.height()))},updateIsDesktop:function(){var e=Unison.fetch.all(),t=Unison.fetch.now();this.isDesktop=parseInt(t.width,10)>=parseInt(e["usn-medium-max"],10)},addSelectedProductsToBag:function(t){var o=[];if(t.nodes.$selectedProducts.each((function(){var t=e(this);o.push(t.attr("data-sku-base-id"))})),o.length>0){var r={skus:o,itemType:"cart",INCREMENT:1,CAT_BASE_ID:"",QTY:1};generic.checkout.cart.updateCart({params:r,onSuccess:function(t){var o=t.getMessages(),r="";if(o&&o.forEach((function(e){"offer_criteria_not_met"===e.key&&(r=r.concat(e.text+" "))})),r)e(document).trigger("addToCart.failure",[o]),generic.overlay.launch({content:r,includeBackground:!0,cssStyle:{width:"324px",padding:"25px"}});else{var a=t.getData();e(document).trigger("addToCart.success",[a])}},onFailure:function(t){var o=t.getMessages(),r=e("").html(''+o[0].text+"").html();e(document).trigger("addToCart.failure",[o]),generic.overlay.launch({content:r,includeBackground:!0,cssStyle:{width:"324px",padding:"25px"}})}})}},getFormattedPrice:function(e,t){var o=e.nodes.$product.first(),r=o.attr("data-formatted-price").replace(/^[USCA]+/,""),a=r.replace(/[^0-9,.]/gu,""),s=[",","."].includes(a?.substr(-3,1))?{minimumFractionDigits:2,maximumFractionDigits:2}:{},d=parseFloat(o.attr("data-price")).toLocaleString(Drupal.settings.price_locale,s),c=parseFloat(t).toLocaleString(Drupal.settings.price_locale,s);return r.replace(d,c)}}}(jQuery);
;
(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):global.videojs=factory()})(this,function(){var version="7.0.3";var commonjsGlobal=typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};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 empty={};var empty$1=Object.freeze({default:empty});var minDoc=empty$1&&empty||empty$1;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 log=void 0;var level="info";var history=[];var logByType=function logByType(type,args){var lvl=log.levels[level];var lvlRegExp=new RegExp("^("+lvl+")$");if(type!=="log"){args.unshift(type.toUpperCase()+":")}if(history){history.push([].concat(args))}args.unshift("VIDEOJS:");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)};log=function log(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}logByType("log",args)};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.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=Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}return logByType("error",args)};log.warn=function(){for(var _len3=arguments.length,args=Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3]}return logByType("warn",args)};log.debug=function(){for(var _len4=arguments.length,args=Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4]}return logByType("debug",args)};var log$1=log;function clean(s){return s.replace(/\n\r?\s*/g,"")}var tsml=function tsml(sa){var s="",i=0;for(;i2&&arguments[2]!==undefined?arguments[2]:0;return keys(object).reduce(function(accum,key){return fn(accum,object[key],key)},initial)}function assign(target){for(var _len=arguments.length,sources=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){sources[_key-1]=arguments[_key]}if(Object.assign){return Object.assign.apply(Object,[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==="undefined"?"undefined":_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 cs=window_1.getComputedStyle(el);return cs?cs[prop]:""}return""}var _templateObject=taggedTemplateLiteralLoose(["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 "," to ","."],["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 "," to ","."]);function isNonBlankString(str){return typeof str==="string"&&/\S/.test(str)}function throwIfWhitespace(str){if(/\s/.test(str)){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(){var tagName=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"div";var properties=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var attributes=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var content=arguments[3];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$1.warn(tsml(_templateObject,propName,val));el.setAttribute(propName,val)}else if(propName==="textContent"){textContent(el,val)}else{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){var box=void 0;if(el.getBoundingClientRect&&el.parentNode){box=el.getBoundingClientRect()}if(!box){return{left:0,top:0}}var docEl=document_1.documentElement;var body=document_1.body;var clientLeft=docEl.clientLeft||body.clientLeft||0;var scrollLeft=window_1.pageXOffset||body.scrollLeft;var left=box.left+scrollLeft-clientLeft;var clientTop=docEl.clientTop||body.clientTop||0;var scrollTop=window_1.pageYOffset||body.scrollTop;var top=box.top+scrollTop-clientTop;return{left:Math.round(left),top:Math.round(top)}}function getPointerPosition(el,event){var position={};var box=findPosition(el);var boxW=el.offsetWidth;var boxH=el.offsetHeight;var boxY=box.top;var boxX=box.left;var pageY=event.pageY;var pageX=event.pageX;if(event.changedTouches){pageX=event.changedTouches[0].pageX;pageY=event.changedTouches[0].pageY}position.y=Math.max(0,Math.min(1,(boxY-pageY+boxH)/boxH));position.x=Math.max(0,Math.min(1,(pageX-boxX)/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.button!==0||event.buttons!==1){return false}return true}var $=createQuerier("querySelector");var $$=createQuerier("querySelectorAll");var Dom=Object.freeze({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 _guid=1;function newGUID(){return _guid++}var elData={};var elIdAttr="vdata"+(new Date).getTime();function getData(el){var id=el[elIdAttr];if(!id){id=el[elIdAttr]=newGUID()}if(!elData[id]){elData[id]={}}return elData[id]}function hasData(el){var id=el[elIdAttr];if(!id){return false}return!!Object.getOwnPropertyNames(elData[id]).length}function removeData(el){var id=el[elIdAttr];if(!id){return}delete elData[id];try{delete el[elIdAttr]}catch(e){if(el.removeAttribute){el.removeAttribute(elIdAttr)}else{el[elIdAttr]=null}}}function _cleanUpEvents(elem,type){var data=getData(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){removeData(elem)}}function _handleMultipleEvents(fn,elem,types,callback){types.forEach(function(type){fn(elem,type,callback)})}function fixEvent(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}}return event}var _supportsPassive=false;(function(){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){}})();var passiveEvents=["touchstart","touchmove"];function on(elem,type,fn){if(Array.isArray(type)){return _handleMultipleEvents(on,elem,type,fn)}var data=getData(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-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(!hasData(elem)){return}var data=getData(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;n0){for(var i=0,e=mediaEls.length;i=wait){fn.apply(undefined,arguments);last=now}};return throttled};var debounce=function debounce(func,wait,immediate){var context=arguments.length>3&&arguments[3]!==undefined?arguments[3]:window_1;var timeout=void 0;return function(){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)}};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.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 isEvented=function isEvented(object){return object instanceof EventTarget||!!object.eventBusEl_&&["on","one","off","trigger"].every(function(k){return typeof object[k]==="function"})};var isValidEventType=function isValidEventType(type){return typeof type==="string"&&/\S/.test(type)||Array.isArray(type)&&!!type.length};var validateTarget=function validateTarget(target){if(!target.nodeName&&!isEvented(target)){throw new Error("Invalid target; must be a DOM node or evented object.")}};var validateEventType=function validateEventType(type){if(!isValidEventType(type)){throw new Error("Invalid event type; must be a non-empty string or array.")}};var validateListener=function validateListener(listener){if(typeof listener!=="function"){throw new Error("Invalid listener; must be a function.")}};var normalizeListenArgs=function normalizeListenArgs(self,args){var isTargetingSelf=args.length<3||args[0]===self||args[0]===self.eventBusEl_;var target=void 0;var type=void 0;var listener=void 0;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);validateEventType(type);validateListener(listener);listener=bind(self,listener);return{isTargetingSelf:isTargetingSelf,target:target,type:type,listener:listener}};var listen=function listen(target,method,type,listener){validateTarget(target);if(target.nodeName){Events[method](target,type,listener)}else{target[method](type,listener)}};var EventedMixin={on:function on$$1(){var _this=this;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}var _normalizeListenArgs=normalizeListenArgs(this,args),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$$1(){var _this2=this;for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}var _normalizeListenArgs2=normalizeListenArgs(this,args),isTargetingSelf=_normalizeListenArgs2.isTargetingSelf,target=_normalizeListenArgs2.target,type=_normalizeListenArgs2.type,listener=_normalizeListenArgs2.listener;if(isTargetingSelf){listen(target,"one",type,listener)}else{var wrapper=function wrapper(){for(var _len3=arguments.length,largs=Array(_len3),_key3=0;_key3<_len3;_key3++){largs[_key3]=arguments[_key3]}_this2.off(target,type,wrapper);listener.apply(null,largs)};wrapper.guid=listener.guid;listen(target,"one",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);validateEventType(type);validateListener(listener);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){return trigger(this.eventBusEl_,event,hash)}};function evented(target){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var 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);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=void 0;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}function toTitleCase(string){if(typeof string!=="string"){return string}return string.charAt(0).toUpperCase()+string.slice(1)}function titleCaseEquals(str1,str2){return toTitleCase(str1)===toTitleCase(str2)}function mergeOptions(){var result={};for(var _len=arguments.length,sources=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 Component=function(){function Component(player,options,ready){classCallCheck(this,Component);if(!player&&this.play){this.player_=player=this}else{this.player_=player}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})}stateful(this,this.constructor.defaultState);this.children_=[];this.childIndex_={};this.childNameIndex_={};if(options.initChildren!==false){this.initChildren()}this.ready(ready);if(options.reportTouchActivity!==false){this.enableTouchActivity()}}Component.prototype.dispose=function dispose(){this.trigger({type:"dispose",bubbles:false});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;if(this.el_){if(this.el_.parentNode){this.el_.parentNode.removeChild(this.el_)}removeData(this.el_);this.el_=null}this.player_=null};Component.prototype.player=function player(){return this.player_};Component.prototype.options=function options(obj){log$1.warn("this.options() has been deprecated and will be moved to the constructor in 6.0");if(!obj){return this.options_}this.options_=mergeOptions(this.options_,obj);return this.options_};Component.prototype.el=function el(){return this.el_};Component.prototype.createEl=function createEl$$1(tagName,properties,attributes){return createEl(tagName,properties,attributes)};Component.prototype.localize=function localize(string,tokens){var defaultValue=arguments.length>2&&arguments[2]!==undefined?arguments[2]: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};Component.prototype.contentEl=function contentEl(){return this.contentEl_||this.el_};Component.prototype.id=function id(){return this.id_};Component.prototype.name=function name(){return this.name_};Component.prototype.children=function children(){return this.children_};Component.prototype.getChildById=function getChildById(id){return this.childIndex_[id]};Component.prototype.getChild=function getChild(name){if(!name){return}name=toTitleCase(name);return this.childNameIndex_[name]};Component.prototype.addChild=function addChild(child){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var index=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this.children_.length;var component=void 0;var componentName=void 0;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}this.children_.splice(index,0,component);if(typeof component.id==="function"){this.childIndex_[component.id()]=component}componentName=componentName||component.name&&toTitleCase(component.name());if(componentName){this.childNameIndex_[componentName]=component}if(typeof component.el==="function"&&component.el()){var childNodes=this.contentEl().children;var refNode=childNodes[index]||null;this.contentEl().insertBefore(component.el(),refNode)}return component};Component.prototype.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}this.childIndex_[component.id()]=null;this.childNameIndex_[component.name()]=null;var compEl=component.el();if(compEl&&compEl.parentNode===this.contentEl()){this.contentEl().removeChild(component.el())}};Component.prototype.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=void 0;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=void 0;var opts=void 0;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)}};Component.prototype.buildCSSClass=function buildCSSClass(){return""};Component.prototype.ready=function ready(fn){var sync=arguments.length>1&&arguments[1]!==undefined?arguments[1]: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)}};Component.prototype.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)};Component.prototype.$=function $$$1(selector,context){return $(selector,context||this.contentEl())};Component.prototype.$$=function $$$$1(selector,context){return $$(selector,context||this.contentEl())};Component.prototype.hasClass=function hasClass$$1(classToCheck){return hasClass(this.el_,classToCheck)};Component.prototype.addClass=function addClass$$1(classToAdd){addClass(this.el_,classToAdd)};Component.prototype.removeClass=function removeClass$$1(classToRemove){removeClass(this.el_,classToRemove)};Component.prototype.toggleClass=function toggleClass$$1(classToToggle,predicate){toggleClass(this.el_,classToToggle,predicate)};Component.prototype.show=function show(){this.removeClass("vjs-hidden")};Component.prototype.hide=function hide(){this.addClass("vjs-hidden")};Component.prototype.lockShowing=function lockShowing(){this.addClass("vjs-lock-showing")};Component.prototype.unlockShowing=function unlockShowing(){this.removeClass("vjs-lock-showing")};Component.prototype.getAttribute=function getAttribute$$1(attribute){return getAttribute(this.el_,attribute)};Component.prototype.setAttribute=function setAttribute$$1(attribute,value){setAttribute(this.el_,attribute,value)};Component.prototype.removeAttribute=function removeAttribute$$1(attribute){removeAttribute(this.el_,attribute)};Component.prototype.width=function width(num,skipListeners){return this.dimension("width",num,skipListeners)};Component.prototype.height=function height(num,skipListeners){return this.dimension("height",num,skipListeners)};Component.prototype.dimensions=function dimensions(width,height){this.width(width,true);this.height(height)};Component.prototype.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)};Component.prototype.currentDimension=function currentDimension(widthOrHeight){var computedWidthOrHeight=0;if(widthOrHeight!=="width"&&widthOrHeight!=="height"){throw new Error("currentDimension only accepts width or height value")}if(typeof window_1.getComputedStyle==="function"){var computedStyle=window_1.getComputedStyle(this.el_);computedWidthOrHeight=computedStyle.getPropertyValue(widthOrHeight)||computedStyle[widthOrHeight]}computedWidthOrHeight=parseFloat(computedWidthOrHeight);if(computedWidthOrHeight===0){var rule="offset"+toTitleCase(widthOrHeight);computedWidthOrHeight=this.el_[rule]}return computedWidthOrHeight};Component.prototype.currentDimensions=function currentDimensions(){return{width:this.currentDimension("width"),height:this.currentDimension("height")}};Component.prototype.currentWidth=function currentWidth(){return this.currentDimension("width")};Component.prototype.currentHeight=function currentHeight(){return this.currentDimension("height")};Component.prototype.focus=function focus(){this.el_.focus()};Component.prototype.blur=function blur(){this.el_.blur()};Component.prototype.emitTapEvents=function emitTapEvents(){var touchStart=0;var firstTouch=null;var tapMovementThreshold=10;var touchTimeThreshold=200;var couldBeTap=void 0;this.on("touchstart",function(event){if(event.touches.length===1){firstTouch={pageX:event.touches[0].pageX,pageY:event.touches[0].pageY};touchStart=(new Date).getTime();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=(new Date).getTime()-touchStart;if(touchTime0&&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;return ComponentToRegister};Component.getComponent=function getComponent(name){if(!name){return}name=toTitleCase(name);if(Component.components_&&Component.components_[name]){return Component.components_[name]}};return Component}();Component.prototype.supportsRaf_=typeof window_1.requestAnimationFrame==="function"&&typeof window_1.cancelAnimationFrame==="function";Component.registerComponent("Component",Component);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_IPAD=/iPad/i.test(USER_AGENT);var IS_IPHONE=/iPhone/i.test(USER_AGENT)&&!IS_IPAD;var IS_IPOD=/iPod/i.test(USER_AGENT);var IS_IOS=IS_IPHONE||IS_IPAD||IS_IPOD;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=/Edge/i.test(USER_AGENT);var IS_CHROME=!IS_EDGE&&/Chrome/i.test(USER_AGENT);var CHROME_VERSION=function(){var match=USER_AGENT.match(/Chrome\/(\d+)/);if(match&&match[1]){return parseFloat(match[1])}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}return version}();var IS_SAFARI=/Safari/i.test(USER_AGENT)&&!IS_CHROME&&!IS_ANDROID&&!IS_EDGE;var IS_ANY_SAFARI=IS_SAFARI||IS_IOS;var TOUCH_ENABLED=isReal()&&("ontouchstart"in window_1||window_1.DocumentTouch&&window_1.document instanceof window_1.DocumentTouch);var browser=Object.freeze({IS_IPAD:IS_IPAD,IS_IPHONE:IS_IPHONE,IS_IPOD:IS_IPOD,IS_IOS:IS_IOS,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_ANY_SAFARI:IS_ANY_SAFARI,TOUCH_ENABLED:TOUCH_ENABLED});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=void 0;var end=void 0;if(!duration){return 0}if(!buffered||!buffered.length){buffered=createTimeRanges(0,0)}for(var i=0;iduration){end=duration}bufferedDuration+=end-start}return bufferedDuration/duration}var FullscreenApi={};var apiMap=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]];var specApi=apiMap[0];var browserApi=void 0;for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:[];classCallCheck(this,TrackList);var _this=possibleConstructorReturn(this,_EventTarget.call(this));_this.tracks_=[];Object.defineProperty(_this,"length",{get:function get$$1(){return this.tracks_.length}});for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:[];classCallCheck(this,AudioTrackList);for(var i=tracks.length-1;i>=0;i--){if(tracks[i].enabled){disableOthers(tracks,tracks[i]);break}}var _this=possibleConstructorReturn(this,_TrackList.call(this,tracks));_this.changing_=false;return _this}AudioTrackList.prototype.addTrack=function addTrack(track){var _this2=this;if(track.enabled){disableOthers(this,track)}_TrackList.prototype.addTrack.call(this,track);if(!track.addEventListener){return}track.addEventListener("enabledchange",function(){if(_this2.changing_){return}_this2.changing_=true;disableOthers(_this2,track);_this2.changing_=false;_this2.trigger("change")})};return AudioTrackList}(TrackList);var disableOthers$1=function disableOthers(list,track){for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:[];classCallCheck(this,VideoTrackList);for(var i=tracks.length-1;i>=0;i--){if(tracks[i].selected){disableOthers$1(tracks,tracks[i]);break}}var _this=possibleConstructorReturn(this,_TrackList.call(this,tracks));_this.changing_=false;Object.defineProperty(_this,"selectedIndex",{get:function get$$1(){for(var _i=0;_i0&&arguments[0]!==undefined?arguments[0]:[];classCallCheck(this,HtmlTrackElementList);this.trackElements_=[];Object.defineProperty(this,"length",{get:function get$$1(){return this.trackElements_.length}});for(var i=0,length=trackElements.length;i0&&arguments[0]!==undefined?arguments[0]:{};classCallCheck(this,Track);var _this=possibleConstructorReturn(this,_EventTarget.call(this));var trackProps={id:options.id||"vjs_track_"+newGUID(),kind:options.kind||"",label:options.label||"",language:options.language||""};var _loop=function _loop(key){Object.defineProperty(_this,key,{get:function get$$1(){return trackProps[key]},set:function set$$1(){}})};for(var key in trackProps){_loop(key)}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=void 0;if(addToBody){div=document_1.createElement("div");div.innerHTML='';a=div.firstChild;div.setAttribute("style","display:none; position:absolute;");document_1.body.appendChild(div)}var details={};for(var i=0;ix';url=div.firstChild.href}return url};var getFileExtension=function getFileExtension(path){if(typeof path==="string"){var splitPathRe=/^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i;var pathParts=splitPathRe.exec(path);if(pathParts){return pathParts.pop().toLowerCase()}}return""};var isCrossOrigin=function isCrossOrigin(url){var 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({parseUrl:parseUrl,getAbsoluteURL:getAbsoluteURL,getFileExtension:getFileExtension,isCrossOrigin:isCrossOrigin});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 isFunction$1=Object.freeze({default:isFunction_1,__moduleExports:isFunction_1});var trim_1=createCommonjsModule(function(module,exports){exports=module.exports=trim;function trim(str){return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){return str.replace(/^\s*/,"")};exports.right=function(str){return str.replace(/\s*$/,"")}});var trim_2=trim_1.left;var trim_3=trim_1.right;var trim=Object.freeze({default:trim_1,__moduleExports:trim_1,left:trim_2,right:trim_3});var isFunction$2=isFunction$1&&isFunction_1||isFunction$1;var forEach_1=forEach;var toString$2=Object.prototype.toString;var hasOwnProperty=Object.prototype.hasOwnProperty;function forEach(list,iterator,context){if(!isFunction$2(iterator)){throw new TypeError("iterator must be a function")}if(arguments.length<3){context=this}if(toString$2.call(list)==="[object Array]")forEachArray(list,iterator,context);else if(typeof list==="string")forEachString(list,iterator,context);else forEachObject(list,iterator,context)}function forEachArray(array,iterator,context){for(var i=0,len=array.length;i0){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){if(xhr.responseType==="document"){return xhr.responseXML}var firefoxBugTakenEffect=xhr.responseXML&&xhr.responseXML.documentElement.nodeName==="parsererror";if(xhr.responseType===""&&!firefoxBugTakenEffect){return xhr.responseXML}return null}function noop(){}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$1.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}xhr(opts,bind(this,function(err,response,responseBody){if(err){return log$1.error(err,response)}track.loaded_=true;if(typeof window_1.WebVTT!=="function"){if(track.tech_){var loadHandler=function loadHandler(){return parseCues(responseBody,track)};track.tech_.on("vttjsloaded",loadHandler);track.tech_.on("vttjserror",function(){log$1.error("vttjs failed to load, stopping trying to process "+track.src);track.tech_.off("vttjsloaded",loadHandler)})}}else{parseCues(responseBody,track)}}))};var TextTrack=function(_Track){inherits(TextTrack,_Track);function TextTrack(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};classCallCheck(this,TextTrack);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"}var _this=possibleConstructorReturn(this,_Track.call(this,settings));_this.tech_=settings.tech;_this.cues_=[];_this.activeCues_=[];var cues=new TextTrackCueList(_this.cues_);var activeCues=new TextTrackCueList(_this.activeCues_);var changed=false;var timeupdateHandler=bind(_this,function(){this.activeCues;if(changed){this.trigger("cuechange");changed=false}});if(mode!=="disabled"){_this.tech_.ready(function(){_this.tech_.on("timeupdate",timeupdateHandler)},true)}Object.defineProperties(_this,{default:{get:function get$$1(){return default_},set:function set$$1(){}},mode:{get:function get$$1(){return mode},set:function set$$1(newMode){var _this2=this;if(!TextTrackMode[newMode]){return}mode=newMode;if(mode==="showing"){this.tech_.ready(function(){_this2.tech_.on("timeupdate",timeupdateHandler)},true)}this.trigger("modechange")}},cues:{get:function get$$1(){if(!this.loaded_){return null}return cues},set:function set$$1(){}},activeCues:{get:function get$$1(){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=ct){active.push(cue)}else if(cue.startTime===cue.endTime&&cue.startTime<=ct&&cue.startTime+.5>=ct){active.push(cue)}}changed=false;if(active.length!==this.activeCues_.length){changed=true}else{for(var _i=0;_i0&&arguments[0]!==undefined?arguments[0]:{};classCallCheck(this,AudioTrack);var settings=mergeOptions(options,{kind:AudioTrackKind[options.kind]||""});var _this=possibleConstructorReturn(this,_Track.call(this,settings));var enabled=false;Object.defineProperty(_this,"enabled",{get:function get$$1(){return enabled},set:function set$$1(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){inherits(VideoTrack,_Track);function VideoTrack(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};classCallCheck(this,VideoTrack);var settings=mergeOptions(options,{kind:VideoTrackKind[options.kind]||""});var _this=possibleConstructorReturn(this,_Track.call(this,settings));var selected=false;Object.defineProperty(_this,"selected",{get:function get$$1(){return selected},set:function set$$1(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){inherits(HTMLTrackElement,_EventTarget);function HTMLTrackElement(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};classCallCheck(this,HTMLTrackElement);var _this=possibleConstructorReturn(this,_EventTarget.call(this));var readyState=void 0;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(_this,{readyState:{get:function get$$1(){return readyState}},track:{get:function get$$1(){return track}}});readyState=NONE;track.addEventListener("loadeddata",function(){readyState=LOADED;_this.trigger({type:"load",target:_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=mergeOptions(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)/1e3}var m=input.match(/^(\d+):(\d{2})(:\d{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=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","middle","end"])}break;case"position":vals=v.split(",");settings.percent(k,vals[0]);if(vals.length===2){settings.alt("positionAlign",vals[1],["start","middle","end"])}break;case"size":settings.percent(k,v);break;case"align":settings.alt(k,v,["start","middle","end","left","right"]);break}},/:/,/\s/);cue.region=settings.get("region",null);cue.vertical=settings.get("vertical","");cue.line=settings.get("line","auto");cue.lineAlign=settings.get("lineAlign","start");cue.snapToLines=settings.get("snapToLines",true);cue.size=settings.get("size",100);cue.align=settings.get("align","middle");cue.position=settings.get("position",{start:0,left:0,middle:50,end:100,right:100},cue.align);cue.positionAlign=settings.get("positionAlign",{start:"start",left:"start",middle:"middle",end:"end",right:"end"},cue.align)}function skipWhitespace(){input=input.replace(/^\s+/,"")}skipWhitespace();cue.startTime=consumeTimeStamp();skipWhitespace();if(input.substr(0,3)!=="--\x3e"){throw new ParsingError(ParsingError.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '--\x3e'): "+oInput)}input=input.substr(3);skipWhitespace();cue.endTime=consumeTimeStamp();skipWhitespace();consumeCueSettings(input,cue)}var ESCAPE={"&":"&","<":"<",">":">","":"","":""," ":" "};var TAG_NAME={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span"};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 unescape1(e){return ESCAPE[e]}function unescape(s){while(m=s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/)){s=s.replace(m[0],unescape1)}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);element.localName=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]){node.className=m[2].substr(1).replace("."," ")}tagStack.push(m[1]);current.appendChild(node);current=node;continue}current.appendChild(window.document.createTextNode(unescape(t)))}return rootDiv}var strongRTLRanges=[[1470,1470],[1472,1472],[1475,1475],[1478,1478],[1488,1514],[1520,1524],[1544,1544],[1547,1547],[1549,1549],[1563,1563],[1566,1610],[1645,1647],[1649,1749],[1765,1766],[1774,1775],[1786,1805],[1807,1808],[1810,1839],[1869,1957],[1969,1969],[1984,2026],[2036,2037],[2042,2042],[2048,2069],[2074,2074],[2084,2084],[2088,2088],[2096,2110],[2112,2136],[2142,2142],[2208,2208],[2210,2220],[8207,8207],[64285,64285],[64287,64296],[64298,64310],[64312,64316],[64318,64318],[64320,64321],[64323,64324],[64326,64449],[64467,64829],[64848,64911],[64914,64967],[65008,65020],[65136,65140],[65142,65276],[67584,67589],[67592,67592],[67594,67637],[67639,67640],[67644,67644],[67647,67669],[67671,67679],[67840,67867],[67872,67897],[67903,67903],[67968,68023],[68030,68031],[68096,68096],[68112,68115],[68117,68119],[68121,68147],[68160,68167],[68176,68184],[68192,68223],[68352,68405],[68416,68437],[68440,68466],[68472,68479],[68608,68680],[126464,126467],[126469,126495],[126497,126498],[126500,126500],[126503,126503],[126505,126514],[126516,126519],[126521,126521],[126523,126523],[126530,126530],[126535,126535],[126537,126537],[126539,126539],[126541,126543],[126545,126546],[126548,126548],[126551,126551],[126553,126553],[126555,126555],[126557,126557],[126559,126559],[126561,126562],[126564,126564],[126567,126570],[126572,126578],[126580,126583],[126585,126588],[126590,126590],[126592,126601],[126603,126619],[126625,126627],[126629,126633],[126635,126651],[1114109,1114109]];function isStrongRTLChar(charCode){for(var i=0;i=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=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;ib2.left&&this.topb2.top};BoxPosition.prototype.overlapsAny=function(boxes){for(var i=0;i=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.leftcontainer.right;case"+y":return this.topcontainer.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;ip){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"middle":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=.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;i100){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){throw new SyntaxError("An invalid or illegal string was specified.")}_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("An invalid or illegal 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 vttcue$1=Object.freeze({default:vttcue,__moduleExports: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){throw new SyntaxError("An invalid or illegal string was specified.")}_scroll=setting}}})}var vttregion=VTTRegion;var vttregion$1=Object.freeze({default:vttregion,__moduleExports:vttregion});var require$$0=vtt$1&&vtt||vtt$1;var require$$1=vttcue$1&&vttcue||vttcue$1;var require$$2=vttregion$1&&vttregion||vttregion$1;var browserIndex=createCommonjsModule(function(module){var vttjs=module.exports={WebVTT:require$$0,VTTCue:require$$1,VTTRegion:require$$2};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){var options=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{};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){inherits(Tech,_Component);function Tech(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var ready=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(){};classCallCheck(this,Tech);options.reportTouchActivity=false;var _this=possibleConstructorReturn(this,_Component.call(this,null,options,ready));_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.autoRemoteTextTracks_=new ALL.text.ListClass;_this.initTrackListeners();if(!options.nativeControlsForTouch){_this.emitTapEvents()}if(_this.constructor){_this.name_=_this.constructor.name||"Unknown Tech"}return _this}Tech.prototype.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"})};Tech.prototype.manualProgressOn=function manualProgressOn(){this.on("durationchange",this.onDurationChange);this.manualProgress=true;this.one("ready",this.trackProgress)};Tech.prototype.manualProgressOff=function manualProgressOff(){this.manualProgress=false;this.stopTrackingProgress();this.off("durationchange",this.onDurationChange)};Tech.prototype.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)};Tech.prototype.onDurationChange=function onDurationChange(event){this.duration_=this.duration()};Tech.prototype.buffered=function buffered(){return createTimeRanges(0,0)};Tech.prototype.bufferedPercent=function bufferedPercent$$1(){return bufferedPercent(this.buffered(),this.duration_)};Tech.prototype.stopTrackingProgress=function stopTrackingProgress(){this.clearInterval(this.progressInterval)};Tech.prototype.manualTimeUpdatesOn=function manualTimeUpdatesOn(){this.manualTimeUpdates=true;this.on("play",this.trackCurrentTime);this.on("pause",this.stopTrackingCurrentTime)};Tech.prototype.manualTimeUpdatesOff=function manualTimeUpdatesOff(){this.manualTimeUpdates=false;this.stopTrackingCurrentTime();this.off("play",this.trackCurrentTime);this.off("pause",this.stopTrackingCurrentTime)};Tech.prototype.trackCurrentTime=function trackCurrentTime(){if(this.currentTimeInterval){this.stopTrackingCurrentTime()}this.currentTimeInterval=this.setInterval(function(){this.trigger({type:"timeupdate",target:this,manuallyTriggered:true})},250)};Tech.prototype.stopTrackingCurrentTime=function stopTrackingCurrentTime(){this.clearInterval(this.currentTimeInterval);this.trigger({type:"timeupdate",target:this,manuallyTriggered:true})};Tech.prototype.dispose=function dispose(){this.clearTracks(NORMAL.names);if(this.manualProgress){this.manualProgressOff()}if(this.manualTimeUpdates){this.manualTimeUpdatesOff()}_Component.prototype.dispose.call(this)};Tech.prototype.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)}})};Tech.prototype.cleanupAutoTextTracks=function cleanupAutoTextTracks(){var list=this.autoRemoteTextTracks_||[];var i=list.length;while(i--){var track=list[i];this.removeRemoteTextTrack(track)}};Tech.prototype.reset=function reset(){};Tech.prototype.error=function error(err){if(err!==undefined){this.error_=new MediaError(err);this.trigger("error")}return this.error_};Tech.prototype.played=function played(){if(this.hasStarted_){return createTimeRanges(0,0)}return createTimeRanges()};Tech.prototype.setCurrentTime=function setCurrentTime(){if(this.manualTimeUpdates){this.trigger({type:"timeupdate",target:this,manuallyTriggered:true})}};Tech.prototype.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)})})};Tech.prototype.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_)}};Tech.prototype.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;i0&&arguments[0]!==undefined?arguments[0]:{};var manualCleanup=arguments[1];var htmlTrackElement=this.createRemoteTextTrack(options);if(manualCleanup!==true&&manualCleanup!==false){log$1.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};Tech.prototype.removeRemoteTextTrack=function removeRemoteTextTrack(track){var trackElement=this.remoteTextTrackEls().getTrackElementByTrack_(track);this.remoteTextTrackEls().removeTrackElement_(trackElement);this.remoteTextTracks().removeTrack(track);this.autoRemoteTextTracks_.removeTrack(track)};Tech.prototype.getVideoPlaybackQuality=function getVideoPlaybackQuality(){return{}};Tech.prototype.setPoster=function setPoster(){};Tech.prototype.playsinline=function playsinline(){};Tech.prototype.setPlaysinline=function setPlaysinline(){};Tech.prototype.overrideNativeAudioTracks=function overrideNativeAudioTracks(){};Tech.prototype.overrideNativeVideoTracks=function overrideNativeVideoTracks(){};Tech.prototype.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;if(name!=="Tech"){Tech.defaultTechOrder_.push(name)}return tech};Tech.getTech=function getTech(name){if(!name){return}name=toTitleCase(name);if(Tech.techs_&&Tech.techs_[name]){return Tech.techs_[name]}if(window_1&&window_1.videojs&&window_1.videojs[name]){log$1.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.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=void 0;for(var i=0;i3&&arguments[3]!==undefined?arguments[3]: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,seekable:1,played:1,paused:1};var allowedSetters={setCurrentTime: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;i0&&arguments[0]!==undefined?arguments[0]:{};var middleware=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];var next=arguments[2];var player=arguments[3];var acc=arguments.length>4&&arguments[4]!==undefined?arguments[4]:[];var lastRun=arguments.length>5&&arguments[5]!==undefined?arguments[5]:false;var 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);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",mp3:"audio/mpeg",aac:"audio/aac",oga:"audio/ogg",m3u8:"application/x-mpegURL"};var getMimetype=function getMimetype(){var src=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";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;i0&&arguments[0]!==undefined?arguments[0]:"div";var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var attributes=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};props=assign({innerHTML:'',className:this.buildCSSClass(),tabIndex:0},props);if(tag==="button"){log$1.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};ClickableComponent.prototype.dispose=function dispose(){this.controlTextEl_=null;_Component.prototype.dispose.call(this)};ClickableComponent.prototype.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_};ClickableComponent.prototype.controlText=function controlText(text){var el=arguments.length>1&&arguments[1]!==undefined?arguments[1]: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)}};ClickableComponent.prototype.buildCSSClass=function buildCSSClass(){return"vjs-control vjs-button "+_Component.prototype.buildCSSClass.call(this)};ClickableComponent.prototype.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("focus",this.handleFocus);this.on("blur",this.handleBlur)}};ClickableComponent.prototype.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(["tap","click"],this.handleClick);this.off("focus",this.handleFocus);this.off("blur",this.handleBlur)};ClickableComponent.prototype.handleClick=function handleClick(event){};ClickableComponent.prototype.handleFocus=function handleFocus(event){on(document_1,"keydown",bind(this,this.handleKeyPress))};ClickableComponent.prototype.handleKeyPress=function handleKeyPress(event){if(event.which===32||event.which===13){event.preventDefault();this.trigger("click")}else if(_Component.prototype.handleKeyPress){_Component.prototype.handleKeyPress.call(this,event)}};ClickableComponent.prototype.handleBlur=function handleBlur(event){off(document_1,"keydown",bind(this,this.handleKeyPress))};return ClickableComponent}(Component);Component.registerComponent("ClickableComponent",ClickableComponent);var PosterImage=function(_ClickableComponent){inherits(PosterImage,_ClickableComponent);function PosterImage(player,options){classCallCheck(this,PosterImage);var _this=possibleConstructorReturn(this,_ClickableComponent.call(this,player,options));_this.update();player.on("posterchange",bind(_this,_this.update));return _this}PosterImage.prototype.dispose=function dispose(){this.player().off("posterchange",this.update);_ClickableComponent.prototype.dispose.call(this)};PosterImage.prototype.createEl=function createEl$$1(){var el=createEl("div",{className:"vjs-poster",tabIndex:-1});return el};PosterImage.prototype.update=function update(event){var url=this.player().poster();this.setSrc(url);if(url){this.show()}else{this.hide()}};PosterImage.prototype.setSrc=function setSrc(url){var backgroundImage="";if(url){backgroundImage='url("'+url+'")'}this.el_.style.backgroundImage=backgroundImage};PosterImage.prototype.handleClick=function handleClick(event){if(!this.player_.controls()){return}if(this.player_.paused()){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){return"rgba("+parseInt(color[1]+color[1],16)+","+parseInt(color[2]+color[2],16)+","+parseInt(color[3]+color[3],16)+","+opacity+")"}function tryUpdateStyle(el,style,rule){try{el.style[style]=rule}catch(e){return}}var TextTrackDisplay=function(_Component){inherits(TextTrackDisplay,_Component);function TextTrackDisplay(player,options,ready){classCallCheck(this,TextTrackDisplay);var _this=possibleConstructorReturn(this,_Component.call(this,player,options,ready));player.on("loadstart",bind(_this,_this.toggleDisplay));player.on("texttrackchange",bind(_this,_this.updateDisplay));player.on("loadstart",bind(_this,_this.preselectTrack));player.ready(bind(_this,function(){if(player.tech_&&player.tech_.featuresNativeTextTracks){this.hide();return}player.on("fullscreenchange",bind(this,this.updateDisplay));var tracks=this.options_.playerOptions.tracks||[];for(var i=0;i1&&arguments[1]!==undefined?arguments[1]:{};var attributes=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};tag="button";props=assign({innerHTML:'',className:this.buildCSSClass()},props);attributes=assign({type:"button"},attributes);var el=Component.prototype.createEl.call(this,tag,props,attributes);this.createControlTextEl(el);return el};Button.prototype.addChild=function addChild(child){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var className=this.constructor.name;log$1.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)};Button.prototype.enable=function enable(){_ClickableComponent.prototype.enable.call(this);this.el_.removeAttribute("disabled")};Button.prototype.disable=function disable(){_ClickableComponent.prototype.disable.call(this);this.el_.setAttribute("disabled","disabled")};Button.prototype.handleKeyPress=function handleKeyPress(event){if(event.which===32||event.which===13){return}_ClickableComponent.prototype.handleKeyPress.call(this,event)};return Button}(ClickableComponent);Component.registerComponent("Button",Button);var BigPlayButton=function(_Button){inherits(BigPlayButton,_Button);function BigPlayButton(player,options){classCallCheck(this,BigPlayButton);var _this=possibleConstructorReturn(this,_Button.call(this,player,options));_this.mouseused_=false;_this.on("mousedown",_this.handleMouseDown);return _this}BigPlayButton.prototype.buildCSSClass=function buildCSSClass(){return"vjs-big-play-button"};BigPlayButton.prototype.handleClick=function handleClick(event){var playPromise=this.player_.play();if(this.mouseused_&&event.clientX&&event.clientY){return}var cb=this.player_.getChild("controlBar");var playToggle=cb&&cb.getChild("playToggle");if(!playToggle){this.player_.focus();return}var playFocus=function playFocus(){return playToggle.focus()};if(isPromise(playPromise)){playPromise.then(playFocus,function(){})}else{this.setTimeout(playFocus,1)}};BigPlayButton.prototype.handleKeyPress=function handleKeyPress(event){this.mouseused_=false;_Button.prototype.handleKeyPress.call(this,event)};BigPlayButton.prototype.handleMouseDown=function handleMouseDown(event){this.mouseused_=true};return BigPlayButton}(Button);BigPlayButton.prototype.controlText_="Play Video";Component.registerComponent("BigPlayButton",BigPlayButton);var CloseButton=function(_Button){inherits(CloseButton,_Button);function CloseButton(player,options){classCallCheck(this,CloseButton);var _this=possibleConstructorReturn(this,_Button.call(this,player,options));_this.controlText(options&&options.controlText||_this.localize("Close"));return _this}CloseButton.prototype.buildCSSClass=function buildCSSClass(){return"vjs-close-button "+_Button.prototype.buildCSSClass.call(this)};CloseButton.prototype.handleClick=function handleClick(event){this.trigger({type:"close",bubbles:false})};return CloseButton}(Button);Component.registerComponent("CloseButton",CloseButton);var PlayToggle=function(_Button){inherits(PlayToggle,_Button);function PlayToggle(player,options){classCallCheck(this,PlayToggle);var _this=possibleConstructorReturn(this,_Button.call(this,player,options));_this.on(player,"play",_this.handlePlay);_this.on(player,"pause",_this.handlePause);_this.on(player,"ended",_this.handleEnded);return _this}PlayToggle.prototype.buildCSSClass=function buildCSSClass(){return"vjs-play-control "+_Button.prototype.buildCSSClass.call(this)};PlayToggle.prototype.handleClick=function handleClick(event){if(this.player_.paused()){this.player_.play()}else{this.player_.pause()}};PlayToggle.prototype.handleSeeked=function handleSeeked(event){this.removeClass("vjs-ended");if(this.player_.paused()){this.handlePause(event)}else{this.handlePlay(event)}};PlayToggle.prototype.handlePlay=function handlePlay(event){this.removeClass("vjs-ended");this.removeClass("vjs-paused");this.addClass("vjs-playing");this.controlText("Pause")};PlayToggle.prototype.handlePause=function handlePause(event){this.removeClass("vjs-playing");this.addClass("vjs-paused");this.controlText("Play")};PlayToggle.prototype.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){var guide=arguments.length>1&&arguments[1]!==undefined?arguments[1]:seconds;return implementation(seconds,guide)}var TimeDisplay=function(_Component){inherits(TimeDisplay,_Component);function TimeDisplay(player,options){classCallCheck(this,TimeDisplay);var _this=possibleConstructorReturn(this,_Component.call(this,player,options));_this.throttledUpdateContent=throttle(bind(_this,_this.updateContent),25);_this.on(player,"timeupdate",_this.throttledUpdateContent);return _this}TimeDisplay.prototype.createEl=function createEl$$1(plainName){var className=this.buildCSSClass();var el=_Component.prototype.createEl.call(this,"div",{className:className+" vjs-time-control vjs-control",innerHTML:''+this.localize(this.labelText_)+" "});this.contentEl_=createEl("span",{className:className+"-display"},{"aria-live":"off"});this.updateTextNode_();el.appendChild(this.contentEl_);return el};TimeDisplay.prototype.dispose=function dispose(){this.contentEl_=null;this.textNode_=null;_Component.prototype.dispose.call(this)};TimeDisplay.prototype.updateTextNode_=function updateTextNode_(){if(!this.contentEl_){return}while(this.contentEl_.firstChild){this.contentEl_.removeChild(this.contentEl_.firstChild)}this.textNode_=document_1.createTextNode(this.formattedTime_||this.formatTime_(0));this.contentEl_.appendChild(this.textNode_)};TimeDisplay.prototype.formatTime_=function formatTime_(time){return formatTime(time)};TimeDisplay.prototype.updateFormattedTime_=function updateFormattedTime_(time){var formattedTime=this.formatTime_(time);if(formattedTime===this.formattedTime_){return}this.formattedTime_=formattedTime;this.requestAnimationFrame(this.updateTextNode_)};TimeDisplay.prototype.updateContent=function updateContent(event){};return TimeDisplay}(Component);TimeDisplay.prototype.labelText_="Time";TimeDisplay.prototype.controlText_="Time";Component.registerComponent("TimeDisplay",TimeDisplay);var CurrentTimeDisplay=function(_TimeDisplay){inherits(CurrentTimeDisplay,_TimeDisplay);function CurrentTimeDisplay(player,options){classCallCheck(this,CurrentTimeDisplay);var _this=possibleConstructorReturn(this,_TimeDisplay.call(this,player,options));_this.on(player,"ended",_this.handleEnded);return _this}CurrentTimeDisplay.prototype.buildCSSClass=function buildCSSClass(){return"vjs-current-time"};CurrentTimeDisplay.prototype.updateContent=function updateContent(event){var time=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();this.updateFormattedTime_(time)};CurrentTimeDisplay.prototype.handleEnded=function handleEnded(event){if(!this.player_.duration()){return}this.updateFormattedTime_(this.player_.duration())};return CurrentTimeDisplay}(TimeDisplay);CurrentTimeDisplay.prototype.labelText_="Current Time";CurrentTimeDisplay.prototype.controlText_="Current Time";Component.registerComponent("CurrentTimeDisplay",CurrentTimeDisplay);var DurationDisplay=function(_TimeDisplay){inherits(DurationDisplay,_TimeDisplay);function DurationDisplay(player,options){classCallCheck(this,DurationDisplay);var _this=possibleConstructorReturn(this,_TimeDisplay.call(this,player,options));_this.on(player,"durationchange",_this.updateContent);_this.on(player,"loadedmetadata",_this.throttledUpdateContent);return _this}DurationDisplay.prototype.buildCSSClass=function buildCSSClass(){return"vjs-duration"};DurationDisplay.prototype.updateContent=function updateContent(event){var duration=this.player_.duration();if(duration&&this.duration_!==duration){this.duration_=duration;this.updateFormattedTime_(duration)}};return DurationDisplay}(TimeDisplay);DurationDisplay.prototype.labelText_="Duration";DurationDisplay.prototype.controlText_="Duration";Component.registerComponent("DurationDisplay",DurationDisplay);var TimeDivider=function(_Component){inherits(TimeDivider,_Component);function TimeDivider(){classCallCheck(this,TimeDivider);return possibleConstructorReturn(this,_Component.apply(this,arguments))}TimeDivider.prototype.createEl=function createEl(){return _Component.prototype.createEl.call(this,"div",{className:"vjs-time-control vjs-time-divider",innerHTML:"
/
"})};return TimeDivider}(Component);Component.registerComponent("TimeDivider",TimeDivider);var RemainingTimeDisplay=function(_TimeDisplay){inherits(RemainingTimeDisplay,_TimeDisplay);function RemainingTimeDisplay(player,options){classCallCheck(this,RemainingTimeDisplay);var _this=possibleConstructorReturn(this,_TimeDisplay.call(this,player,options));_this.on(player,"durationchange",_this.throttledUpdateContent);_this.on(player,"ended",_this.handleEnded);return _this}RemainingTimeDisplay.prototype.buildCSSClass=function buildCSSClass(){return"vjs-remaining-time"};RemainingTimeDisplay.prototype.formatTime_=function formatTime_(time){return"-"+_TimeDisplay.prototype.formatTime_.call(this,time)};RemainingTimeDisplay.prototype.updateContent=function updateContent(event){if(!this.player_.duration()){return}if(this.player_.remainingTimeDisplay){this.updateFormattedTime_(this.player_.remainingTimeDisplay())}else{this.updateFormattedTime_(this.player_.remainingTime())}};RemainingTimeDisplay.prototype.handleEnded=function handleEnded(event){if(!this.player_.duration()){return}this.updateFormattedTime_(0)};return RemainingTimeDisplay}(TimeDisplay);RemainingTimeDisplay.prototype.labelText_="Remaining Time";RemainingTimeDisplay.prototype.controlText_="Remaining Time";Component.registerComponent("RemainingTimeDisplay",RemainingTimeDisplay);var LiveDisplay=function(_Component){inherits(LiveDisplay,_Component);function LiveDisplay(player,options){classCallCheck(this,LiveDisplay);var _this=possibleConstructorReturn(this,_Component.call(this,player,options));_this.updateShowing();_this.on(_this.player(),"durationchange",_this.updateShowing);return _this}LiveDisplay.prototype.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:''+this.localize("Stream Type")+" "+this.localize("LIVE")},{"aria-live":"off"});el.appendChild(this.contentEl_);return el};LiveDisplay.prototype.dispose=function dispose(){this.contentEl_=null;_Component.prototype.dispose.call(this)};LiveDisplay.prototype.updateShowing=function updateShowing(event){if(this.player().duration()===Infinity){this.show()}else{this.hide()}};return LiveDisplay}(Component);Component.registerComponent("LiveDisplay",LiveDisplay);var Slider=function(_Component){inherits(Slider,_Component);function Slider(player,options){classCallCheck(this,Slider);var _this=possibleConstructorReturn(this,_Component.call(this,player,options));_this.bar=_this.getChild(_this.options_.barName);_this.vertical(!!_this.options_.vertical);_this.enable();return _this}Slider.prototype.enabled=function enabled(){return this.enabled_};Slider.prototype.enable=function enable(){if(this.enabled()){return}this.on("mousedown",this.handleMouseDown);this.on("touchstart",this.handleMouseDown);this.on("focus",this.handleFocus);this.on("blur",this.handleBlur);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};Slider.prototype.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("focus",this.handleFocus);this.off("blur",this.handleBlur);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};Slider.prototype.createEl=function createEl$$1(type){var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var attributes=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};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)};Slider.prototype.handleMouseDown=function handleMouseDown(event){var doc=this.bar.el_.ownerDocument;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)};Slider.prototype.handleMouseMove=function handleMouseMove(event){};Slider.prototype.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()};Slider.prototype.update=function update(){if(!this.el_){return}var progress=this.getPercent();var bar=this.bar;if(!bar){return}if(typeof progress!=="number"||progress!==progress||progress<0||progress===Infinity){progress=0}var percentage=(progress*100).toFixed(2)+"%";var style=bar.el().style;if(this.vertical()){style.height=percentage}else{style.width=percentage}return progress};Slider.prototype.calculateDistance=function calculateDistance(event){var position=getPointerPosition(this.el_,event);if(this.vertical()){return position.y}return position.x};Slider.prototype.handleFocus=function handleFocus(){this.on(this.bar.el_.ownerDocument,"keydown",this.handleKeyPress)};Slider.prototype.handleKeyPress=function handleKeyPress(event){if(event.which===37||event.which===40){event.preventDefault();this.stepBack()}else if(event.which===38||event.which===39){event.preventDefault();this.stepForward()}};Slider.prototype.handleBlur=function handleBlur(){this.off(this.bar.el_.ownerDocument,"keydown",this.handleKeyPress)};Slider.prototype.handleClick=function handleClick(event){event.stopImmediatePropagation();event.preventDefault()};Slider.prototype.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 LoadProgressBar=function(_Component){inherits(LoadProgressBar,_Component);function LoadProgressBar(player,options){classCallCheck(this,LoadProgressBar);var _this=possibleConstructorReturn(this,_Component.call(this,player,options));_this.partEls_=[];_this.on(player,"progress",_this.update);return _this}LoadProgressBar.prototype.createEl=function createEl$$1(){return _Component.prototype.createEl.call(this,"div",{className:"vjs-load-progress",innerHTML:''+this.localize("Loaded")+": 0%"})};LoadProgressBar.prototype.dispose=function dispose(){this.partEls_=null;_Component.prototype.dispose.call(this)};LoadProgressBar.prototype.update=function update(event){var buffered=this.player_.buffered();var duration=this.player_.duration();var bufferedEnd=this.player_.bufferedEnd();var children=this.partEls_;var percentify=function percentify(time,end){var percent=time/end||0;return(percent>=1?1:percent)*100+"%"};this.el_.style.width=percentify(bufferedEnd,duration);for(var i=0;ibuffered.length;_i--){this.el_.removeChild(children[_i-1])}children.length=buffered.length};return LoadProgressBar}(Component);Component.registerComponent("LoadProgressBar",LoadProgressBar);var TimeTooltip=function(_Component){inherits(TimeTooltip,_Component);function TimeTooltip(){classCallCheck(this,TimeTooltip);return possibleConstructorReturn(this,_Component.apply(this,arguments))}TimeTooltip.prototype.createEl=function createEl$$1(){return _Component.prototype.createEl.call(this,"div",{className:"vjs-time-tooltip"})};TimeTooltip.prototype.update=function update(seekBarRect,seekBarPoint,content){var tooltipRect=getBoundingClientRect(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(spaceLeftOfPointtooltipRect.width){pullTooltipBy=tooltipRect.width}this.el_.style.right="-"+pullTooltipBy+"px";textContent(this.el_,content)};return TimeTooltip}(Component);Component.registerComponent("TimeTooltip",TimeTooltip);var PlayProgressBar=function(_Component){inherits(PlayProgressBar,_Component);function PlayProgressBar(){classCallCheck(this,PlayProgressBar);return possibleConstructorReturn(this,_Component.apply(this,arguments))}PlayProgressBar.prototype.createEl=function createEl(){return _Component.prototype.createEl.call(this,"div",{className:"vjs-play-progress vjs-slider-bar",innerHTML:''+this.localize("Progress")+": 0%"})};PlayProgressBar.prototype.update=function update(seekBarRect,seekBarPoint){var _this2=this;if(this.rafId_){this.cancelAnimationFrame(this.rafId_)}this.rafId_=this.requestAnimationFrame(function(){var time=_this2.player_.scrubbing()?_this2.player_.getCache().currentTime:_this2.player_.currentTime();var content=formatTime(time,_this2.player_.duration());var timeTooltip=_this2.getChild("timeTooltip");if(timeTooltip){timeTooltip.update(seekBarRect,seekBarPoint,content)}})};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){inherits(MouseTimeDisplay,_Component);function MouseTimeDisplay(player,options){classCallCheck(this,MouseTimeDisplay);var _this=possibleConstructorReturn(this,_Component.call(this,player,options));_this.update=throttle(bind(_this,_this.update),25);return _this}MouseTimeDisplay.prototype.createEl=function createEl(){return _Component.prototype.createEl.call(this,"div",{className:"vjs-mouse-display"})};MouseTimeDisplay.prototype.update=function update(seekBarRect,seekBarPoint){var _this2=this;if(this.rafId_){this.cancelAnimationFrame(this.rafId_)}this.rafId_=this.requestAnimationFrame(function(){var duration=_this2.player_.duration();var content=formatTime(seekBarPoint*duration,duration);_this2.el_.style.left=seekBarRect.width*seekBarPoint+"px";_this2.getChild("timeTooltip").update(seekBarRect,seekBarPoint,content)})};return MouseTimeDisplay}(Component);MouseTimeDisplay.prototype.options_={children:["timeTooltip"]};Component.registerComponent("MouseTimeDisplay",MouseTimeDisplay);var STEP_SECONDS=5;var UPDATE_REFRESH_INTERVAL=30;var SeekBar=function(_Slider){inherits(SeekBar,_Slider);function SeekBar(player,options){classCallCheck(this,SeekBar);var _this=possibleConstructorReturn(this,_Slider.call(this,player,options));_this.setEventHandlers_();return _this}SeekBar.prototype.setEventHandlers_=function setEventHandlers_(){var _this2=this;this.update=throttle(bind(this,this.update),UPDATE_REFRESH_INTERVAL);this.on(this.player_,"timeupdate",this.update);this.on(this.player_,"ended",this.handleEnded);this.updateInterval=null;this.on(this.player_,["playing"],function(){_this2.clearInterval(_this2.updateInterval);_this2.updateInterval=_this2.setInterval(function(){_this2.requestAnimationFrame(function(){_this2.update()})},UPDATE_REFRESH_INTERVAL)});this.on(this.player_,["ended","pause","waiting"],function(){_this2.clearInterval(_this2.updateInterval)});this.on(this.player_,["timeupdate","ended"],this.update)};SeekBar.prototype.createEl=function createEl$$1(){return _Slider.prototype.createEl.call(this,"div",{className:"vjs-progress-holder"},{"aria-label":this.localize("Progress Bar")})};SeekBar.prototype.update_=function update_(currentTime,percent){var duration=this.player_.duration();this.el_.setAttribute("aria-valuenow",(percent*100).toFixed(2));this.el_.setAttribute("aria-valuetext",this.localize("progress bar timing: currentTime={1} duration={2}",[formatTime(currentTime,duration),formatTime(duration,duration)],"{1} of {2}"));this.bar.update(getBoundingClientRect(this.el_),percent)};SeekBar.prototype.update=function update(event){var percent=_Slider.prototype.update.call(this);this.update_(this.getCurrentTime_(),percent);return percent};SeekBar.prototype.getCurrentTime_=function getCurrentTime_(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime()};SeekBar.prototype.handleEnded=function handleEnded(event){this.update_(this.player_.duration(),1)};SeekBar.prototype.getPercent=function getPercent(){var percent=this.getCurrentTime_()/this.player_.duration();return percent>=1?1:percent||0};SeekBar.prototype.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)};SeekBar.prototype.handleMouseMove=function handleMouseMove(event){if(!isSingleLeftClick(event)){return}var newTime=this.calculateDistance(event)*this.player_.duration();if(newTime===this.player_.duration()){newTime=newTime-.1}this.player_.currentTime(newTime)};SeekBar.prototype.enable=function enable(){_Slider.prototype.enable.call(this);var mouseTimeDisplay=this.getChild("mouseTimeDisplay");if(!mouseTimeDisplay){return}mouseTimeDisplay.show()};SeekBar.prototype.disable=function disable(){_Slider.prototype.disable.call(this);var mouseTimeDisplay=this.getChild("mouseTimeDisplay");if(!mouseTimeDisplay){return}mouseTimeDisplay.hide()};SeekBar.prototype.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())}};SeekBar.prototype.stepForward=function stepForward(){this.player_.currentTime(this.player_.currentTime()+STEP_SECONDS)};SeekBar.prototype.stepBack=function stepBack(){this.player_.currentTime(this.player_.currentTime()-STEP_SECONDS)};SeekBar.prototype.handleAction=function handleAction(event){if(this.player_.paused()){this.player_.play()}else{this.player_.pause()}};SeekBar.prototype.handleKeyPress=function handleKeyPress(event){if(event.which===32||event.which===13){event.preventDefault();this.handleAction(event)}else if(_Slider.prototype.handleKeyPress){_Slider.prototype.handleKeyPress.call(this,event)}};return SeekBar}(Slider);SeekBar.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar"};if(!IS_IOS&&!IS_ANDROID){SeekBar.prototype.options_.children.splice(1,0,"mouseTimeDisplay")}SeekBar.prototype.playerEvent="timeupdate";Component.registerComponent("SeekBar",SeekBar);var ProgressControl=function(_Component){inherits(ProgressControl,_Component);function ProgressControl(player,options){classCallCheck(this,ProgressControl);var _this=possibleConstructorReturn(this,_Component.call(this,player,options));_this.handleMouseMove=throttle(bind(_this,_this.handleMouseMove),25);_this.throttledHandleMouseSeek=throttle(bind(_this,_this.handleMouseSeek),25);_this.enable();return _this}ProgressControl.prototype.createEl=function createEl$$1(){return _Component.prototype.createEl.call(this,"div",{className:"vjs-progress-control vjs-control"})};ProgressControl.prototype.handleMouseMove=function handleMouseMove(event){var seekBar=this.getChild("seekBar");if(seekBar){var mouseTimeDisplay=seekBar.getChild("mouseTimeDisplay");var seekBarEl=seekBar.el();var seekBarRect=getBoundingClientRect(seekBarEl);var seekBarPoint=getPointerPosition(seekBarEl,event).x;if(seekBarPoint>1){seekBarPoint=1}else if(seekBarPoint<0){seekBarPoint=0}if(mouseTimeDisplay){mouseTimeDisplay.update(seekBarRect,seekBarPoint)}}};ProgressControl.prototype.handleMouseSeek=function handleMouseSeek(event){var seekBar=this.getChild("seekBar");if(seekBar){seekBar.handleMouseMove(event)}};ProgressControl.prototype.enabled=function enabled(){return this.enabled_};ProgressControl.prototype.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};ProgressControl.prototype.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};ProgressControl.prototype.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)};ProgressControl.prototype.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 FullscreenToggle=function(_Button){inherits(FullscreenToggle,_Button);function FullscreenToggle(player,options){classCallCheck(this,FullscreenToggle);var _this=possibleConstructorReturn(this,_Button.call(this,player,options));_this.on(player,"fullscreenchange",_this.handleFullscreenChange);return _this}FullscreenToggle.prototype.buildCSSClass=function buildCSSClass(){return"vjs-fullscreen-control "+_Button.prototype.buildCSSClass.call(this)};FullscreenToggle.prototype.handleFullscreenChange=function handleFullscreenChange(event){if(this.player_.isFullscreen()){this.controlText("Non-Fullscreen")}else{this.controlText("Fullscreen")}};FullscreenToggle.prototype.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){inherits(VolumeLevel,_Component);function VolumeLevel(){classCallCheck(this,VolumeLevel);return possibleConstructorReturn(this,_Component.apply(this,arguments))}VolumeLevel.prototype.createEl=function createEl(){return _Component.prototype.createEl.call(this,"div",{className:"vjs-volume-level",innerHTML:''})};return VolumeLevel}(Component);Component.registerComponent("VolumeLevel",VolumeLevel);var VolumeBar=function(_Slider){inherits(VolumeBar,_Slider);function VolumeBar(player,options){classCallCheck(this,VolumeBar);var _this=possibleConstructorReturn(this,_Slider.call(this,player,options));_this.on("slideractive",_this.updateLastVolume_);_this.on(player,"volumechange",_this.updateARIAAttributes);player.ready(function(){return _this.updateARIAAttributes()});return _this}VolumeBar.prototype.createEl=function createEl$$1(){return _Slider.prototype.createEl.call(this,"div",{className:"vjs-volume-bar vjs-slider-bar"},{"aria-label":this.localize("Volume Level"),"aria-live":"polite"})};VolumeBar.prototype.handleMouseDown=function handleMouseDown(event){if(!isSingleLeftClick(event)){return}_Slider.prototype.handleMouseDown.call(this,event)};VolumeBar.prototype.handleMouseMove=function handleMouseMove(event){if(!isSingleLeftClick(event)){return}this.checkMuted();this.player_.volume(this.calculateDistance(event))};VolumeBar.prototype.checkMuted=function checkMuted(){if(this.player_.muted()){this.player_.muted(false)}};VolumeBar.prototype.getPercent=function getPercent(){if(this.player_.muted()){return 0}return this.player_.volume()};VolumeBar.prototype.stepForward=function stepForward(){this.checkMuted();this.player_.volume(this.player_.volume()+.1)};VolumeBar.prototype.stepBack=function stepBack(){this.checkMuted();this.player_.volume(this.player_.volume()-.1)};VolumeBar.prototype.updateARIAAttributes=function updateARIAAttributes(event){var ariaValue=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute("aria-valuenow",ariaValue);this.el_.setAttribute("aria-valuetext",ariaValue+"%")};VolumeBar.prototype.volumeAsPercentage_=function volumeAsPercentage_(){return Math.round(this.player_.volume()*100)};VolumeBar.prototype.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){inherits(VolumeControl,_Component);function VolumeControl(player){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};classCallCheck(this,VolumeControl);options.vertical=options.vertical||false;if(typeof options.volumeBar==="undefined"||isPlain(options.volumeBar)){options.volumeBar=options.volumeBar||{};options.volumeBar.vertical=options.vertical}var _this=possibleConstructorReturn(this,_Component.call(this,player,options));checkVolumeSupport(_this,player);_this.throttledHandleMouseMove=throttle(bind(_this,_this.handleMouseMove),25);_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}VolumeControl.prototype.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})};VolumeControl.prototype.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)};VolumeControl.prototype.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)};VolumeControl.prototype.handleMouseMove=function handleMouseMove(event){this.volumeBar.handleMouseMove(event)};return VolumeControl}(Component);VolumeControl.prototype.options_={children:["volumeBar"]};Component.registerComponent("VolumeControl",VolumeControl);var MuteToggle=function(_Button){inherits(MuteToggle,_Button);function MuteToggle(player,options){classCallCheck(this,MuteToggle);var _this=possibleConstructorReturn(this,_Button.call(this,player,options));checkVolumeSupport(_this,player);_this.on(player,["loadstart","volumechange"],_this.update);return _this}MuteToggle.prototype.buildCSSClass=function buildCSSClass(){return"vjs-mute-control "+_Button.prototype.buildCSSClass.call(this)};MuteToggle.prototype.handleClick=function handleClick(event){var vol=this.player_.volume();var lastVolume=this.player_.lastVolume_();if(vol===0){var volumeToSet=lastVolume<.1?.1:lastVolume;this.player_.volume(volumeToSet);this.player_.muted(false)}else{this.player_.muted(this.player_.muted()?false:true)}};MuteToggle.prototype.update=function update(event){this.updateIcon_();this.updateControlText_()};MuteToggle.prototype.updateIcon_=function updateIcon_(){var vol=this.player_.volume();var level=3;if(vol===0||this.player_.muted()){level=0}else if(vol<.33){level=1}else if(vol<.67){level=2}for(var i=0;i<4;i++){removeClass(this.el_,"vjs-vol-"+i)}addClass(this.el_,"vjs-vol-"+level)};MuteToggle.prototype.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){inherits(VolumePanel,_Component);function VolumePanel(player){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};classCallCheck(this,VolumePanel);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}var _this=possibleConstructorReturn(this,_Component.call(this,player,options));checkVolumeSupport(_this,player);_this.on(_this.volumeControl,["slideractive"],_this.sliderActive_);_this.on(_this.volumeControl,["sliderinactive"],_this.sliderInactive_);return _this}VolumePanel.prototype.sliderActive_=function sliderActive_(){this.addClass("vjs-slider-active")};VolumePanel.prototype.sliderInactive_=function sliderInactive_(){this.removeClass("vjs-slider-active")};VolumePanel.prototype.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})};return VolumePanel}(Component);VolumePanel.prototype.options_={children:["muteToggle","volumeControl"]};Component.registerComponent("VolumePanel",VolumePanel);var Menu=function(_Component){inherits(Menu,_Component);function Menu(player,options){classCallCheck(this,Menu);var _this=possibleConstructorReturn(this,_Component.call(this,player,options));if(options){_this.menuButton_=options.menuButton}_this.focusedChild_=-1;_this.on("keydown",_this.handleKeyPress);return _this}Menu.prototype.addItem=function addItem(component){this.addChild(component);component.on("click",bind(this,function(event){if(this.menuButton_){this.menuButton_.unpressButton();if(component.name()!=="CaptionSettingsMenuItem"){this.menuButton_.focus()}}}))};Menu.prototype.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};Menu.prototype.dispose=function dispose(){this.contentEl_=null;_Component.prototype.dispose.call(this)};Menu.prototype.handleKeyPress=function handleKeyPress(event){if(event.which===37||event.which===40){event.preventDefault();this.stepForward()}else if(event.which===38||event.which===39){event.preventDefault();this.stepBack()}};Menu.prototype.stepForward=function stepForward(){var stepChild=0;if(this.focusedChild_!==undefined){stepChild=this.focusedChild_+1}this.focus(stepChild)};Menu.prototype.stepBack=function stepBack(){var stepChild=0;if(this.focusedChild_!==undefined){stepChild=this.focusedChild_-1}this.focus(stepChild)};Menu.prototype.focus=function focus(){var item=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var children=this.children().slice();var haveTitle=children.length&&children[0].className&&/vjs-menu-title/.test(children[0].className);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){inherits(MenuButton,_Component);function MenuButton(player){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};classCallCheck(this,MenuButton);var _this=possibleConstructorReturn(this,_Component.call(this,player,options));_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_,"focus",_this.handleFocus);_this.on(_this.menuButton_,"blur",_this.handleBlur);_this.on("keydown",_this.handleSubmenuKeyPress);return _this}MenuButton.prototype.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()}};MenuButton.prototype.createMenu=function createMenu(){var menu=new Menu(this.player_,{menuButton:this});this.hideThreshold_=0;if(this.options_.title){var title=createEl("li",{className:"vjs-menu-title",innerHTML:toTitleCase(this.options_.title),tabIndex:-1});this.hideThreshold_+=1;menu.children_.unshift(title);prependTo(title,menu.contentEl())}this.items=this.createItems();if(this.items){for(var i=0;i1&&arguments[1]!==undefined?arguments[1]:this.menuButton_.el();return this.menuButton_.controlText(text,el)};MenuButton.prototype.handleClick=function handleClick(event){this.one(this.menu.contentEl(),"mouseleave",bind(this,function(e){this.unpressButton();this.el_.blur()}));if(this.buttonPressed_){this.unpressButton()}else{this.pressButton()}};MenuButton.prototype.focus=function focus(){this.menuButton_.focus()};MenuButton.prototype.blur=function blur(){this.menuButton_.blur()};MenuButton.prototype.handleFocus=function handleFocus(){on(document_1,"keydown",bind(this,this.handleKeyPress))};MenuButton.prototype.handleBlur=function handleBlur(){off(document_1,"keydown",bind(this,this.handleKeyPress))};MenuButton.prototype.handleKeyPress=function handleKeyPress(event){if(event.which===27||event.which===9){if(this.buttonPressed_){this.unpressButton()}if(event.which!==9){event.preventDefault();this.menuButton_.el_.focus()}}else if(event.which===38||event.which===40){if(!this.buttonPressed_){this.pressButton();event.preventDefault()}}};MenuButton.prototype.handleSubmenuKeyPress=function handleSubmenuKeyPress(event){if(event.which===27||event.which===9){if(this.buttonPressed_){this.unpressButton()}if(event.which!==9){event.preventDefault();this.menuButton_.el_.focus()}}};MenuButton.prototype.pressButton=function pressButton(){if(this.enabled_){this.buttonPressed_=true;this.menu.lockShowing();this.menuButton_.el_.setAttribute("aria-expanded","true");if(IS_IOS&&isInFrame()){return}this.menu.focus()}};MenuButton.prototype.unpressButton=function unpressButton(){if(this.enabled_){this.buttonPressed_=false;this.menu.unlockShowing();this.menuButton_.el_.setAttribute("aria-expanded","false")}};MenuButton.prototype.disable=function disable(){this.unpressButton();this.enabled_=false;this.addClass("vjs-disabled");this.menuButton_.disable()};MenuButton.prototype.enable=function enable(){this.enabled_=true;this.removeClass("vjs-disabled");this.menuButton_.enable()};return MenuButton}(Component);Component.registerComponent("MenuButton",MenuButton);var TrackButton=function(_MenuButton){inherits(TrackButton,_MenuButton);function TrackButton(player,options){classCallCheck(this,TrackButton);var tracks=options.tracks;var _this=possibleConstructorReturn(this,_MenuButton.call(this,player,options));if(_this.items.length<=1){_this.hide()}if(!tracks){return possibleConstructorReturn(_this)}var updateHandler=bind(_this,_this.update);tracks.addEventListener("removetrack",updateHandler);tracks.addEventListener("addtrack",updateHandler);_this.player_.on("ready",updateHandler);_this.player_.on("dispose",function(){tracks.removeEventListener("removetrack",updateHandler);tracks.removeEventListener("addtrack",updateHandler)});return _this}return TrackButton}(MenuButton);Component.registerComponent("TrackButton",TrackButton);var MenuItem=function(_ClickableComponent){inherits(MenuItem,_ClickableComponent);function MenuItem(player,options){classCallCheck(this,MenuItem);var _this=possibleConstructorReturn(this,_ClickableComponent.call(this,player,options));_this.selectable=options.selectable;_this.isSelected_=options.selected||false;_this.selected(_this.isSelected_);if(_this.selectable){_this.el_.setAttribute("role","menuitemcheckbox")}else{_this.el_.setAttribute("role","menuitem")}return _this}MenuItem.prototype.createEl=function createEl(type,props,attrs){this.nonIconControl=true;return _ClickableComponent.prototype.createEl.call(this,"li",assign({className:"vjs-menu-item",innerHTML:''+this.localize(this.options_.label)+"",tabIndex:-1},props),attrs)};MenuItem.prototype.handleClick=function handleClick(event){this.selected(true)};MenuItem.prototype.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){inherits(TextTrackMenuItem,_MenuItem);function TextTrackMenuItem(player,options){classCallCheck(this,TextTrackMenuItem);var track=options.track;var tracks=player.textTracks();options.label=track.label||track.language||"Unknown";options.selected=track.mode==="showing";var _this=possibleConstructorReturn(this,_MenuItem.call(this,player,options));_this.track=track;var changeHandler=function changeHandler(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this.handleTracksChange.apply(_this,args)};var selectedLanguageChangeHandler=function selectedLanguageChangeHandler(){for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}_this.handleSelectedLanguageChange.apply(_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=void 0;_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}TextTrackMenuItem.prototype.handleClick=function handleClick(event){var kind=this.track.kind;var kinds=this.track.kinds;var tracks=this.player_.textTracks();if(!kinds){kinds=[kind]}_MenuItem.prototype.handleClick.call(this,event);if(!tracks){return}for(var i=0;i-1){if(track.mode!=="showing"){track.mode="showing"}}else if(track.mode!=="disabled"){track.mode="disabled"}}};TextTrackMenuItem.prototype.handleTracksChange=function handleTracksChange(event){var shouldBeSelected=this.track.mode==="showing";if(shouldBeSelected!==this.isSelected_){this.selected(shouldBeSelected)}};TextTrackMenuItem.prototype.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}}};TextTrackMenuItem.prototype.dispose=function dispose(){this.track=null;_MenuItem.prototype.dispose.call(this)};return TextTrackMenuItem}(MenuItem);Component.registerComponent("TextTrackMenuItem",TextTrackMenuItem);var OffTextTrackMenuItem=function(_TextTrackMenuItem){inherits(OffTextTrackMenuItem,_TextTrackMenuItem);function OffTextTrackMenuItem(player,options){classCallCheck(this,OffTextTrackMenuItem);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;return possibleConstructorReturn(this,_TextTrackMenuItem.call(this,player,options))}OffTextTrackMenuItem.prototype.handleTracksChange=function handleTracksChange(event){var tracks=this.player().textTracks();var shouldBeSelected=true;for(var i=0,l=tracks.length;i-1&&track.mode==="showing"){shouldBeSelected=false;break}}if(shouldBeSelected!==this.isSelected_){this.selected(shouldBeSelected)}};OffTextTrackMenuItem.prototype.handleSelectedLanguageChange=function handleSelectedLanguageChange(event){var tracks=this.player().textTracks();var allHidden=true;for(var i=0,l=tracks.length;i-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){inherits(TextTrackButton,_TrackButton);function TextTrackButton(player){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};classCallCheck(this,TextTrackButton);options.tracks=player.textTracks();return possibleConstructorReturn(this,_TrackButton.call(this,player,options))}TextTrackButton.prototype.createItems=function createItems(){var items=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var TrackMenuItem=arguments.length>1&&arguments[1]!==undefined?arguments[1]:TextTrackMenuItem;var label=void 0;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-1){var item=new TrackMenuItem(this.player_,{track:track,selectable:true});item.addClass("vjs-"+track.kind+"-menu-item");items.push(item)}}return items};return TextTrackButton}(TrackButton);Component.registerComponent("TextTrackButton",TextTrackButton);var ChaptersTrackMenuItem=function(_MenuItem){inherits(ChaptersTrackMenuItem,_MenuItem);function ChaptersTrackMenuItem(player,options){classCallCheck(this,ChaptersTrackMenuItem);var track=options.track;var cue=options.cue;var currentTime=player.currentTime();options.selectable=true;options.label=cue.text;options.selected=cue.startTime<=currentTime&¤tTime=0;i--){var track=tracks[i];if(track.kind===this.kind_){return track}}};ChaptersButton.prototype.getMenuCaption=function getMenuCaption(){if(this.track_&&this.track_.label){return this.track_.label}return this.localize(toTitleCase(this.kind_))};ChaptersButton.prototype.createMenu=function createMenu(){this.options_.title=this.getMenuCaption();return _TextTrackButton.prototype.createMenu.call(this)};ChaptersButton.prototype.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\n '+this.localize("Captions")+"\n "}innerHTML+="";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){inherits(SubsCapsButton,_TextTrackButton);function SubsCapsButton(player){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};classCallCheck(this,SubsCapsButton);var _this=possibleConstructorReturn(this,_TextTrackButton.call(this,player,options));_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}SubsCapsButton.prototype.buildCSSClass=function buildCSSClass(){return"vjs-subs-caps-button "+_TextTrackButton.prototype.buildCSSClass.call(this)};SubsCapsButton.prototype.buildWrapperCSSClass=function buildWrapperCSSClass(){return"vjs-subs-caps-button "+_TextTrackButton.prototype.buildWrapperCSSClass.call(this)};SubsCapsButton.prototype.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){inherits(AudioTrackMenuItem,_MenuItem);function AudioTrackMenuItem(player,options){classCallCheck(this,AudioTrackMenuItem);var track=options.track;var tracks=player.audioTracks();options.label=track.label||track.language||"Unknown";options.selected=track.enabled;var _this=possibleConstructorReturn(this,_MenuItem.call(this,player,options));_this.track=track;var changeHandler=function changeHandler(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this.handleTracksChange.apply(_this,args)};tracks.addEventListener("change",changeHandler);_this.on("dispose",function(){tracks.removeEventListener("change",changeHandler)});return _this}AudioTrackMenuItem.prototype.handleClick=function handleClick(event){var tracks=this.player_.audioTracks();_MenuItem.prototype.handleClick.call(this,event);for(var i=0;i1&&arguments[1]!==undefined?arguments[1]:{};classCallCheck(this,AudioTrackButton);options.tracks=player.audioTracks();return possibleConstructorReturn(this,_TrackButton.call(this,player,options))}AudioTrackButton.prototype.buildCSSClass=function buildCSSClass(){return"vjs-audio-button "+_TrackButton.prototype.buildCSSClass.call(this)};AudioTrackButton.prototype.buildWrapperCSSClass=function buildWrapperCSSClass(){return"vjs-audio-button "+_TrackButton.prototype.buildWrapperCSSClass.call(this)};AudioTrackButton.prototype.createItems=function createItems(){var items=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];this.hideThreshold_=1;var tracks=this.player_.audioTracks();for(var i=0;i=0;i--){menu.addChild(new PlaybackRateMenuItem(this.player(),{rate:rates[i]+"x"}))}}return menu};PlaybackRateMenuButton.prototype.updateARIAAttributes=function updateARIAAttributes(){this.el().setAttribute("aria-valuenow",this.player().playbackRate())};PlaybackRateMenuButton.prototype.handleClick=function handleClick(event){var currentRate=this.player().playbackRate();var rates=this.playbackRates();var newRate=rates[0];for(var i=0;icurrentRate){newRate=rates[i];break}}this.player().playbackRate(newRate)};PlaybackRateMenuButton.prototype.playbackRates=function playbackRates(){return this.options_.playbackRates||this.options_.playerOptions&&this.options_.playerOptions.playbackRates};PlaybackRateMenuButton.prototype.playbackRateSupported=function playbackRateSupported(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0};PlaybackRateMenuButton.prototype.updateVisibility=function updateVisibility(event){if(this.playbackRateSupported()){this.removeClass("vjs-hidden")}else{this.addClass("vjs-hidden")}};PlaybackRateMenuButton.prototype.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){inherits(Spacer,_Component);function Spacer(){classCallCheck(this,Spacer);return possibleConstructorReturn(this,_Component.apply(this,arguments))}Spacer.prototype.buildCSSClass=function buildCSSClass(){return"vjs-spacer "+_Component.prototype.buildCSSClass.call(this)};Spacer.prototype.createEl=function createEl(){return _Component.prototype.createEl.call(this,"div",{className:this.buildCSSClass()})};return Spacer}(Component);Component.registerComponent("Spacer",Spacer);var CustomControlSpacer=function(_Spacer){inherits(CustomControlSpacer,_Spacer);function CustomControlSpacer(){classCallCheck(this,CustomControlSpacer);return possibleConstructorReturn(this,_Spacer.apply(this,arguments))}CustomControlSpacer.prototype.buildCSSClass=function buildCSSClass(){return"vjs-custom-control-spacer "+_Spacer.prototype.buildCSSClass.call(this)};CustomControlSpacer.prototype.createEl=function createEl(){var el=_Spacer.prototype.createEl.call(this,{className:this.buildCSSClass()});el.innerHTML=" ";return el};return CustomControlSpacer}(Spacer);Component.registerComponent("CustomControlSpacer",CustomControlSpacer);var ControlBar=function(_Component){inherits(ControlBar,_Component);function ControlBar(){classCallCheck(this,ControlBar);return possibleConstructorReturn(this,_Component.apply(this,arguments))}ControlBar.prototype.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","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","fullscreenToggle"]};Component.registerComponent("ControlBar",ControlBar);var ErrorDisplay=function(_ModalDialog){inherits(ErrorDisplay,_ModalDialog);function ErrorDisplay(player,options){classCallCheck(this,ErrorDisplay);var _this=possibleConstructorReturn(this,_ModalDialog.call(this,player,options));_this.on(player,"error",_this.open);return _this}ErrorDisplay.prototype.buildCSSClass=function buildCSSClass(){return"vjs-error-display "+_ModalDialog.prototype.buildCSSClass.call(this)};ErrorDisplay.prototype.content=function content(){var error=this.player().error();return error?this.localize(error.message):""};return ErrorDisplay}(ModalDialog);ErrorDisplay.prototype.options_=mergeOptions(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;i1&&arguments[1]!==undefined?arguments[1]:"";var type=arguments.length>2&&arguments[2]!==undefined?arguments[2]:"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+">",'").join("")};TextTrackSettings.prototype.createElFgColor_=function createElFgColor_(){var legendId="captions-text-legend-"+this.id_;return['"].join("")};TextTrackSettings.prototype.createElBgColor_=function createElBgColor_(){var legendId="captions-background-"+this.id_;return['"].join("")};TextTrackSettings.prototype.createElWinColor_=function createElWinColor_(){var legendId="captions-window-"+this.id_;return['"].join("")};TextTrackSettings.prototype.createElColors_=function createElColors_(){return createEl("div",{className:"vjs-track-settings-colors",innerHTML:[this.createElFgColor_(),this.createElBgColor_(),this.createElWinColor_()].join("")})};TextTrackSettings.prototype.createElFont_=function createElFont_(){return createEl("div",{className:"vjs-track-settings-font",innerHTML:['",'",'"].join("")})};TextTrackSettings.prototype.createElControls_=function createElControls_(){var defaultsDescription=this.localize("restore all settings to the default values");return createEl("div",{className:"vjs-track-settings-controls",innerHTML:['",'"].join("")})};TextTrackSettings.prototype.content=function content(){return[this.createElColors_(),this.createElFont_(),this.createElControls_()]};TextTrackSettings.prototype.label=function label(){return this.localize("Caption Settings Dialog")};TextTrackSettings.prototype.description=function description(){return this.localize("Beginning of dialog window. Escape will cancel and close the window.")};TextTrackSettings.prototype.buildCSSClass=function buildCSSClass(){return _ModalDialog.prototype.buildCSSClass.call(this)+" vjs-text-track-settings"};TextTrackSettings.prototype.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},{})};TextTrackSettings.prototype.setValues=function setValues(values){var _this4=this;each(selectConfigs,function(config,key){setSelectedOption(_this4.$(config.selector),values[key],config.parser)})};TextTrackSettings.prototype.setDefaults=function setDefaults(){var _this5=this;each(selectConfigs,function(config){var index=config.hasOwnProperty("default")?config.default:0;_this5.$(config.selector).selectedIndex=index})};TextTrackSettings.prototype.restoreSettings=function restoreSettings(){var values=void 0;try{values=JSON.parse(window_1.localStorage.getItem(LOCAL_STORAGE_KEY))}catch(err){log$1.warn(err)}if(values){this.setValues(values)}};TextTrackSettings.prototype.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$1.warn(err)}};TextTrackSettings.prototype.updateDisplay=function updateDisplay(){var ttDisplay=this.player_.getChild("textTrackDisplay");if(ttDisplay){ttDisplay.updateDisplay()}};TextTrackSettings.prototype.conditionalBlur_=function conditionalBlur_(){this.previouslyActiveEl_=null;this.off(document_1,"keydown",this.handleKeyDown);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){inherits(ResizeManager,_Component);function ResizeManager(player,options){classCallCheck(this,ResizeManager);var RESIZE_OBSERVER_AVAILABLE=options.ResizeObserver||window_1.ResizeObserver;if(options.ResizeObserver===null){RESIZE_OBSERVER_AVAILABLE=false}var options_=mergeOptions({createEl:!RESIZE_OBSERVER_AVAILABLE},options);var _this=possibleConstructorReturn(this,_Component.call(this,player,options_));_this.ResizeObserver=options.ResizeObserver||window_1.ResizeObserver;_this.loadListener_=null;_this.resizeObserver_=null;_this.debouncedHandler_=debounce(function(){_this.resizeHandler()},100,false,player);if(RESIZE_OBSERVER_AVAILABLE){_this.resizeObserver_=new _this.ResizeObserver(_this.debouncedHandler_);_this.resizeObserver_.observe(player.el())}else{_this.loadListener_=function(){if(_this.el_.contentWindow){on(_this.el_.contentWindow,"resize",_this.debouncedHandler_)}_this.off("load",_this.loadListener_)};_this.on("load",_this.loadListener_)}return _this}ResizeManager.prototype.createEl=function createEl(){return _Component.prototype.createEl.call(this,"iframe",{className:"vjs-resize-manager"})};ResizeManager.prototype.resizeHandler=function resizeHandler(){this.player_.trigger("playerresize")};ResizeManager.prototype.dispose=function dispose(){if(this.resizeObserver_){if(this.player_.el()){this.resizeObserver_.unobserve(this.player_.el())}this.resizeObserver_.disconnect()}if(this.el_&&this.el_.contentWindow){off(this.el_.contentWindow,"resize",this.debouncedHandler_)}if(this.loadListener_){this.off("load",this.loadListener_)}this.ResizeObserver=null;this.resizeObserver=null;this.debouncedHandler_=null;this.loadListener_=null};return ResizeManager}(Component);Component.registerComponent("ResizeManager",ResizeManager);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=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)})};Html5.prototype.setCurrentTime=function setCurrentTime(seconds){try{this.el_.currentTime=seconds}catch(e){log$1(e,"Video is not ready. (Video.js)")}};Html5.prototype.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};Html5.prototype.width=function width(){return this.el_.offsetWidth};Html5.prototype.height=function height(){return this.el_.offsetHeight};Html5.prototype.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})}};this.on("webkitbeginfullscreen",beginFn);this.on("dispose",function(){_this6.off("webkitbeginfullscreen",beginFn);_this6.off("webkitendfullscreen",endFn)})};Html5.prototype.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};Html5.prototype.enterFullScreen=function enterFullScreen(){var video=this.el_;if(video.paused&&video.networkState<=video.HAVE_METADATA){this.el_.play();this.setTimeout(function(){video.pause();video.webkitEnterFullScreen()},0)}else{video.webkitEnterFullScreen()}};Html5.prototype.exitFullScreen=function exitFullScreen(){this.el_.webkitExitFullScreen()};Html5.prototype.src=function src(_src){if(_src===undefined){return this.el_.src}this.setSrc(_src)};Html5.prototype.reset=function reset(){Html5.resetMediaElement(this.el_)};Html5.prototype.currentSrc=function currentSrc(){if(this.currentSource_){return this.currentSource_.src}return this.el_.currentSrc};Html5.prototype.setControls=function setControls(val){this.el_.controls=!!val};Html5.prototype.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)};Html5.prototype.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};Html5.prototype.addRemoteTextTrack=function addRemoteTextTrack(options,manualCleanup){var htmlTrackElement=_Tech.prototype.addRemoteTextTrack.call(this,options,manualCleanup);if(this.featuresNativeTextTracks){this.el().appendChild(htmlTrackElement)}return htmlTrackElement};Html5.prototype.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])}}}};Html5.prototype.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);if(isReal()){Html5.TEST_VID=document_1.createElement("video");var track=document_1.createElement("track");track.kind="captions";track.srclang="en";track.label="English";Html5.TEST_VID.appendChild(track)}Html5.isSupported=function(){try{Html5.TEST_VID.volume=.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+.1;return volume!==Html5.TEST_VID.volume}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+.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};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"];Html5.prototype.featuresVolumeControl=Html5.canControlVolume();Html5.prototype.featuresPlaybackRate=Html5.canControlPlaybackRate();Html5.prototype.featuresSourceset=Html5.canOverrideAttributes();Html5.prototype.movingMediaElementInDOM=!IS_IOS;Html5.prototype.featuresFullscreenResize=true;Html5.prototype.featuresProgressEvents=true;Html5.prototype.featuresTimeupdateEvents=true;Html5.prototype.featuresNativeTextTracks=Html5.supportsNativeTextTracks();Html5.prototype.featuresNativeVideoTracks=Html5.supportsNativeVideoTracks();Html5.prototype.featuresNativeAudioTracks=Html5.supportsNativeAudioTracks();var canPlayType=Html5.TEST_VID&&Html5.TEST_VID.constructor.prototype.canPlayType;var mpegurlRE=/^application\/(?:x-|vnd\.apple\.)mpegurl/i;Html5.patchCanPlayType=function(){if(ANDROID_VERSION>=4&&!IS_FIREFOX&&!IS_CHROME){Html5.TEST_VID.constructor.prototype.canPlayType=function(type){if(type&&mpegurlRE.test(type)){return"maybe"}return canPlayType.call(this,type)}}};Html5.unpatchCanPlayType=function(){var r=Html5.TEST_VID.constructor.prototype.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","played","networkState","readyState","videoWidth","videoHeight"].forEach(function(prop){Html5.prototype[prop]=function(){return this.el_[prop]}});["volume","src","poster","preload","playbackRate","defaultPlaybackRate"].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 _templateObject$2=taggedTemplateLiteralLoose(["\n 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 "],["\n 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 "]);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 Player=function(_Component){inherits(Player,_Component);function Player(tag,options,ready){classCallCheck(this,Player);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}}}var _this=possibleConstructorReturn(this,_Component.call(this,null,options,ready));_this.isPosterFromTech_=false;_this.queuedCallbacks_=[];_this.isReady_=false;_this.hasStarted_=false;_this.userActive_=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$$1){languagesToLower[name$$1.toLowerCase()]=options.languages[name$$1]});_this.languages_=languagesToLower}else{_this.languages_=Player.prototype.options_.languages}_this.cache_={};_this.poster_=options.poster||"";_this.controls_=!!options.controls;_this.cache_.lastVolume=1;tag.controls=false;tag.removeAttribute("controls");_this.scrubbing_=false;_this.el_=_this.createEl();_this.cache_.lastPlaybackRate=_this.defaultPlaybackRate();evented(_this,{eventBusKey:"el_"});var playerOptionsCopy=mergeOptions(_this.options_);if(options.plugins){var plugins=options.plugins;Object.keys(plugins).forEach(function(name$$1){if(typeof this[name$$1]==="function"){this[name$$1](plugins[name$$1])}else{throw new Error('plugin "'+name$$1+'" does not exist')}},_this)}_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(!IS_IOS){_this.addClass("vjs-workinghover")}Player.players[_this.id_]=_this;var majorVersion=version.split(".")[0];_this.addClass("vjs-v"+majorVersion);_this.userActive(true);_this.reportUserActivity();_this.one("play",_this.listenForUserActivity_);_this.on("fullscreenchange",_this.handleFullscreenChange_);_this.on("stageclick",_this.handleStageClick_);_this.changingSrc_=false;_this.playWaitingForReady_=false;_this.playOnLoadstart_=null;return _this}Player.prototype.dispose=function dispose(){this.trigger("dispose");this.off("dispose");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);_Component.prototype.dispose.call(this)};Player.prototype.createEl=function createEl$$1(){var tag=this.tag;var el=void 0;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){tag[k]=el[k]})}tag.setAttribute("tabindex","-1");tag.removeAttribute("width");tag.removeAttribute("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.width(this.options_.width);this.height(this.options_.height);this.fluid(this.options_.fluid);this.aspectRatio(this.options_.aspectRatio);var links=tag.getElementsByTagName("a");for(var i=0;i=0){techEl.width=_width}if(_height>=0){techEl.height=_height}}return}var width=void 0;var height=void 0;var aspectRatio=void 0;var idClass=void 0;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 ")};Player.prototype.loadTech_=function loadTech_(techName,source){var _this2=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 techOptions={source:source,nativeControlsForTouch:this.options_.nativeControlsForTouch,playerId:this.id(),techId:this.id()+"_"+titleTechName+"_api",autoplay:this.options_.autoplay,playsinline:this.options_.playsinline,preload:this.options_.preload,loop:this.options_.loop,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};ALL.names.forEach(function(name$$1){var props=ALL[name$$1];techOptions[props.getterName]=_this2[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){_this2.on(_this2.tech_,event,_this2["handleTech"+toTitleCase(event)+"_"])});Object.keys(TECH_EVENTS_QUEUE).forEach(function(event){_this2.on(_this2.tech_,event,function(eventObj){if(_this2.tech_.playbackRate()===0&&_this2.tech_.seeking()){_this2.queuedCallbacks_.push({callback:_this2["handleTech"+TECH_EVENTS_QUEUE[event]+"_"].bind(_this2),event:eventObj});return}_this2["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_,"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}};Player.prototype.unloadTech_=function unloadTech_(){var _this3=this;ALL.names.forEach(function(name$$1){var props=ALL[name$$1];_this3[props.privateName]=_this3[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};Player.prototype.tech=function tech(safety){if(safety===undefined){log$1.warn(tsml(_templateObject$2))}return this.tech_};Player.prototype.addTechControlsListeners_=function addTechControlsListeners_(){this.removeTechControlsListeners_();this.on(this.tech_,"mousedown",this.handleTechClick_);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_)};Player.prototype.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_,"mousedown",this.handleTechClick_)};Player.prototype.handleTechReady_=function handleTechReady_(){this.triggerReady();if(this.cache_.volume){this.techCall_("setVolume",this.cache_.volume)}this.handleTechPosterChange_();this.handleTechDurationChange_();if((this.src()||this.currentSrc())&&this.tag&&this.options_.autoplay&&this.paused()){try{delete this.tag.poster}catch(e){log$1("deleting tag.poster throws in some browsers",e)}}};Player.prototype.handleTechLoadStart_=function handleTechLoadStart_(){this.removeClass("vjs-ended");this.removeClass("vjs-seeking");this.error(null);if(!this.paused()){this.trigger("loadstart");this.trigger("firstplay")}else{this.hasStarted(false);this.trigger("loadstart")}};Player.prototype.updateSourceCaches_=function updateSourceCaches_(){var srcObj=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";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={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;i0&&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")};Player.prototype.handleTechWaiting_=function handleTechWaiting_(){var _this5=this;this.addClass("vjs-waiting");this.trigger("waiting");this.one("timeupdate",function(){return _this5.removeClass("vjs-waiting")})};Player.prototype.handleTechCanPlay_=function handleTechCanPlay_(){this.removeClass("vjs-waiting");this.trigger("canplay")};Player.prototype.handleTechCanPlayThrough_=function handleTechCanPlayThrough_(){this.removeClass("vjs-waiting");this.trigger("canplaythrough")};Player.prototype.handleTechPlaying_=function handleTechPlaying_(){this.removeClass("vjs-waiting");this.trigger("playing")};Player.prototype.handleTechSeeking_=function handleTechSeeking_(){this.addClass("vjs-seeking");this.trigger("seeking")};Player.prototype.handleTechSeeked_=function handleTechSeeked_(){this.removeClass("vjs-seeking");this.trigger("seeked")};Player.prototype.handleTechFirstPlay_=function handleTechFirstPlay_(){if(this.options_.starttime){log$1.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")};Player.prototype.handleTechPause_=function handleTechPause_(){this.removeClass("vjs-playing");this.addClass("vjs-paused");this.trigger("pause")};Player.prototype.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")};Player.prototype.handleTechDurationChange_=function handleTechDurationChange_(){this.duration(this.techGet_("duration"))};Player.prototype.handleTechClick_=function handleTechClick_(event){if(!isSingleLeftClick(event)){return}if(!this.controls_){return}if(this.paused()){this.play()}else{this.pause()}};Player.prototype.handleTechTap_=function handleTechTap_(){this.userActive(!this.userActive())};Player.prototype.handleTechTouchStart_=function handleTechTouchStart_(){this.userWasActive=this.userActive()};Player.prototype.handleTechTouchMove_=function handleTechTouchMove_(){if(this.userWasActive){this.reportUserActivity()}};Player.prototype.handleTechTouchEnd_=function handleTechTouchEnd_(event){event.preventDefault()};Player.prototype.handleFullscreenChange_=function handleFullscreenChange_(){if(this.isFullscreen()){this.addClass("vjs-fullscreen")}else{this.removeClass("vjs-fullscreen")}};Player.prototype.handleStageClick_=function handleStageClick_(){this.reportUserActivity()};Player.prototype.handleTechFullscreenChange_=function handleTechFullscreenChange_(event,data){if(data){this.isFullscreen(data.isFullscreen)}this.trigger("fullscreenchange")};Player.prototype.handleTechError_=function handleTechError_(){var error=this.tech_.error();this.error(error)};Player.prototype.handleTechTextData_=function handleTechTextData_(){var data=null;if(arguments.length>1){data=arguments[1]}this.trigger("textdata",data)};Player.prototype.getCache=function getCache(){return this.cache_};Player.prototype.techCall_=function techCall_(method,arg){this.ready(function(){if(method in allowedSetters){return set$1(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$1(e);throw e}},true)};Player.prototype.techGet_=function techGet_(method){if(!this.tech_||!this.tech_.isReady_){return}if(method in allowedGetters){return get$1(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$1("Video.js: "+method+" method not defined for "+this.techName_+" playback technology.",e);throw e}if(e.name==="TypeError"){log$1("Video.js: "+method+" unavailable on "+this.techName_+" playback technology element.",e);this.tech_.isReady_=false;throw e}log$1(e);throw e}};Player.prototype.play=function play(){var _this6=this;if(this.playOnLoadstart_){this.off("loadstart",this.playOnLoadstart_)}if(!this.isReady_){if(this.playWaitingForReady_){return}this.playWaitingForReady_=true;this.ready(function(){_this6.playWaitingForReady_=false;silencePromise(_this6.play())})}else if(!this.changingSrc_&&(this.src()||this.currentSrc())){return this.techGet_("play")}else{this.playOnLoadstart_=function(){_this6.playOnLoadstart_=null;silencePromise(_this6.play())};this.one("loadstart",this.playOnLoadstart_)}};Player.prototype.pause=function pause(){this.techCall_("pause")};Player.prototype.paused=function paused(){return this.techGet_("paused")===false?false:true};Player.prototype.played=function played(){return this.techGet_("played")||createTimeRanges(0,0)};Player.prototype.scrubbing=function scrubbing(isScrubbing){if(typeof isScrubbing==="undefined"){return this.scrubbing_}this.scrubbing_=!!isScrubbing;if(isScrubbing){this.addClass("vjs-scrubbing")}else{this.removeClass("vjs-scrubbing")}};Player.prototype.currentTime=function currentTime(seconds){if(typeof seconds!=="undefined"){if(seconds<0){seconds=0}this.techCall_("setCurrentTime",seconds);return}this.cache_.currentTime=this.techGet_("currentTime")||0;return this.cache_.currentTime};Player.prototype.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")}this.trigger("durationchange")}};Player.prototype.remainingTime=function remainingTime(){return this.duration()-this.currentTime()};Player.prototype.remainingTimeDisplay=function remainingTimeDisplay(){return Math.floor(this.duration())-Math.floor(this.currentTime())};Player.prototype.buffered=function buffered(){var buffered=this.techGet_("buffered");if(!buffered||!buffered.length){buffered=createTimeRanges(0,0)}return buffered};Player.prototype.bufferedPercent=function bufferedPercent$$1(){return bufferedPercent(this.buffered(),this.duration())};Player.prototype.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};Player.prototype.volume=function volume(percentAsDecimal){var vol=void 0;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};Player.prototype.muted=function muted(_muted){if(_muted!==undefined){this.techCall_("setMuted",_muted);return}return this.techGet_("muted")||false};Player.prototype.defaultMuted=function defaultMuted(_defaultMuted){if(_defaultMuted!==undefined){return this.techCall_("setDefaultMuted",_defaultMuted)}return this.techGet_("defaultMuted")||false};Player.prototype.lastVolume_=function lastVolume_(percentAsDecimal){if(percentAsDecimal!==undefined&&percentAsDecimal!==0){this.cache_.lastVolume=percentAsDecimal;return}return this.cache_.lastVolume};Player.prototype.supportsFullScreen=function supportsFullScreen(){return this.techGet_("supportsFullScreen")||false};Player.prototype.isFullscreen=function isFullscreen(isFS){if(isFS!==undefined){this.isFullscreen_=!!isFS;return}return!!this.isFullscreen_};Player.prototype.requestFullscreen=function requestFullscreen(){var fsApi=FullscreenApi;this.isFullscreen(true);if(fsApi.requestFullscreen){on(document_1,fsApi.fullscreenchange,bind(this,function documentFullscreenChange(e){this.isFullscreen(document_1[fsApi.fullscreenElement]);if(this.isFullscreen()===false){off(document_1,fsApi.fullscreenchange,documentFullscreenChange)}this.trigger("fullscreenchange")}));this.el_[fsApi.requestFullscreen]()}else if(this.tech_.supportsFullScreen()){this.techCall_("enterFullScreen")}else{this.enterFullWindow();this.trigger("fullscreenchange")}};Player.prototype.exitFullscreen=function exitFullscreen(){var fsApi=FullscreenApi;this.isFullscreen(false);if(fsApi.requestFullscreen){document_1[fsApi.exitFullscreen]()}else if(this.tech_.supportsFullScreen()){this.techCall_("exitFullScreen")}else{this.exitFullWindow();this.trigger("fullscreenchange")}};Player.prototype.enterFullWindow=function enterFullWindow(){this.isFullWindow=true;this.docOrigOverflow=document_1.documentElement.style.overflow;on(document_1,"keydown",bind(this,this.fullWindowOnEscKey));document_1.documentElement.style.overflow="hidden";addClass(document_1.body,"vjs-full-window");this.trigger("enterFullWindow")};Player.prototype.fullWindowOnEscKey=function fullWindowOnEscKey(event){if(event.keyCode===27){if(this.isFullscreen()===true){this.exitFullscreen()}else{this.exitFullWindow()}}};Player.prototype.exitFullWindow=function exitFullWindow(){this.isFullWindow=false;off(document_1,"keydown",this.fullWindowOnEscKey);document_1.documentElement.style.overflow=this.docOrigOverflow;removeClass(document_1.body,"vjs-full-window");this.trigger("exitFullWindow")};Player.prototype.canPlayType=function canPlayType(type){var can=void 0;for(var i=0,j=this.options_.techOrder;i1){return _this8.src(sources.slice(1))}_this8.changingSrc_=false;_this8.setTimeout(function(){this.error({code:4,message:this.localize(this.options_.notSupportedMessage)})},0);_this8.triggerReady();return}setTech(mws,_this8.tech_)})};Player.prototype.src_=function src_(source){var _this9=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(){_this9.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};Player.prototype.load=function load(){this.techCall_("load")};Player.prototype.reset=function reset(){this.loadTech_(this.options_.techOrder[0],null);this.techCall_("reset")};Player.prototype.currentSources=function currentSources(){var source=this.currentSource();var sources=[];if(Object.keys(source).length!==0){sources.push(source)}return this.cache_.sources||sources};Player.prototype.currentSource=function currentSource(){return this.cache_.source||{}};Player.prototype.currentSrc=function currentSrc(){return this.currentSource()&&this.currentSource().src||""};Player.prototype.currentType=function currentType(){return this.currentSource()&&this.currentSource().type||""};Player.prototype.preload=function preload(value){if(value!==undefined){this.techCall_("setPreload",value);this.options_.preload=value;return}return this.techGet_("preload")};Player.prototype.autoplay=function autoplay(value){if(value!==undefined){this.techCall_("setAutoplay",value);this.options_.autoplay=value;return}return this.techGet_("autoplay",value)};Player.prototype.playsinline=function playsinline(value){if(value!==undefined){this.techCall_("setPlaysinline",value);this.options_.playsinline=value;return this}return this.techGet_("playsinline")};Player.prototype.loop=function loop(value){if(value!==undefined){this.techCall_("setLoop",value);this.options_.loop=value;return}return this.techGet_("loop")};Player.prototype.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")};Player.prototype.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")}}};Player.prototype.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_()}}};Player.prototype.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")}};Player.prototype.error=function error(err){if(err===undefined){return this.error_||null}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$1.error("(CODE:"+this.error_.code+" "+MediaError.errorTypes[this.error_.code]+")",this.error_.message,this.error_);this.trigger("error");return};Player.prototype.reportUserActivity=function reportUserActivity(event){this.userActivity_=true};Player.prototype.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")};Player.prototype.listenForUserActivity_=function listenForUserActivity_(){var mouseInProgress=void 0;var lastMoveX=void 0;var lastMoveY=void 0;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 handleMouseUp=function handleMouseUp(event){handleActivity();this.clearInterval(mouseInProgress)};this.on("mousedown",handleMouseDown);this.on("mousemove",handleMouseMove);this.on("mouseup",handleMouseUp);this.on("keydown",handleActivity);this.on("keyup",handleActivity);var inactivityTimeout=void 0;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)};Player.prototype.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};Player.prototype.defaultPlaybackRate=function defaultPlaybackRate(rate){if(rate!==undefined){return this.techCall_("setDefaultPlaybackRate",rate)}if(this.tech_&&this.tech_.featuresPlaybackRate){return this.techGet_("defaultPlaybackRate")}return 1};Player.prototype.isAudio=function isAudio(bool){if(bool!==undefined){this.isAudio_=!!bool;return}return!!this.isAudio_};Player.prototype.addTextTrack=function addTextTrack(kind,label,language){if(this.tech_){return this.tech_.addTextTrack(kind,label,language)}};Player.prototype.addRemoteTextTrack=function addRemoteTextTrack(options,manualCleanup){if(this.tech_){return this.tech_.addRemoteTextTrack(options,manualCleanup)}};Player.prototype.removeRemoteTextTrack=function removeRemoteTextTrack(){var _ref3=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},_ref3$track=_ref3.track,track=_ref3$track===undefined?arguments[0]:_ref3$track;if(this.tech_){return this.tech_.removeRemoteTextTrack(track)}};Player.prototype.getVideoPlaybackQuality=function getVideoPlaybackQuality(){return this.techGet_("getVideoPlaybackQuality")};Player.prototype.videoWidth=function videoWidth(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0};Player.prototype.videoHeight=function videoHeight(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0};Player.prototype.language=function language(code){if(code===undefined){return this.language_}this.language_=String(code).toLowerCase()};Player.prototype.languages=function languages(){return mergeOptions(Player.prototype.options_.languages,this.languages_)};Player.prototype.toJSON=function toJSON(){var options=mergeOptions(this.options_);var tracks=options.tracks;options.tracks=[];for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:{};hash.name=this.name;hash.plugin=this.constructor;hash.instance=this;return hash};Plugin.prototype.trigger=function trigger$$1(event){var hash=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return trigger(this.eventBusEl_,event,this.getEventHash(hash))};Plugin.prototype.handleStateChanged=function handleStateChanged(e){};Plugin.prototype.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==="undefined"?"undefined":_typeof(name))+".")}if(pluginExists(name)){log$1.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==="undefined"?"undefined":_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(){var names=arguments.length>0&&arguments[0]!==undefined?arguments[0]:Object.keys(pluginStorage);var result=void 0;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)};var _inherits=function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass){subClass.super_=superClass}};var extendFn=function extendFn(superClass){var subClassMethods=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var subClass=function subClass(){superClass.apply(this,arguments)};var methods={};if((typeof subClassMethods==="undefined"?"undefined":_typeof(subClassMethods))==="object"){if(subClassMethods.constructor!==Object.prototype.constructor){subClass=subClassMethods.constructor}methods=subClassMethods}else if(typeof subClassMethods==="function"){subClass=subClassMethods}_inherits(subClass,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$1.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(!document_1.body.contains(el)){log$1.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$1.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(undefined,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$1=$(".vjs-styles-defaults");if(!style$1){style$1=createStyleElement("vjs-styles-defaults");var head=$("head");if(head){head.insertBefore(style$1,head.firstChild)}setTextContent(style$1,"\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=void 0;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$$1,comp){if(Tech.isTech(comp)){log$1.warn("The "+name$$1+" tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)")}Component.registerComponent.call(Component,name$$1,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=extendFn;videojs$1.mergeOptions=mergeOptions;videojs$1.bind=bind;videojs$1.registerPlugin=Plugin.registerPlugin;videojs$1.plugin=function(name$$1,plugin){log$1.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead");return Plugin.registerPlugin(name$$1,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$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$1.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;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})(commonjsGlobal)});var classCallCheck$1=function classCallCheck$$1(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var _extends$1=Object.assign||function(target){for(var i=1;i-1};Stream.prototype.trigger=function trigger(type){var callbacks=this.listeners[type];var i=void 0;var length=void 0;var args=void 0;if(!callbacks){return}if(arguments.length===2){length=callbacks.length;for(i=0;i-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=void 0;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){inherits$1(ParseStream,_Stream);function ParseStream(){classCallCheck$1(this,ParseStream);var _this=possibleConstructorReturn$1(this,_Stream.call(this));_this.customParsers=[];return _this}ParseStream.prototype.push=function push(line){var match=void 0;var event=void 0;line=line.replace(/^[\u0000\s]+|[\u0000\s]+$/g,"");if(line.length===0){return}if(line[0]!=="#"){this.trigger("data",{type:"uri",uri:line});return}for(var i=0;i0){currentUri.duration=entry.duration}if(entry.duration===0){currentUri.duration=.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.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}Parser.prototype.push=function push(chunk){this.lineStream.push(chunk)};Parser.prototype.end=function end(){this.lineStream.push("\n")};Parser.prototype.addParser=function addParser(options){this.parseStream.addParser(options)};return Parser}(Stream);var formatAudioPlaylist=function formatAudioPlaylist(_ref){var _attributes;var attributes=_ref.attributes,segments=_ref.segments;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}return playlist};var formatVttPlaylist=function formatVttPlaylist(_ref2){var _attributes2;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}return{attributes:(_attributes2={NAME:attributes.id,BANDWIDTH:attributes.bandwidth},_attributes2["PROGRAM-ID"]=1,_attributes2),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){return playlists.reduce(function(a,playlist){var role=playlist.attributes.role&&playlist.attributes.role.value||"main";var language=playlist.attributes.lang||"";var label="main";if(language){label=playlist.attributes.lang+" ("+role+")"}if(a[label]&&a[label].playlists[0].attributes.BANDWIDTH>playlist.attributes.bandwidth){return a}a[label]={language:language,autoselect:true,default:role==="main",playlists:[formatAudioPlaylist(playlist)],uri:""};return a},{})};var organizeVttPlaylists=function organizeVttPlaylists(playlists){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:[formatVttPlaylist(playlist)],uri:""};return a},{})};var formatVideoPlaylist=function formatVideoPlaylist(_ref3){var _attributes3;var attributes=_ref3.attributes,segments=_ref3.segments;var playlist={attributes:(_attributes3={NAME:attributes.id,AUDIO:"audio",SUBTITLES:"subs",RESOLUTION:{width:attributes.width,height:attributes.height},CODECS:attributes.codecs,BANDWIDTH:attributes.bandwidth},_attributes3["PROGRAM-ID"]=1,_attributes3),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}return playlist};var toM3u8=function toM3u8(dashPlaylists){var _mediaGroups;if(!dashPlaylists.length){return{}}var _dashPlaylists$0$attr=dashPlaylists[0].attributes,duration=_dashPlaylists$0$attr.sourceDuration,_dashPlaylists$0$attr2=_dashPlaylists$0$attr.minimumUpdatePeriod,minimumUpdatePeriod=_dashPlaylists$0$attr2===undefined?0:_dashPlaylists$0$attr2;var videoOnly=function videoOnly(_ref4){var attributes=_ref4.attributes;return attributes.mimeType==="video/mp4"||attributes.contentType==="video"};var audioOnly=function audioOnly(_ref5){var attributes=_ref5.attributes;return attributes.mimeType==="audio/mp4"||attributes.contentType==="audio"};var vttOnly=function vttOnly(_ref6){var attributes=_ref6.attributes;return attributes.mimeType==="text/vtt"||attributes.contentType==="text"};var videoPlaylists=dashPlaylists.filter(videoOnly).map(formatVideoPlaylist);var audioPlaylists=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:videoPlaylists,minimumUpdatePeriod:minimumUpdatePeriod*1e3};if(audioPlaylists.length){master.mediaGroups.AUDIO.audio=organizeAudioPlaylists(audioPlaylists)}if(vttPlaylists.length){master.mediaGroups.SUBTITLES.subs=organizeVttPlaylists(vttPlaylists)}return master};var isObject$1=function isObject(obj){return!!obj&&(typeof obj==="undefined"?"undefined":_typeof(obj))==="object"};var merge=function merge(){for(var _len=arguments.length,objects=Array(_len),_key=0;_key<_len;_key++){objects[_key]=arguments[_key]}return objects.reduce(function(result,source){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 resolveUrl=function resolveUrl(baseUrl,relativeUrl){if(/^[a-z]+:/i.test(relativeUrl)){return relativeUrl}if(!/\/\//i.test(baseUrl)){baseUrl=urlToolkit.buildAbsoluteURL(window_1.location.href,baseUrl)}return urlToolkit.buildAbsoluteURL(baseUrl,relativeUrl)};var urlTypeToSegment=function urlTypeToSegment(_ref7){var _ref7$baseUrl=_ref7.baseUrl,baseUrl=_ref7$baseUrl===undefined?"":_ref7$baseUrl,_ref7$source=_ref7.source,source=_ref7$source===undefined?"":_ref7$source,_ref7$range=_ref7.range,range=_ref7$range===undefined?"":_ref7$range;var init={uri:source,resolvedUri:resolveUrl(baseUrl||"",source)};if(range){var ranges=range.split("-");var startRange=parseInt(ranges[0],10);var endRange=parseInt(ranges[1],10);init.byterange={length:endRange-startRange,offset:startRange}}return init};var getLiveRValue=function getLiveRValue(attributes,time,duration){var NOW=attributes.NOW,clientOffset=attributes.clientOffset,availabilityStartTime=attributes.availabilityStartTime,_attributes$timescale=attributes.timescale,timescale=_attributes$timescale===undefined?1:_attributes$timescale,_attributes$start=attributes.start,start=_attributes$start===undefined?0:_attributes$start,_attributes$minimumUp=attributes.minimumUpdatePeriod,minimumUpdatePeriod=_attributes$minimumUp===undefined?0:_attributes$minimumUp;var now=(NOW+clientOffset)/1e3;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===undefined?"static":_attributes$type,_attributes$minimumUp2=attributes.minimumUpdatePeriod,minimumUpdatePeriod=_attributes$minimumUp2===undefined?0:_attributes$minimumUp2,_attributes$media=attributes.media,media=_attributes$media===undefined?"":_attributes$media,sourceDuration=attributes.sourceDuration,_attributes$timescale2=attributes.timescale,timescale=_attributes$timescale2===undefined?1:_attributes$timescale2,_attributes$startNumb=attributes.startNumber,startNumber=_attributes$startNumb===undefined?1:_attributes$startNumb,timeline=attributes.periodIndex;var segments=[];var time=-1;for(var sIndex=0;sIndextime){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=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===undefined?{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(attributes.baseUrl||"",uri),map:mapSegment,number:segment.number}})};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 SegmentURLToSegmentObject=function SegmentURLToSegmentObject(attributes,segmentUrl){var baseUrl=attributes.baseUrl,_attributes$initializ2=attributes.initialization,initialization=_attributes$initializ2===undefined?{}:_attributes$initializ2;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===undefined?[]:_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=void 0;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 segmentsFromBase=function segmentsFromBase(attributes){var baseUrl=attributes.baseUrl,_attributes$initializ3=attributes.initialization,initialization=_attributes$initializ3===undefined?{}:_attributes$initializ3,sourceDuration=attributes.sourceDuration,_attributes$timescale7=attributes.timescale,timescale=_attributes$timescale7===undefined?1:_attributes$timescale7,_attributes$indexRang=attributes.indexRange,indexRange=_attributes$indexRang===undefined?"":_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,range: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/timescale;segment.timeline=0}segment.number=0;return[segment]};var generateSegments=function generateSegments(_ref8){var attributes=_ref8.attributes,segmentInfo=_ref8.segmentInfo;var segmentAttributes=void 0;var segmentsFn=void 0;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)}if(!segmentsFn){return{attributes:attributes}}var segments=segmentsFn(segmentAttributes,segmentInfo.timeline);if(segmentAttributes.duration){var _segmentAttributes=segmentAttributes,duration=_segmentAttributes.duration,_segmentAttributes$ti=_segmentAttributes.timescale,timescale=_segmentAttributes$ti===undefined?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}return{attributes:segmentAttributes,segments:segments}};var toPlaylists=function toPlaylists(representations){return representations.map(generateSegments)};var findChildren=function findChildren(element,name){return from(element.childNodes).filter(function(_ref9){var tagName=_ref9.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)/1e3},minimumUpdatePeriod:function minimumUpdatePeriod(value){return parseDuration(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},{})};function decodeB64ToUint8Array(b64Text){var decodedString=window_1.atob(b64Text);var array=new Uint8Array(decodedString.length);for(var i=0;i1&&arguments[1]!==undefined?arguments[1]:{};var _options$manifestUri=options.manifestUri,manifestUri=_options$manifestUri===undefined?"":_options$manifestUri,_options$NOW=options.NOW,NOW=_options$NOW===undefined?Date.now():_options$NOW,_options$clientOffset=options.clientOffset,clientOffset=_options$clientOffset===undefined?0:_options$clientOffset;var periods=findChildren(mpd,"Period");if(periods.length!==1){throw new Error(errors.INVALID_NUMBER_OF_PERIOD)}var mpdAttributes=parseAttributes$1(mpd);var mpdBaseUrls=buildBaseUrls([manifestUri],findChildren(mpd,"BaseURL"));mpdAttributes.sourceDuration=mpdAttributes.mediaPresentationDuration||0;mpdAttributes.NOW=NOW;mpdAttributes.clientOffset=clientOffset;return flatten(periods.map(toAdaptationSets(mpdAttributes,mpdBaseUrls)))};var stringToMpdXml=function stringToMpdXml(manifestString){if(manifestString===""){throw new Error(errors.DASH_EMPTY_MANIFEST)}var parser=new window_1.DOMParser;var xml=parser.parseFromString(manifestString,"application/xml");var mpd=xml&&xml.documentElement.tagName==="MPD"?xml.documentElement:null;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){return toM3u8(toPlaylists(inheritAttributes(stringToMpdXml(manifestString),options)))};var parseUTCTiming=function parseUTCTiming(manifestString){return parseUTCTimingScheme(stringToMpdXml(manifestString))};var toUnsigned=function toUnsigned(value){return value>>>0};var bin={toUnsigned:toUnsigned};var bin_1=bin.toUnsigned;var bin$1=Object.freeze({default:bin,__moduleExports:bin,toUnsigned:bin_1});var require$$0$1=bin$1&&bin||bin$1;var toUnsigned$1=require$$0$1.toUnsigned;var _findBox,parseType,timescale,startTime;_findBox=function findBox(data,path){var results=[],i,size,type,end,subresults;if(!path.length){return null}for(i=0;i1?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};parseType=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};timescale=function timescale(init){var result={},traks=_findBox(init,["moov","trak"]);return traks.reduce(function(result,trak){var tkhd,version,index,id,mdhd;tkhd=_findBox(trak,["tkhd"])[0];if(!tkhd){return null}version=tkhd[0];index=version===0?12:20;id=toUnsigned$1(tkhd[index]<<24|tkhd[index+1]<<16|tkhd[index+2]<<8|tkhd[index+3]);mdhd=_findBox(trak,["mdia","mdhd"])[0];if(!mdhd){return null}version=mdhd[0];index=version===0?12:20;result[id]=toUnsigned$1(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(fragment,["moof","traf"]);baseTimes=[].concat.apply([],trafs.map(function(traf){return _findBox(traf,["tfhd"]).map(function(tfhd){var id,scale,baseTime;id=toUnsigned$1(tfhd[4]<<24|tfhd[5]<<16|tfhd[6]<<8|tfhd[7]);scale=timescale[id]||9e4;baseTime=_findBox(traf,["tfdt"]).map(function(tfdt){var version,result;version=tfdt[0];result=toUnsigned$1(tfdt[4]<<24|tfdt[5]<<16|tfdt[6]<<8|tfdt[7]);if(version===1){result*=Math.pow(2,32);result+=toUnsigned$1(tfdt[8]<<24|tfdt[9]<<16|tfdt[10]<<8|tfdt[11])}return result})[0];baseTime=baseTime||Infinity;return baseTime/scale})}));result=Math.min.apply(null,baseTimes);return isFinite(result)?result:0};var probe={parseType:parseType,timescale:timescale,startTime:startTime};var streamTypes={H264_STREAM_TYPE:27,ADTS_STREAM_TYPE:15,METADATA_STREAM_TYPE:21};var streamTypes_1=streamTypes.H264_STREAM_TYPE;var streamTypes_2=streamTypes.ADTS_STREAM_TYPE;var streamTypes_3=streamTypes.METADATA_STREAM_TYPE;var streamTypes$1=Object.freeze({default:streamTypes,__moduleExports:streamTypes,H264_STREAM_TYPE:streamTypes_1,ADTS_STREAM_TYPE:streamTypes_2,METADATA_STREAM_TYPE:streamTypes_3});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;ireference){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;this.push=function(data){if(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.discontinuity=function(){referenceDTS=void 0;lastDTS=void 0}};TimestampRolloverStream.prototype=new Stream$2;var timestampRolloverStream={TimestampRolloverStream:TimestampRolloverStream,handleRollover:handleRollover};var timestampRolloverStream_1=timestampRolloverStream.TimestampRolloverStream;var timestampRolloverStream_2=timestampRolloverStream.handleRollover;var timestampRolloverStream$1=Object.freeze({default:timestampRolloverStream,__moduleExports:timestampRolloverStream,TimestampRolloverStream:timestampRolloverStream_1,handleRollover:timestampRolloverStream_2});var StreamTypes=streamTypes$1&&streamTypes||streamTypes$1;var parsePid=function parsePid(packet){var pid=packet[1]&31;pid<<=8;pid|=packet[2];return pid};var parsePayloadUnitStartIndicator=function parsePayloadUnitStartIndicator(packet){return!!(packet[1]&64)};var parseAdaptionField=function parseAdaptionField(packet){var offset=0;if((packet[3]&48)>>>4>1){offset+=packet[4]+1}return offset};var parseType$1=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]&31)<<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]&1)){return}var sectionLength,tableEnd,programInfoLength;sectionLength=(packet[payloadOffset+1]&15)<<8|packet[payloadOffset+2];tableEnd=3+sectionLength-4;programInfoLength=(packet[payloadOffset+10]&15)<<8|packet[payloadOffset+11];var offset=12+programInfoLength;while(offset=packet.byteLength){return null}var pes=null;var ptsDtsFlags;ptsDtsFlags=packet[offset+7];if(ptsDtsFlags&192){pes={};pes.pts=(packet[offset+9]&14)<<27|(packet[offset+10]&255)<<20|(packet[offset+11]&254)<<12|(packet[offset+12]&255)<<5|(packet[offset+13]&254)>>>3;pes.pts*=4;pes.pts+=(packet[offset+13]&6)>>>1;pes.dts=pes.pts;if(ptsDtsFlags&64){pes.dts=(packet[offset+14]&14)<<27|(packet[offset+15]&255)<<20|(packet[offset+16]&254)<<12|(packet[offset+17]&255)<<5|(packet[offset+18]&254)>>>3;pes.dts*=4;pes.dts+=(packet[offset+18]&6)>>>1}}return pes};var parseNalUnitType=function parseNalUnitType(type){switch(type){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}};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(;frameSyncPoint3){nalType=parseNalUnitType(frameBuffer[frameSyncPoint+3]&31);if(nalType==="slice_layer_without_partitioning_rbsp_idr"){foundKeyFrame=true}}return foundKeyFrame};var probe$1={parseType:parseType$1,parsePat:parsePat,parsePmt:parsePmt,parsePayloadUnitStartIndicator:parsePayloadUnitStartIndicator,parsePesType:parsePesType,parsePesTime:parsePesTime,videoPacketContainsKeyFrame:videoPacketContainsKeyFrame};var probe_1$1=probe$1.parseType;var probe_2$1=probe$1.parsePat;var probe_3$1=probe$1.parsePmt;var probe_4=probe$1.parsePayloadUnitStartIndicator;var probe_5=probe$1.parsePesType;var probe_6=probe$1.parsePesTime;var probe_7=probe$1.videoPacketContainsKeyFrame;var probe$2=Object.freeze({default:probe$1,__moduleExports:probe$1,parseType:probe_1$1,parsePat:probe_2$1,parsePmt:probe_3$1,parsePayloadUnitStartIndicator:probe_4,parsePesType:probe_5,parsePesTime:probe_6,videoPacketContainsKeyFrame:probe_7});var ADTS_SAMPLING_FREQUENCIES=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];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>4;if(footerPresent){return returnSize+20}return returnSize+10};var parseAdtsSize=function parseAdtsSize(header,byteIndex){var lowThree=(header[byteIndex+5]&224)>>5,middle=header[byteIndex+4]<<3,highTwo=header[byteIndex+3]&3<<11;return highTwo|middle|lowThree};var parseType$2=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]&255===255&&(header[byteIndex+1]&240)===240){return"audio"}return null};var parseSampleRate=function parseSampleRate(packet){var i=0;while(i+5>>2]}return null};var parseAacTimestamp=function parseAacTimestamp(packet){var frameStart,frameSize,frame,frameHeader;frameStart=10;if(packet[5]&64){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>>2;size*=4;size+=d[7]&3;return size}break}}}frameStart+=10;frameStart+=frameSize}while(frameStart=0){if(bytes[startIndex]===SYNC_BYTE&&bytes[endIndex]===SYNC_BYTE){packet=bytes.subarray(startIndex,endIndex);type=probe$5.ts.parseType(packet,pmt.pid);switch(type){case"pes":pesType=probe$5.ts.parsePesType(packet,pmt.table);pusi=probe$5.ts.parsePayloadUnitStartIndicator(packet);if(pesType==="audio"&&pusi){parsed=probe$5.ts.parsePesTime(packet);if(parsed){parsed.type="audio";result.audio.push(parsed);endLoop=true}}break;default: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=0){if(bytes[startIndex]===SYNC_BYTE&&bytes[endIndex]===SYNC_BYTE){packet=bytes.subarray(startIndex,endIndex);type=probe$5.ts.parseType(packet,pmt.pid);switch(type){case"pes":pesType=probe$5.ts.parsePesType(packet,pmt.table);pusi=probe$5.ts.parsePayloadUnitStartIndicator(packet);if(pesType==="video"&&pusi){parsed=probe$5.ts.parsePesTime(packet);if(parsed){parsed.type="video";result.video.push(parsed);endLoop=true}}break;default: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/PES_TIMESCALE;info.ptsTime=info.pts/PES_TIMESCALE})}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/PES_TIMESCALE;info.ptsTime=info.pts/PES_TIMESCALE});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/PES_TIMESCALE;frame.ptsTime=frame.dts/PES_TIMESCALE}}};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$5.aac.parseType(bytes,byteIndex);switch(type){case"timed-metadata":if(bytes.length-byteIndex<10){endLoop=true;break}frameSize=probe$5.aac.parseId3TagSize(bytes,byteIndex);if(frameSize>bytes.length){endLoop=true;break}if(timestamp===null){packet=bytes.subarray(byteIndex,byteIndex+frameSize);timestamp=probe$5.aac.parseAacTimestamp(packet)}byteIndex+=frameSize;break;case"audio":if(bytes.length-byteIndex<7){endLoop=true;break}frameSize=probe$5.aac.parseAdtsSize(bytes,byteIndex);if(frameSize>bytes.length){endLoop=true;break}if(sampleRate===null){packet=bytes.subarray(byteIndex,byteIndex+frameSize);sampleRate=probe$5.aac.parseSampleRate(packet)}audioCount++;byteIndex+=frameSize;break;default:byteIndex++;break}if(endLoop){return null}}if(sampleRate===null||timestamp===null){return null}var audioTimescale=PES_TIMESCALE/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;default:break}}}return result};var inspect=function inspect(bytes,baseTimestamp){var isAacData=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};function unpad(padded){return padded.subarray(0,padded.byteLength-padded[padded.byteLength-1])}var classCallCheck$2=function classCallCheck$$1(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var createClass$1=function(){function defineProperties(target,props){for(var i=0;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*16843009^x4*65537^x2*257^x*16843008;tEnc=d[s]*257^s*16843008;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){classCallCheck$2(this,AES);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=void 0;var j=void 0;var tmp=void 0;var encKey=void 0;var decKey=void 0;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")}encKey=key.slice(0);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]]}}}AES.prototype.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=void 0;var b2=void 0;var c2=void 0;var nInnerRounds=key.length/4-2;var i=void 0;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>>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 Stream$3=function(){function Stream(){classCallCheck$2(this,Stream);this.listeners={}}Stream.prototype.on=function on(type,listener){if(!this.listeners[type]){this.listeners[type]=[]}this.listeners[type].push(listener)};Stream.prototype.off=function off(type,listener){if(!this.listeners[type]){return false}var index=this.listeners[type].indexOf(listener);this.listeners[type].splice(index,1);return index>-1};Stream.prototype.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>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=void 0;var init1=void 0;var init2=void 0;var init3=void 0;var encrypted0=void 0;var encrypted1=void 0;var encrypted2=void 0;var encrypted3=void 0;var wordIx=void 0;init0=initVector[0];init1=initVector[1];init2=initVector[2];init3=initVector[3];for(wordIx=0;wordIx=500?4:2};this.trigger("error")};PlaylistLoader.prototype.haveMetadata=function haveMetadata(xhr,url){var _this3=this;this.request=null;this.state="HAVE_METADATA";var parser=new Parser;parser.push(xhr.responseText);parser.end();parser.manifest.uri=url;parser.manifest.attributes=parser.manifest.attributes||{};var update=updateMaster(this.master,parser.manifest);this.targetDuration=parser.manifest.targetDuration;if(update){this.master=update;this.media_=this.master.playlists[parser.manifest.uri]}else{this.trigger("playlistunchanged")}if(!this.media().endList){window_1.clearTimeout(this.mediaUpdateTimeout);this.mediaUpdateTimeout=window_1.setTimeout(function(){_this3.trigger("mediaupdatetimeout")},refreshDelay(this.media(),!!update))}this.trigger("loadedplaylist")};PlaylistLoader.prototype.dispose=function dispose(){this.stopRequest();window_1.clearTimeout(this.mediaUpdateTimeout)};PlaylistLoader.prototype.stopRequest=function stopRequest(){if(this.request){var oldRequest=this.request;this.request=null;oldRequest.onreadystatechange=null;oldRequest.abort()}};PlaylistLoader.prototype.media=function media(playlist){var _this4=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.master.playlists[playlist]){throw new Error("Unknown playlist URI: "+playlist)}playlist=this.master.playlists[playlist]}var mediaChange=!this.media_||playlist.uri!==this.media_.uri;if(this.master.playlists[playlist.uri].endList){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");this.trigger("mediachange")}return}if(!mediaChange){return}this.state="SWITCHING_MEDIA";if(this.request){if(resolveUrl$1(this.master.uri,playlist.uri)===this.request.url){return}this.request.onreadystatechange=null;this.request.abort();this.request=null}if(this.media_){this.trigger("mediachanging")}this.request=this.hls_.xhr({uri:resolveUrl$1(this.master.uri,playlist.uri),withCredentials:this.withCredentials},function(error,req){if(!_this4.request){return}if(error){return _this4.playlistRequestError(_this4.request,playlist.uri,startingState)}_this4.haveMetadata(req,playlist.uri);if(startingState==="HAVE_MASTER"){_this4.trigger("loadedmetadata")}else{_this4.trigger("mediachange")}})};PlaylistLoader.prototype.pause=function pause(){this.stopRequest();window_1.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"}};PlaylistLoader.prototype.load=function load(isFinalRendition){var _this5=this;window_1.clearTimeout(this.mediaUpdateTimeout);var media=this.media();if(isFinalRendition){var delay=media?media.targetDuration/2*1e3:5*1e3;this.mediaUpdateTimeout=window_1.setTimeout(function(){return _this5.load()},delay);return}if(!this.started){this.start();return}if(media&&!media.endList){this.trigger("mediaupdatetimeout")}else{this.trigger("loadedplaylist")}};PlaylistLoader.prototype.start=function start(){var _this6=this;this.started=true;this.request=this.hls_.xhr({uri:this.srcUrl,withCredentials:this.withCredentials},function(error,req){if(!_this6.request){return}_this6.request=null;if(error){_this6.error={status:req.status,message:"HLS playlist request error at URL: "+_this6.srcUrl,responseText:req.responseText,code:2};if(_this6.state==="HAVE_NOTHING"){_this6.started=false}return _this6.trigger("error")}var parser=new Parser;parser.push(req.responseText);parser.end();_this6.state="HAVE_MASTER";parser.manifest.uri=_this6.srcUrl;if(parser.manifest.playlists){_this6.master=parser.manifest;setupMediaPlaylists(_this6.master);resolveMediaGroupUris(_this6.master);_this6.trigger("loadedplaylist");if(!_this6.request){_this6.media(parser.manifest.playlists[0])}return}_this6.master={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:window_1.location.href,playlists:[{uri:_this6.srcUrl,id:0}]};_this6.master.playlists[_this6.srcUrl]=_this6.master.playlists[0];_this6.master.playlists[0].resolvedUri=_this6.srcUrl;_this6.master.playlists[0].attributes=_this6.master.playlists[0].attributes||{};_this6.haveMetadata(req,_this6.srcUrl);return _this6.trigger("loadedmetadata")})};return PlaylistLoader}(EventTarget$1);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=void 0;var i=endSequence-playlist.mediaSequence;for(;iendIndex){var _ref=[endIndex,startIndex];startIndex=_ref[0];endIndex=_ref[1]}if(startIndex<0){for(var i=startIndex;i=safeDistance){break}}return Math.max(0,i)};var playlistEnd=function playlistEnd(playlist,expired,useSafeLiveEnd){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):playlist.segments.length;return intervalDuration(playlist,playlist.mediaSequence+endSequence,expired)};var seekable=function seekable(playlist,expired){var useSafeLiveEnd=true;var seekableStart=expired||0;var seekableEnd=playlistEnd(playlist,expired,useSafeLiveEnd);if(seekableEnd===null){return createTimeRange()}return createTimeRange(seekableStart,seekableEnd)};var isWholeNumber=function isWholeNumber(num){return num-Math.floor(num)===0};var roundSignificantDigit=function roundSignificantDigit(increment,num){if(isWholeNumber(num)){return num+increment*.1}var numDecimalDigits=num.toString().split(".")[1].length;for(var i=1;i<=numDecimalDigits;i++){var scale=Math.pow(10,i);var temp=num*scale;if(isWholeNumber(temp)||i===numDecimalDigits){return(temp+increment)/scale}}};var ceilLeastSignificantDigit=roundSignificantDigit.bind(null,1);var floorLeastSignificantDigit=roundSignificantDigit.bind(null,-1);var getMediaInfoForTime=function getMediaInfoForTime(playlist,currentTime,startIndex,startTime){var i=void 0;var segment=void 0;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+=floorLeastSignificantDigit(segment.duration);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;iDate.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;i3&&arguments[3]!==undefined?arguments[3]: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)=32&&e<126){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 hexDump=function hexDump(data){var bytes=Array.prototype.slice.call(data);var step=16;var result="";var hex=void 0;var ascii=void 0;for(var j=0;j=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 "+range.end(i))}return strArr.join(", ")};var timeUntilRebuffer=function timeUntilRebuffer(buffered,currentTime){var playbackRate=arguments.length>2&&arguments[2]!==undefined?arguments[2]: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=start){track.removeCue(cue)}}};var deprecateOldCue=function deprecateOldCue(cue){Object.defineProperties(cue.frame,{id:{get:function get$$1(){videojs$1.log.warn("cue.frame.id is deprecated. Use cue.value.key instead.");return cue.value.key}},value:{get:function get$$1(){videojs$1.log.warn("cue.frame.value is deprecated. Use cue.value.data instead.");return cue.value.data}},privateData:{get:function get$$1(){videojs$1.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead.");return cue.value.data}}})};var durationOfVideo=function durationOfVideo(duration){var dur=void 0;if(isNaN(duration)||Math.abs(duration)===Infinity){dur=Number.MAX_VALUE}else{dur=duration}return dur};var addTextTrackData=function addTextTrackData(sourceHandler,captionArray,metadataArray){var Cue=window_1.WebKitDataCue||window_1.VTTCue;if(captionArray){captionArray.forEach(function(caption){var track=caption.stream;this.inbandTextTracks_[track].addCue(new Cue(caption.startTime+this.timestampOffset,caption.endTime+this.timestampOffset,caption.text))},sourceHandler)}if(metadataArray){var videoDuration=durationOfVideo(sourceHandler.mediaSource_.duration);metadataArray.forEach(function(metadata){var time=metadata.cueTime+this.timestampOffset;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);this.metadataTrack_.addCue(cue)},this)},sourceHandler);if(sourceHandler.metadataTrack_&&sourceHandler.metadataTrack_.cues&&sourceHandler.metadataTrack_.cues.length){var cues=sourceHandler.metadataTrack_.cues;var cuesArray=[];for(var i=0;i>>1,track.samplingfrequencyindex<<7|track.channelcount<<3,6,1,2]))};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([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,track.duration>>>24&255,track.duration>>>16&255,track.duration>>>8&255,track.duration&255,85,196,0,0]);if(track.samplerate){result[12]=track.samplerate>>>24&255;result[13]=track.samplerate>>>16&255;result[14]=track.samplerate>>>8&255;result[15]=track.samplerate&255}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([0,0,0,0,(sequenceNumber&4278190080)>>24,(sequenceNumber&16711680)>>16,(sequenceNumber&65280)>>8,sequenceNumber&255]))};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(4294967295)].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([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(duration&4278190080)>>24,(duration&16711680)>>16,(duration&65280)>>8,duration&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return box(types.mvhd,bytes)};sdtp=function sdtp(track){var samples=track.samples||[],bytes=new Uint8Array(4+samples.length),flags,i;for(i=0;i>>8);sequenceParameterSets.push(sps[i].byteLength&255);sequenceParameterSets=sequenceParameterSets.concat(Array.prototype.slice.call(sps[i]))}for(i=0;i>>8);pictureParameterSets.push(pps[i].byteLength&255);pictureParameterSets=pictureParameterSets.concat(Array.prototype.slice.call(pps[i]))}return box(types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,(track.width&65280)>>8,track.width&255,(track.height&65280)>>8,track.height&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),box(types.avcC,new Uint8Array([1,track.profileIdc,track.profileCompatibility,track.levelIdc,255].concat([sps.length]).concat(sequenceParameterSets).concat([pps.length]).concat(pictureParameterSets))),box(types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])))};audioSample=function audioSample(track){return box(types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(track.channelcount&65280)>>8,track.channelcount&255,(track.samplesize&65280)>>8,track.samplesize&255,0,0,0,0,(track.samplerate&65280)>>8,track.samplerate&255,0,0]),esds(track))}})();tkhd=function tkhd(track){var result=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(track.id&4278190080)>>24,(track.id&16711680)>>16,(track.id&65280)>>8,track.id&255,0,0,0,0,(track.duration&4278190080)>>24,(track.duration&16711680)>>16,(track.duration&65280)>>8,track.duration&255,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,(track.width&65280)>>8,track.width&255,0,0,(track.height&65280)>>8,track.height&255,0,0]);return box(types.tkhd,result)};traf=function traf(track){var trackFragmentHeader,trackFragmentDecodeTime,trackFragmentRun,sampleDependencyTable,dataOffset,upperWordBaseMediaDecodeTime,lowerWordBaseMediaDecodeTime;trackFragmentHeader=box(types.tfhd,new Uint8Array([0,0,0,58,(track.id&4278190080)>>24,(track.id&16711680)>>16,(track.id&65280)>>8,track.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0]));upperWordBaseMediaDecodeTime=Math.floor(track.baseMediaDecodeTime/(UINT32_MAX+1));lowerWordBaseMediaDecodeTime=Math.floor(track.baseMediaDecodeTime%(UINT32_MAX+1));trackFragmentDecodeTime=box(types.tfdt,new Uint8Array([1,0,0,0,upperWordBaseMediaDecodeTime>>>24&255,upperWordBaseMediaDecodeTime>>>16&255,upperWordBaseMediaDecodeTime>>>8&255,upperWordBaseMediaDecodeTime&255,lowerWordBaseMediaDecodeTime>>>24&255,lowerWordBaseMediaDecodeTime>>>16&255,lowerWordBaseMediaDecodeTime>>>8&255,lowerWordBaseMediaDecodeTime&255]));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||4294967295;return box(types.trak,tkhd(track),mdia(track))};trex=function trex(track){var result=new Uint8Array([0,0,0,0,(track.id&4278190080)>>24,(track.id&16711680)>>16,(track.id&65280)>>8,track.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);if(track.type!=="video"){result[result.length-1]=0}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=1}if(samples[0].size!==undefined){sizePresent=2}if(samples[0].flags!==undefined){flagsPresent=4}if(samples[0].compositionTimeOffset!==undefined){compositionTimeOffset=8}}return[0,0,durationPresent|sizePresent|flagsPresent|compositionTimeOffset,1,(samples.length&4278190080)>>>24,(samples.length&16711680)>>>16,(samples.length&65280)>>>8,samples.length&255,(offset&4278190080)>>>24,(offset&16711680)>>>16,(offset&65280)>>>8,offset&255]};videoTrun=function videoTrun(track,offset){var bytes,samples,sample,i;samples=track.samples||[];offset+=8+12+16*samples.length;bytes=trunHeader(samples,offset);for(i=0;i>>24,(sample.duration&16711680)>>>16,(sample.duration&65280)>>>8,sample.duration&255,(sample.size&4278190080)>>>24,(sample.size&16711680)>>>16,(sample.size&65280)>>>8,sample.size&255,sample.flags.isLeading<<2|sample.flags.dependsOn,sample.flags.isDependedOn<<6|sample.flags.hasRedundancy<<4|sample.flags.paddingValue<<1|sample.flags.isNonSyncSample,sample.flags.degradationPriority&240<<8,sample.flags.degradationPriority&15,(sample.compositionTimeOffset&4278190080)>>>24,(sample.compositionTimeOffset&16711680)>>>16,(sample.compositionTimeOffset&65280)>>>8,sample.compositionTimeOffset&255])}return box(types.trun,new Uint8Array(bytes))};audioTrun=function audioTrun(track,offset){var bytes,samples,sample,i;samples=track.samples||[];offset+=8+12+8*samples.length;bytes=trunHeader(samples,offset);for(i=0;i>>24,(sample.duration&16711680)>>>16,(sample.duration&65280)>>>8,sample.duration&255,(sample.size&4278190080)>>>24,(sample.size&16711680)>>>16,(sample.size&65280)>>>8,sample.size&255])}return box(types.trun,new Uint8Array(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 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>>8;char1=data&255;if(data===this.PADDING_){return}else if(data===this.RESUME_CAPTION_LOADING_){this.mode_="popOn"}else if(data===this.END_OF_CAPTION_){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.topRow_=BOTTOM_ROW-1;this.mode_="rollUp"}else if(data===this.ROLL_UP_3_ROWS_){this.topRow_=BOTTOM_ROW-2;this.mode_="rollUp"}else if(data===this.ROLL_UP_4_ROWS_){this.topRow_=BOTTOM_ROW-3;this.mode_="rollUp"}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_[BOTTOM_ROW]=this.nonDisplayed_[BOTTOM_ROW].slice(0,-1)}else{this.displayed_[BOTTOM_ROW]=this.displayed_[BOTTOM_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_){this.mode_="paintOn"}else if(this.isSpecialCharacter(char0,char1)){char0=(char0&3)<<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_[BOTTOM_ROW]=this.displayed_[BOTTOM_ROW].slice(0,-1)}char0=(char0&3)<<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&14)===14){this.addFormatting(packet.pts,["i"])}if((char1&1)===1){this.addFormatting(packet.pts,["u"])}}else if(this.isOffsetControlCode(char0,char1)){this.column_+=char1&3}else if(this.isPAC(char0,char1)){var row=ROWS.indexOf(data&7968);if(row!==this.row_){this.clearFormatting(packet.pts);this.row_=row}if(char1&1&&this.formatting_.indexOf("u")===-1){this.addFormatting(packet.pts,["u"])}if((data&16)===16){this.column_=((data&14)>>1)*4}if(this.isColorPAC(char1)){if((char1&14)===14){this.addFormatting(packet.pts,["i"])}}}else if(this.isNormalChar(char0)){if(char1===0){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){return row.trim()}).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.formatting_=[]};Cea608Stream.prototype.setConstants=function(){if(this.dataChannel_===0){this.BASE_=16;this.EXT_=17;this.CONTROL_=(20|this.field_)<<8;this.OFFSET_=23}else if(this.dataChannel_===1){this.BASE_=24;this.EXT_=25;this.CONTROL_=(28|this.field_)<<8;this.OFFSET_=31}this.PADDING_=0;this.RESUME_CAPTION_LOADING_=this.CONTROL_|32;this.END_OF_CAPTION_=this.CONTROL_|47;this.ROLL_UP_2_ROWS_=this.CONTROL_|37;this.ROLL_UP_3_ROWS_=this.CONTROL_|38;this.ROLL_UP_4_ROWS_=this.CONTROL_|39;this.CARRIAGE_RETURN_=this.CONTROL_|45;this.RESUME_DIRECT_CAPTIONING_=this.CONTROL_|41;this.BACKSPACE_=this.CONTROL_|33;this.ERASE_DISPLAYED_MEMORY_=this.CONTROL_|44;this.ERASE_NON_DISPLAYED_MEMORY_=this.CONTROL_|46};Cea608Stream.prototype.isSpecialCharacter=function(char0,char1){return char0===this.EXT_&&char1>=48&&char1<=63};Cea608Stream.prototype.isExtCharacter=function(char0,char1){return(char0===this.EXT_+1||char0===this.EXT_+2)&&char1>=32&&char1<=63};Cea608Stream.prototype.isMidRowCode=function(char0,char1){return char0===this.EXT_&&char1>=32&&char1<=47};Cea608Stream.prototype.isOffsetControlCode=function(char0,char1){return char0===this.OFFSET_&&char1>=33&&char1<=35};Cea608Stream.prototype.isPAC=function(char0,char1){return char0>=this.BASE_&&char0=64&&char1<=127};Cea608Stream.prototype.isColorPAC=function(char1){return char1>=64&&char1<=79||char1>=96&&char1<=127};Cea608Stream.prototype.isNormalChar=function(char){return char>=32&&char<=127};Cea608Stream.prototype.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_[BOTTOM_ROW];baseRow+=text;this.displayed_[BOTTOM_ROW]=baseRow};Cea608Stream.prototype.shiftRowsUp_=function(){var i;for(i=0;ireference){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;this.push=function(data){if(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.discontinuity=function(){referenceDTS=void 0;lastDTS=void 0}};TimestampRolloverStream.prototype=new stream;var timestampRolloverStream={TimestampRolloverStream:TimestampRolloverStream,handleRollover:handleRollover};var percentEncode=function percentEncode(bytes,start,end){var i,result="";for(i=start;i>>2;size*=4;size+=d[7]&3;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>>4>1){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:27,adts:15};_ElementaryStream=function ElementaryStream(){var self=this,video={data:[],size:0},audio={data:[],size:0},timedMetadata={data:[],size:0},parsePes=function parsePes(payload,pes){var ptsDtsFlags;pes.packetLength=6+(payload[4]<<8|payload[5]);pes.dataAlignmentIndicator=(payload[6]&4)!==0;ptsDtsFlags=payload[7];if(ptsDtsFlags&192){pes.pts=(payload[9]&14)<<27|(payload[10]&255)<<20|(payload[11]&254)<<12|(payload[12]&255)<<5|(payload[13]&254)>>>3;pes.pts*=4;pes.pts+=(payload[13]&6)>>>1;pes.dts=pes.pts;if(ptsDtsFlags&64){pes.dts=(payload[14]&14)<<27|(payload[15]&255)<<20|(payload[16]&254)<<12|(payload[17]&255)<<5|(payload[18]&254)>>>3;pes.dts*=4;pes.dts+=(payload[18]&6)>>>1}}pes.data=payload.subarray(9+payload[8])},flushStream=function flushStream(stream$$1,type,forceFlush){var packetData=new Uint8Array(stream$$1.size),event={type:type},i=0,offset=0,packetFlushable=false,fragment;if(!stream$$1.data.length||stream$$1.size<9){return}event.trackId=stream$$1.data[0].pid;for(i=0;i>5;sampleCount=((buffer[i+6]&3)+1)*1024;adtsFrameDuration=sampleCount*9e4/ADTS_SAMPLING_FREQUENCIES[(buffer[i+2]&60)>>>2];frameEnd=i+frameLength;if(buffer.byteLength>>6&3)+1,channelcount:(buffer[i+2]&1)<<2|(buffer[i+3]&192)>>>6,samplerate:ADTS_SAMPLING_FREQUENCIES[(buffer[i+2]&60)>>>2],samplingfrequencyindex:(buffer[i+2]&60)>>>2,samplesize:16,data:buffer.subarray(i+7+protectionSkipBytes,frameEnd)});if(buffer.byteLength===frameEnd){buffer=undefined;return}frameNum++;buffer=buffer.subarray(frameEnd)}};this.flush=function(){this.trigger("done")}};_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<>>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(1&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}for(;syncPoint3){this.trigger("data",buffer.subarray(syncPoint+3))}buffer=null;syncPoint=0;this.trigger("done")}};_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]&31){case 5:event.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:event.nalUnitType="sei_rbsp";event.escapedRBSP=discardEmulationPreventionBytes(data.subarray(1));break;case 7:event.nalUnitType="seq_parameter_set_rbsp";event.escapedRBSP=discardEmulationPreventionBytes(data.subarray(1));event.config=readSequenceParameterSet(event.escapedRBSP);break;case 8:event.nalUnitType="pic_parameter_set_rbsp";break;case 9:event.nalUnitType="access_unit_delimiter_rbsp";break;default:break}self.trigger("data",event)});nalByteStream.on("done",function(){self.trigger("done")});this.flush=function(){nalByteStream.flush()};skipScalingList=function skipScalingList(count,expGolombDecoder){var lastScale=8,nextScale=8,j,deltaScale;for(j=0;j>4;if(footerPresent){return returnSize+20}return returnSize+10};this.parseAdtsSize=function(header,byteIndex){var lowThree=(header[byteIndex+5]&224)>>5,middle=header[byteIndex+4]<<3,highTwo=header[byteIndex+3]&3<<11;return highTwo|middle|lowThree};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=this.parseId3TagSize(everything,byteIndex);if(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]&255===255&&(everything[byteIndex+1]&240)===240){if(everything.length-byteIndex<7){break}frameSize=this.parseAdtsSize(everything,byteIndex);if(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}}};_AacStream.prototype=new stream;var aac=_AacStream;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 coneOfSilence={96e3:[highPrefix,[227,64],zeroFill(154),[56]],88200:[highPrefix,[231],zeroFill(170),[56]],64e3:[highPrefix,[248,192],zeroFill(240),[56]],48e3:[highPrefix,[255,192],zeroFill(268),[55,148,128],zeroFill(54),[112]],44100:[highPrefix,[255,192],zeroFill(268),[55,163,128],zeroFill(84),[112]],32e3:[highPrefix,[255,192],zeroFill(268),[55,234],zeroFill(226),[112]],24e3:[highPrefix,[255,192],zeroFill(268),[55,255,128],zeroFill(268),[111,112],zeroFill(126),[224]],16e3:[highPrefix,[255,192],zeroFill(268),[55,255,128],zeroFill(268),[111,255],zeroFill(269),[223,108],zeroFill(195),[1,192]],12e3:[lowPrefix,zeroFill(268),[3,127,248],zeroFill(268),[6,255,240],zeroFill(268),[13,255,224],zeroFill(268),[27,253,128],zeroFill(259),[56]],11025:[lowPrefix,zeroFill(268),[3,127,248],zeroFill(268),[6,255,240],zeroFill(268),[13,255,224],zeroFill(268),[27,255,192],zeroFill(268),[55,175,128],zeroFill(108),[112]],8e3:[lowPrefix,zeroFill(268),[3,121,16],zeroFill(47),[7]]};var silence=makeTable(coneOfSilence);var ONE_SECOND_IN_TS=9e4,secondsToVideoTs,secondsToAudioTs,videoTsToSeconds,audioTsToSeconds,audioTsToVideoTs,videoTsToAudioTs;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)};var clock={secondsToVideoTs:secondsToVideoTs,secondsToAudioTs:secondsToAudioTs,videoTsToSeconds:videoTsToSeconds,audioTsToSeconds:audioTsToSeconds,audioTsToVideoTs:audioTsToVideoTs,videoTsToAudioTs:videoTsToAudioTs};var H264Stream=h264.H264Stream;var AUDIO_PROPERTIES=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"];var VIDEO_PROPERTIES=["width","height","profileIdc","levelIdc","profileCompatibility"];var ONE_SECOND_IN_TS$1=9e4;var _VideoSegmentStream,_AudioSegmentStream,_Transmuxer,_CoalesceStream;var createDefaultSample,isLikelyAacData,collectDtsInfo,clearDtsInfo,calculateTrackBaseMediaDecodeTime,arrayEquals,sumFrameByteLengths;createDefaultSample=function createDefaultSample(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0}}};isLikelyAacData=function isLikelyAacData(data){if(data[0]==="I".charCodeAt(0)&&data[1]==="D".charCodeAt(0)&&data[2]==="3".charCodeAt(0)){return true}return false};arrayEquals=function arrayEquals(a,b){var i;if(a.length!==b.length){return false}for(i=0;iONE_SECOND_IN_TS$1/2){return}silentFrame=silence[track.samplerate];if(!silentFrame){silentFrame=frames[0].data}for(i=0;i=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})};this.generateSampleTable_=function(frames){var i,currentFrame,samples=[];for(i=0;i=-allowableOverlap&&dtsDistance<=halfSecond){if(!nearestGopObj||nearestDistance>dtsDistance){nearestGopObj=currentGopObj;nearestDistance=dtsDistance}}}if(nearestGopObj){return nearestGopObj.gop}return null};this.extendFirstKeyFrame_=function(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};this.groupNalsIntoFrames_=function(nalUnits){var i,currentNal,currentFrame=[],frames=[];currentFrame.byteLength=0;for(i=0;ialign.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;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)}}};clearDtsInfo=function clearDtsInfo(track){delete track.minSegmentDts;delete track.maxSegmentDts;delete track.minSegmentPts;delete track.maxSegmentPts};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};_CoalesceStream=function CoalesceStream(options,metadataStream){this.numberOfTracks=0;this.metadataStream=metadataStream;if(typeof options.remux!=="undefined"){this.remuxTracks=!!options.remux}else{this.remuxTracks=true}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.pendingBoxes.push(output.boxes);this.pendingBytes+=output.boxes.byteLength;if(output.track.type==="video"){this.videoTrack=output.track}if(output.track.type==="audio"){this.audioTrack=output.track}}};_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){this.trigger("done");this.emittedTracks=0}return}}if(this.videoTrack){timelineStartPts=this.videoTrack.timelineStartInfo.pts;VIDEO_PROPERTIES.forEach(function(prop){event.info[prop]=this.videoTrack[prop]},this)}else if(this.audioTrack){timelineStartPts=this.audioTrack.timelineStartInfo.pts;AUDIO_PROPERTIES.forEach(function(prop){event.info[prop]=this.audioTrack[prop]},this)}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.numberOfTracks){this.trigger("done");this.emittedTracks=0}};_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"&&!pipeline.audioSegmentStream){audioTrack=audioTrack||{timelineStartInfo:{baseMediaDecodeTime:self.baseMediaDecodeTime},codec:"adts",type:"audio"};pipeline.coalesceStream.numberOfTracks++;pipeline.audioSegmentStream=new _AudioSegmentStream(audioTrack,options);pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream)}});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.videoTimestampRolloverStream=new m2ts_1.TimestampRolloverStream("video");pipeline.audioTimestampRolloverStream=new m2ts_1.TimestampRolloverStream("audio");pipeline.timedMetadataTimestampRolloverStream=new m2ts_1.TimestampRolloverStream("timed-metadata");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);pipeline.elementaryStream.pipe(pipeline.videoTimestampRolloverStream).pipe(pipeline.h264Stream);pipeline.elementaryStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);pipeline.elementaryStream.pipe(pipeline.timedMetadataTimestampRolloverStream).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){audioTrack.timelineStartInfo=timelineStartInfo;pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts)}});pipeline.videoSegmentStream.on("processedGopsInfo",self.trigger.bind(self,"gopInfo"));pipeline.videoSegmentStream.on("baseMediaDecodeTime",function(baseMediaDecodeTime){if(audioTrack){pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime)}});pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream)}if(audioTrack&&!pipeline.audioSegmentStream){pipeline.coalesceStream.numberOfTracks++;pipeline.audioSegmentStream=new _AudioSegmentStream(audioTrack,options);pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream)}}});pipeline.coalesceStream.on("data",this.trigger.bind(this,"data"));pipeline.coalesceStream.on("done",this.trigger.bind(this,"done"))};this.setBaseMediaDecodeTime=function(baseMediaDecodeTime){var pipeline=this.transmuxPipeline_;this.baseMediaDecodeTime=baseMediaDecodeTime;if(audioTrack){audioTrack.timelineStartInfo.dts=undefined;audioTrack.timelineStartInfo.pts=undefined;clearDtsInfo(audioTrack);audioTrack.timelineStartInfo.baseMediaDecodeTime=baseMediaDecodeTime;if(pipeline.audioTimestampRolloverStream){pipeline.audioTimestampRolloverStream.discontinuity()}}if(videoTrack){if(pipeline.videoSegmentStream){pipeline.videoSegmentStream.gopCache_=[];pipeline.videoTimestampRolloverStream.discontinuity()}videoTrack.timelineStartInfo.dts=undefined;videoTrack.timelineStartInfo.pts=undefined;clearDtsInfo(videoTrack);pipeline.captionStream.reset();videoTrack.timelineStartInfo.baseMediaDecodeTime=baseMediaDecodeTime}if(pipeline.timedMetadataTimestampRolloverStream){pipeline.timedMetadataTimestampRolloverStream.discontinuity()}};this.setAudioAppendStart=function(timestamp){if(audioTrack){this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp)}};this.alignGopsWith=function(gopsToAlignWith){if(videoTrack&&this.transmuxPipeline_.videoSegmentStream){this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith)}};this.push=function(data){if(hasFlushed){var isAac=isLikelyAacData(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.resetCaptions=function(){if(this.transmuxPipeline_.captionStream){this.transmuxPipeline_.captionStream.reset()}}};_Transmuxer.prototype=new stream;var transmuxer={Transmuxer:_Transmuxer,VideoSegmentStream:_VideoSegmentStream,AudioSegmentStream:_AudioSegmentStream,AUDIO_PROPERTIES:AUDIO_PROPERTIES,VIDEO_PROPERTIES:VIDEO_PROPERTIES};var mp4={generator:mp4Generator,Transmuxer:transmuxer.Transmuxer,AudioSegmentStream:transmuxer.AudioSegmentStream,VideoSegmentStream:transmuxer.VideoSegmentStream};var classCallCheck$$1=function classCallCheck$$1(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var createClass$$1=function(){function defineProperties(target,props){for(var i=0;i1){var name=pair[0].replace(/"/g,"").trim();var value=pair[1].replace(/"/g,"").trim();object.parameters[name]=value}});return object};var translateLegacyCodecs=function translateLegacyCodecs(codecs){return codecs.map(function(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 makeWrappedSourceBuffer=function makeWrappedSourceBuffer(mediaSource,mimeType){var sourceBuffer=mediaSource.addSourceBuffer(mimeType);var wrapper=Object.create(null);wrapper.updating=false;wrapper.realBuffer_=sourceBuffer;var _loop=function _loop(key){if(typeof sourceBuffer[key]==="function"){wrapper[key]=function(){return sourceBuffer[key].apply(sourceBuffer,arguments)}}else if(typeof wrapper[key]==="undefined"){Object.defineProperty(wrapper,key,{get:function get$$1(){return sourceBuffer[key]},set:function set$$1(v){return sourceBuffer[key]=v}})}};for(var key in sourceBuffer){_loop(key)}return wrapper};var gopsSafeToAlignWith=function gopsSafeToAlignWith(buffer,player,mapping){if(!player||!buffer.length){return[]}var currentTimePts=Math.ceil((player.currentTime()-mapping+3)*9e4);var i=void 0;for(i=0;icurrentTimePts){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=start){break}}return buffer.slice(0,i).concat(gops)};var removeGopBuffer=function removeGopBuffer(buffer,start,end,mapping){var startPts=Math.ceil((start-mapping)*9e4);var endPts=Math.ceil((end-mapping)*9e4);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 VirtualSourceBuffer=function(_videojs$EventTarget){inherits(VirtualSourceBuffer,_videojs$EventTarget);function VirtualSourceBuffer(mediaSource,codecs){classCallCheck(this,VirtualSourceBuffer);var _this7=possibleConstructorReturn(this,_videojs$EventTarget.call(this,videojs$1.EventTarget));_this7.timestampOffset_=0;_this7.pendingBuffers_=[];_this7.bufferUpdating_=false;_this7.mediaSource_=mediaSource;_this7.codecs_=codecs;_this7.audioCodec_=null;_this7.videoCodec_=null;_this7.audioDisabled_=false;_this7.appendAudioInitSegment_=true;_this7.gopBuffer_=[];_this7.timeMapping_=0;_this7.safeAppend_=videojs$1.browser.IE_VERSION>=11;var options={remux:false,alignGopsAtEnd:_this7.safeAppend_};_this7.codecs_.forEach(function(codec){if(isAudioCodec(codec)){_this7.audioCodec_=codec}else if(isVideoCodec(codec)){_this7.videoCodec_=codec}});_this7.transmuxer_=new TransmuxWorker;_this7.transmuxer_.postMessage({action:"init",options:options});_this7.transmuxer_.onmessage=function(event){if(event.data.action==="data"){return _this7.data_(event)}if(event.data.action==="done"){return _this7.done_(event)}if(event.data.action==="gopInfo"){return _this7.appendGopInfo_(event)}};Object.defineProperty(_this7,"timestampOffset",{get:function get$$1(){return this.timestampOffset_},set:function set$$1(val){if(typeof val==="number"&&val>=0){this.timestampOffset_=val;this.appendAudioInitSegment_=true;this.gopBuffer_.length=0;this.timeMapping_=0;this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:val})}}});Object.defineProperty(_this7,"appendWindowStart",{get:function get$$1(){return(this.videoBuffer_||this.audioBuffer_).appendWindowStart},set:function set$$1(start){if(this.videoBuffer_){this.videoBuffer_.appendWindowStart=start}if(this.audioBuffer_){this.audioBuffer_.appendWindowStart=start}}});Object.defineProperty(_this7,"updating",{get:function get$$1(){return!!(this.bufferUpdating_||!this.audioDisabled_&&this.audioBuffer_&&this.audioBuffer_.updating||this.videoBuffer_&&this.videoBuffer_.updating)}});Object.defineProperty(_this7,"buffered",{get:function get$$1(){var start=null;var end=null;var arity=0;var extents=[];var ranges=[];if(!this.videoBuffer_&&!this.audioBuffer_){return videojs$1.createTimeRange()}if(!this.videoBuffer_){return this.audioBuffer_.buffered}if(!this.audioBuffer_){return this.videoBuffer_.buffered}if(this.audioDisabled_){return this.videoBuffer_.buffered}if(this.videoBuffer_.buffered.length===0&&this.audioBuffer_.buffered.length===0){return videojs$1.createTimeRange()}var videoBuffered=this.videoBuffer_.buffered;var audioBuffered=this.audioBuffer_.buffered;var count=videoBuffered.length;while(count--){extents.push({time:videoBuffered.start(count),type:"start"});extents.push({time:videoBuffered.end(count),type:"end"})}count=audioBuffered.length;while(count--){extents.push({time:audioBuffered.start(count),type:"start"});extents.push({time:audioBuffered.end(count),type:"end"})}extents.sort(function(a,b){return a.time-b.time});for(count=0;countthis.nativeMediaSource_.duration||isNaN(this.nativeMediaSource_.duration)){this.nativeMediaSource_.duration=end}};HtmlMediaSource.prototype.addSourceBuffer=function addSourceBuffer(type){var buffer=void 0;var parsedType=parseContentType(type);if(/^(video|audio)\/mp2t$/i.test(parsedType.type)){var codecs=[];if(parsedType.parameters&&parsedType.parameters.codecs){codecs=parsedType.parameters.codecs.split(",");codecs=translateLegacyCodecs(codecs);codecs=codecs.filter(function(codec){return isAudioCodec(codec)||isVideoCodec(codec)})}if(codecs.length===0){codecs=["avc1.4d400d","mp4a.40.2"]}buffer=new VirtualSourceBuffer(this,codecs);if(this.sourceBuffers.length!==0){this.sourceBuffers[0].createRealSourceBuffers_();buffer.createRealSourceBuffers_();this.sourceBuffers[0].audioDisabled_=true}}else{buffer=this.nativeMediaSource_.addSourceBuffer(type)}this.sourceBuffers.push(buffer);return buffer};return HtmlMediaSource}(videojs$1.EventTarget);var urlCount=0;videojs$1.mediaSources={};var open=function open(msObjectURL,swfId){var mediaSource=videojs$1.mediaSources[msObjectURL];if(mediaSource){mediaSource.trigger({type:"sourceopen",swfId:swfId})}else{throw new Error("Media Source not found (Video.js)")}};var supportsNativeMediaSources=function supportsNativeMediaSources(){return!!window_1.MediaSource&&!!window_1.MediaSource.isTypeSupported&&window_1.MediaSource.isTypeSupported('video/mp4;codecs="avc1.4d400d,mp4a.40.2"')};var MediaSource=function MediaSource(){this.MediaSource={open:open,supportsNativeMediaSources:supportsNativeMediaSources};if(supportsNativeMediaSources()){return new HtmlMediaSource}throw new Error("Cannot use create a virtual MediaSource for this video")};MediaSource.open=open;MediaSource.supportsNativeMediaSources=supportsNativeMediaSources;var URL$1={createObjectURL:function createObjectURL(object){var objectUrlPrefix="blob:vjs-media-source/";var url=void 0;if(object instanceof HtmlMediaSource){url=window_1.URL.createObjectURL(object.nativeMediaSource_);object.url_=url;return url}if(!(object instanceof HtmlMediaSource)){url=window_1.URL.createObjectURL(object);object.url_=url;return url}url=objectUrlPrefix+urlCount;urlCount++;videojs$1.mediaSources[url]=object;return url}};videojs$1.MediaSource=MediaSource;videojs$1.URL=URL$1;var EventTarget$1$1=videojs$1.EventTarget,mergeOptions$2=videojs$1.mergeOptions;var updateMaster$1=function updateMaster$1(oldMaster,newMaster){var update=mergeOptions$2(oldMaster,{duration:newMaster.duration,minimumUpdatePeriod:newMaster.minimumUpdatePeriod});for(var i=0;i")}return function(){}};function noop$1(){}var SourceUpdater=function(){function SourceUpdater(mediaSource,mimeType,type,sourceBufferEmitter){classCallCheck(this,SourceUpdater);this.callbacks_=[];this.pendingCallback_=null;this.timestampOffset_=0;this.mediaSource=mediaSource;this.processedAppend_=false;this.type_=type;this.mimeType_=mimeType;this.logger_=logger("SourceUpdater["+type+"]["+mimeType+"]");if(mediaSource.readyState==="closed"){mediaSource.addEventListener("sourceopen",this.createSourceBuffer_.bind(this,mimeType,sourceBufferEmitter))}else{this.createSourceBuffer_(mimeType,sourceBufferEmitter)}}SourceUpdater.prototype.createSourceBuffer_=function createSourceBuffer_(mimeType,sourceBufferEmitter){var _this16=this;this.sourceBuffer_=this.mediaSource.addSourceBuffer(mimeType);this.logger_("created SourceBuffer");if(sourceBufferEmitter){sourceBufferEmitter.trigger("sourcebufferadded");if(this.mediaSource.sourceBuffers.length<2){sourceBufferEmitter.on("sourcebufferadded",function(){_this16.start_()});return}}this.start_()};SourceUpdater.prototype.start_=function start_(){var _this17=this;this.started_=true;this.onUpdateendCallback_=function(){var pendingCallback=_this17.pendingCallback_;_this17.pendingCallback_=null;_this17.logger_("buffered ["+printableRange(_this17.buffered())+"]");if(pendingCallback){pendingCallback()}_this17.runCallback_()};this.sourceBuffer_.addEventListener("updateend",this.onUpdateendCallback_);this.runCallback_()};SourceUpdater.prototype.abort=function abort(done){var _this18=this;if(this.processedAppend_){this.queueCallback_(function(){_this18.sourceBuffer_.abort()},done)}};SourceUpdater.prototype.appendBuffer=function appendBuffer(bytes,done){var _this19=this;this.processedAppend_=true;this.queueCallback_(function(){_this19.sourceBuffer_.appendBuffer(bytes)},done)};SourceUpdater.prototype.buffered=function buffered(){if(!this.sourceBuffer_){return videojs$1.createTimeRanges()}return this.sourceBuffer_.buffered};SourceUpdater.prototype.remove=function remove(start,end){var _this20=this;if(this.processedAppend_){this.queueCallback_(function(){_this20.logger_("remove ["+start+" => "+end+"]");_this20.sourceBuffer_.remove(start,end)},noop$1)}};SourceUpdater.prototype.updating=function updating(){return!this.sourceBuffer_||this.sourceBuffer_.updating||this.pendingCallback_};SourceUpdater.prototype.timestampOffset=function timestampOffset(offset){var _this21=this;if(typeof offset!=="undefined"){this.queueCallback_(function(){_this21.sourceBuffer_.timestampOffset=offset});this.timestampOffset_=offset}return this.timestampOffset_};SourceUpdater.prototype.queueCallback_=function queueCallback_(callback,done){this.callbacks_.push([callback.bind(this),done]);this.runCallback_()};SourceUpdater.prototype.runCallback_=function runCallback_(){var callbacks=void 0;if(!this.updating()&&this.callbacks_.length&&this.started_){callbacks=this.callbacks_.shift();this.pendingCallback_=callbacks[1];callbacks[0]()}};SourceUpdater.prototype.dispose=function dispose(){this.sourceBuffer_.removeEventListener("updateend",this.onUpdateendCallback_);if(this.sourceBuffer_&&this.mediaSource.readyState==="open"){this.sourceBuffer_.abort()}};return SourceUpdater}();var Config={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,GOAL_BUFFER_LENGTH_RATE:1,BANDWIDTH_VARIANCE:1.2,BUFFER_LOW_WATER_LINE:0,MAX_BUFFER_LOW_WATER_LINE:30,BUFFER_LOW_WATER_LINE_RATE:1};var REQUEST_ERRORS={FAILURE:2,TIMEOUT:-101,ABORTED:-102};var byterangeStr=function byterangeStr(byterange){var byterangeStart=void 0;var byterangeEnd=void 0;byterangeEnd=byterange.offset+byterange.length-1;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 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*1e3);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(segment,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);return finishProcessingFn(null,segment)}};var handleSegmentResponse=function handleSegmentResponse(segment,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.stats=getRequestStats(request);if(segment.key){segment.encryptedBytes=new Uint8Array(request.response)}else{segment.bytes=new Uint8Array(request.response)}return finishProcessingFn(null,segment)}};var decryptSegment=function decryptSegment(decrypter,segment,doneFn){var decryptionHandler=function decryptionHandler(event){if(event.data.source===segment.requestId){decrypter.removeEventListener("message",decryptionHandler);var decrypted=event.data.decrypted;segment.bytes=new Uint8Array(decrypted.bytes,decrypted.byteOffset,decrypted.byteLength);return doneFn(null,segment)}};decrypter.addEventListener("message",decryptionHandler);decrypter.postMessage(createTransferableMessage({source:segment.requestId,encrypted:segment.encryptedBytes,key:segment.key.bytes,iv:segment.key.iv}),[segment.encryptedBytes.buffer,segment.key.bytes.buffer])};var getMostImportantError=function getMostImportantError(errors){return errors.reduce(function(prev,err){return err.code>prev.code?err:prev})};var waitForCompletion=function waitForCompletion(activeXhrs,decrypter,doneFn){var errors=[];var count=0;return function(error,segment){if(error){abortAll(activeXhrs);errors.push(error)}count+=1;if(count===activeXhrs.length){segment.endOfAllRequests=Date.now();if(errors.length>0){var worstError=getMostImportantError(errors);return doneFn(worstError,segment)}if(segment.encryptedBytes){return decryptSegment(decrypter,segment,doneFn)}return doneFn(null,segment)}}};var handleProgress=function handleProgress(segment,progressFn){return function(event){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(xhr,xhrOptions,decryptionWorker,segment,progressFn,doneFn){var activeXhrs=[];var finishProcessingFn=waitForCompletion(activeXhrs,decryptionWorker,doneFn);if(segment.key){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,finishProcessingFn);var initSegmentXhr=xhr(initSegmentOptions,initSegmentRequestCallback);activeXhrs.push(initSegmentXhr)}var segmentRequestOptions=videojs$1.mergeOptions(xhrOptions,{uri:segment.resolvedUri,responseType:"arraybuffer",headers:segmentXhrHeaders(segment)});var segmentRequestCallback=handleSegmentResponse(segment,finishProcessingFn);var segmentXhr=xhr(segmentRequestOptions,segmentRequestCallback);segmentXhr.addEventListener("progress",handleProgress(segment,progressFn));activeXhrs.push(segmentXhr);return function(){return abortAll(activeXhrs)}};var defaultCodecs={videoCodec:"avc1",videoObjectTypeIndicator:".4d400d",audioProfile:"2"};var parseCodecs=function parseCodecs(){var codecs=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";var result={codecCount:0};var parsed=void 0;result.codecCount=codecs.split(",").length;result.codecCount=result.codecCount||2;parsed=/(^|\s|,)+(avc[13])([^ ,]*)/i.exec(codecs);if(parsed){result.videoCodec=parsed[2];result.videoObjectTypeIndicator=parsed[3]}result.audioProfile=/(^|\s|,)+mp4a.[0-9A-Fa-f]+\.([0-9A-Fa-f]+)/i.exec(codecs);result.audioProfile=result.audioProfile&&result.audioProfile[2];return result};var mapLegacyAvcCodecs=function mapLegacyAvcCodecs(codecString){return codecString.replace(/avc1\.(\d+)\.(\d+)/i,function(match){return translateLegacyCodecs([match])[0]})};var makeMimeTypeString=function makeMimeTypeString(type,container,codecs){return type+"/"+container+'; codecs="'+codecs.filter(function(c){return!!c}).join(", ")+'"'};var getContainerType=function getContainerType(media){if(media.segments&&media.segments.length&&media.segments[0].map){return"mp4"}return"mp2t"};var getCodecs=function getCodecs(media){var mediaAttributes=media.attributes||{};if(mediaAttributes.CODECS){return parseCodecs(mediaAttributes.CODECS)}return defaultCodecs};var audioProfileFromDefault=function audioProfileFromDefault(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).audioProfile}}return null};var mimeTypesForPlaylist=function mimeTypesForPlaylist(master,media){var containerType=getContainerType(media);var codecInfo=getCodecs(media);var mediaAttributes=media.attributes||{};var isMuxed=true;var isMaat=false;if(!media){return[]}if(master.mediaGroups.AUDIO&&mediaAttributes.AUDIO){var audioGroup=master.mediaGroups.AUDIO[mediaAttributes.AUDIO];if(audioGroup){isMaat=true;isMuxed=false;for(var groupId in audioGroup){if(!audioGroup[groupId].uri&&!audioGroup[groupId].playlists){isMuxed=true;break}}}}if(isMaat&&!codecInfo.audioProfile){if(!isMuxed){codecInfo.audioProfile=audioProfileFromDefault(master,mediaAttributes.AUDIO)}if(!codecInfo.audioProfile){videojs$1.log.warn("Multiple audio tracks present but no audio codec string is specified. "+"Attempting to use the default audio codec (mp4a.40.2)");codecInfo.audioProfile=defaultCodecs.audioProfile}}var codecStrings={};if(codecInfo.videoCodec){codecStrings.video=""+codecInfo.videoCodec+codecInfo.videoObjectTypeIndicator}if(codecInfo.audioProfile){codecStrings.audio="mp4a.40."+codecInfo.audioProfile}var justAudio=makeMimeTypeString("audio",containerType,[codecStrings.audio]);var justVideo=makeMimeTypeString("video",containerType,[codecStrings.video]);var bothVideoAudio=makeMimeTypeString("video",containerType,[codecStrings.video,codecStrings.audio]);if(isMaat){if(!isMuxed&&codecStrings.video){return[justVideo,justAudio]}if(!isMuxed&&!codecStrings.video){return[justAudio,justAudio]}return[bothVideoAudio,justAudio]}if(!codecStrings.video){return[justAudio]}return[bothVideoAudio]};var safeGetComputedStyle=function safeGetComputedStyle(el,property){var result=void 0;if(!el){return""}result=window_1.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=void 0;var rightBandwidth=void 0;if(left.attributes.BANDWIDTH){leftBandwidth=left.attributes.BANDWIDTH}leftBandwidth=leftBandwidth||window_1.Number.MAX_VALUE;if(right.attributes.BANDWIDTH){rightBandwidth=right.attributes.BANDWIDTH}rightBandwidth=rightBandwidth||window_1.Number.MAX_VALUE;return leftBandwidth-rightBandwidth};var comparePlaylistResolution=function comparePlaylistResolution(left,right){var leftWidth=void 0;var rightWidth=void 0;if(left.attributes.RESOLUTION&&left.attributes.RESOLUTION.width){leftWidth=left.attributes.RESOLUTION.width}leftWidth=leftWidth||window_1.Number.MAX_VALUE;if(right.attributes.RESOLUTION&&right.attributes.RESOLUTION.width){rightWidth=right.attributes.RESOLUTION.width}rightWidth=rightWidth||window_1.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){var sortedPlaylistReps=master.playlists.map(function(playlist){var width=void 0;var height=void 0;var bandwidth=void 0;width=playlist.attributes.RESOLUTION&&playlist.attributes.RESOLUTION.width;height=playlist.attributes.RESOLUTION&&playlist.attributes.RESOLUTION.height;bandwidth=playlist.attributes.BANDWIDTH;bandwidth=bandwidth||window_1.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_VARIANCEplayerWidth||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];return chosenRep?chosenRep.playlist:null};var lastBandwidthSelector=function lastBandwidthSelector(){return simpleSelector(this.playlists.master,this.systemBandwidth,parseInt(safeGetComputedStyle(this.tech_.el(),"width"),10),parseInt(safeGetComputedStyle(this.tech_.el(),"height"),10))};var minRebufferMaxBandwidthSelector=function minRebufferMaxBandwidthSelector(settings){var master=settings.master,currentTime=settings.currentTime,bandwidth=settings.bandwidth,duration$$1=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$$1,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 playlists=this.playlists.master.playlists.filter(Playlist.isEnabled);stableSort(playlists,function(a,b){return comparePlaylistBandwidth(a,b)});var playlistsWithVideo=playlists.filter(function(playlist){return parseCodecs(playlist.attributes.CODECS).videoCodec});return playlistsWithVideo[0]||null};var CHECK_BUFFER_DELAY=500;var detectEndOfStream=function detectEndOfStream(playlist,mediaSource,segmentIndex){if(!playlist||!mediaSource){return false}var segments=playlist.segments;var appendedLastSegment=segmentIndex===segments.length;return playlist.endList&&mediaSource.readyState==="open"&&appendedLastSegment};var finite=function finite(num){return typeof num==="number"&&isFinite(num)};var illegalMediaSwitch=function illegalMediaSwitch(loaderType,startingMedia,newSegmentMedia){if(loaderType!=="main"||!startingMedia||!newSegmentMedia){return null}if(!newSegmentMedia.containsAudio&&!newSegmentMedia.containsVideo){return"Neither audio nor video found in segment."}if(startingMedia.containsVideo&&!newSegmentMedia.containsVideo){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.containsVideo&&newSegmentMedia.containsVideo){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$$1,currentTime,targetDuration){var removeToTime=void 0;if(seekable$$1.length&&seekable$$1.start(0)>0&&seekable$$1.start(0) "+end+"] in timeline ["+timeline+"]"].join(" ")};var SegmentLoader=function(_videojs$EventTarget3){inherits(SegmentLoader,_videojs$EventTarget3);function SegmentLoader(settings){classCallCheck(this,SegmentLoader);var _this22=possibleConstructorReturn(this,_videojs$EventTarget3.call(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")}_this22.bandwidth=settings.bandwidth;_this22.throughput={rate:0,count:0};_this22.roundTrip=NaN;_this22.resetStats_();_this22.mediaIndex=null;_this22.hasPlayed_=settings.hasPlayed;_this22.currentTime_=settings.currentTime;_this22.seekable_=settings.seekable;_this22.seeking_=settings.seeking;_this22.duration_=settings.duration;_this22.mediaSource_=settings.mediaSource;_this22.hls_=settings.hls;_this22.loaderType_=settings.loaderType;_this22.startingMedia_=void 0;_this22.segmentMetadataTrack_=settings.segmentMetadataTrack;_this22.goalBufferLength_=settings.goalBufferLength;_this22.sourceType_=settings.sourceType;_this22.state_="INIT";_this22.checkBufferTimeout_=null;_this22.error_=void 0;_this22.currentTimeline_=-1;_this22.pendingSegment_=null;_this22.mimeType_=null;_this22.sourceUpdater_=null;_this22.xhrOptions_=null;_this22.activeInitSegmentId_=null;_this22.initSegments_={};_this22.decrypter_=settings.decrypter;_this22.syncController_=settings.syncController;_this22.syncPoint_={segmentIndex:0,time:0};_this22.syncController_.on("syncinfoupdate",function(){return _this22.trigger("syncinfoupdate")});_this22.mediaSource_.addEventListener("sourceopen",function(){return _this22.ended_=false});_this22.fetchAtBuffer_=false;_this22.logger_=logger("SegmentLoader["+_this22.loaderType_+"]");Object.defineProperty(_this22,"state",{get:function get$$1(){return this.state_},set:function set$$1(newState){if(newState!==this.state_){this.logger_(this.state_+" -> "+newState);this.state_=newState}}});return _this22}SegmentLoader.prototype.resetStats_=function resetStats_(){this.mediaBytesTransferred=0;this.mediaRequests=0;this.mediaRequestsAborted=0;this.mediaRequestsTimedout=0;this.mediaRequestsErrored=0;this.mediaTransferDuration=0;this.mediaSecondsLoaded=0};SegmentLoader.prototype.dispose=function dispose(){this.state="DISPOSED";this.pause();this.abort_();if(this.sourceUpdater_){this.sourceUpdater_.dispose()}this.resetStats_()};SegmentLoader.prototype.abort=function abort(){if(this.state!=="WAITING"){if(this.pendingSegment_){this.pendingSegment_=null}return}this.abort_();this.state="READY";if(!this.paused()){this.monitorBuffer_()}};SegmentLoader.prototype.abort_=function abort_(){if(this.pendingSegment_){this.pendingSegment_.abortRequests()}this.pendingSegment_=null};SegmentLoader.prototype.error=function error(_error){if(typeof _error!=="undefined"){this.error_=_error}this.pendingSegment_=null;return this.error_};SegmentLoader.prototype.endOfStream=function endOfStream(){this.ended_=true;this.pause();this.trigger("ended")};SegmentLoader.prototype.buffered_=function buffered_(){if(!this.sourceUpdater_){return videojs$1.createTimeRanges()}return this.sourceUpdater_.buffered()};SegmentLoader.prototype.initSegment=function initSegment(map){var set$$1=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!map){return null}var id=initSegmentId(map);var storedMap=this.initSegments_[id];if(set$$1&&!storedMap&&map.bytes){this.initSegments_[id]=storedMap={resolvedUri:map.resolvedUri,byterange:map.byterange,bytes:map.bytes}}return storedMap||map};SegmentLoader.prototype.couldBeginLoading_=function couldBeginLoading_(){return this.playlist_&&(this.sourceUpdater_||this.mimeType_&&this.state==="INIT")&&!this.paused()};SegmentLoader.prototype.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"};SegmentLoader.prototype.init_=function init_(){this.state="READY";this.sourceUpdater_=new SourceUpdater(this.mediaSource_,this.mimeType_,this.loaderType_,this.sourceBufferEmitter_);this.resetEverything();return this.monitorBuffer_()};SegmentLoader.prototype.playlist=function playlist(newPlaylist){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(!newPlaylist){return}var oldPlaylist=this.playlist_;var segmentInfo=this.pendingSegment_;this.playlist_=newPlaylist;this.xhrOptions_=options;if(!this.hasPlayed_()){newPlaylist.syncInfo={mediaSequence:newPlaylist.mediaSequence,time:0}}var oldId=oldPlaylist?oldPlaylist.id:null;this.logger_("playlist update ["+oldId+" => "+newPlaylist.id+"]");this.trigger("syncinfoupdate");if(this.state==="INIT"&&this.couldBeginLoading_()){return this.init_()}if(!oldPlaylist||oldPlaylist.uri!==newPlaylist.uri){if(this.mediaIndex!==null){this.resyncLoader()}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)};SegmentLoader.prototype.pause=function pause(){if(this.checkBufferTimeout_){window_1.clearTimeout(this.checkBufferTimeout_);this.checkBufferTimeout_=null}};SegmentLoader.prototype.paused=function paused(){return this.checkBufferTimeout_===null};SegmentLoader.prototype.mimeType=function mimeType(_mimeType,sourceBufferEmitter){if(this.mimeType_){return}this.mimeType_=_mimeType;this.sourceBufferEmitter_=sourceBufferEmitter;if(this.state==="INIT"&&this.couldBeginLoading_()){this.init_()}};SegmentLoader.prototype.resetEverything=function resetEverything(){this.ended_=false;this.resetLoader();this.remove(0,this.duration_());this.trigger("reseteverything")};SegmentLoader.prototype.resetLoader=function resetLoader(){this.fetchAtBuffer_=false;this.resyncLoader()};SegmentLoader.prototype.resyncLoader=function resyncLoader(){this.mediaIndex=null;this.syncPoint_=null;this.abort()};SegmentLoader.prototype.remove=function remove(start,end){if(this.sourceUpdater_){this.sourceUpdater_.remove(start,end)}removeCuesFromTrack(start,end,this.segmentMetadataTrack_)};SegmentLoader.prototype.monitorBuffer_=function monitorBuffer_(){if(this.checkBufferTimeout_){window_1.clearTimeout(this.checkBufferTimeout_)}this.checkBufferTimeout_=window_1.setTimeout(this.monitorBufferTick_.bind(this),1)};SegmentLoader.prototype.monitorBufferTick_=function monitorBufferTick_(){if(this.state==="READY"){this.fillBuffer_()}if(this.checkBufferTimeout_){window_1.clearTimeout(this.checkBufferTimeout_)}this.checkBufferTimeout_=window_1.setTimeout(this.monitorBufferTick_.bind(this),CHECK_BUFFER_DELAY)};SegmentLoader.prototype.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 segmentInfo=this.checkBuffer_(this.buffered_(),this.playlist_,this.mediaIndex,this.hasPlayed_(),this.currentTime_(),this.syncPoint_);if(!segmentInfo){return}var isEndOfStream=detectEndOfStream(this.playlist_,this.mediaSource_,segmentInfo.mediaIndex);if(isEndOfStream){this.endOfStream();return}if(segmentInfo.mediaIndex===this.playlist_.segments.length-1&&this.mediaSource_.readyState==="ended"&&!this.seeking_()){return}if(segmentInfo.timeline!==this.currentTimeline_||segmentInfo.startOfSegment!==null&&segmentInfo.startOfSegment=this.goalBufferLength_()){return null}if(!hasPlayed&&bufferedTime>=1){return null}if(syncPoint===null){mediaIndex=this.getSyncSegmentCandidate_(playlist);return this.generateSegmentInfo_(playlist,mediaIndex,null,true)}if(mediaIndex!==null){var segment=playlist.segments[mediaIndex];if(segment&&segment.end){startOfSegment=segment.end}else{startOfSegment=lastBufferedEnd}return this.generateSegmentInfo_(playlist,mediaIndex+1,startOfSegment,false)}if(this.fetchAtBuffer_){var mediaSourceInfo=Playlist.getMediaInfoForTime(playlist,lastBufferedEnd,syncPoint.segmentIndex,syncPoint.time);mediaIndex=mediaSourceInfo.mediaIndex;startOfSegment=mediaSourceInfo.startTime}else{var _mediaSourceInfo=Playlist.getMediaInfoForTime(playlist,currentTime,syncPoint.segmentIndex,syncPoint.time);mediaIndex=_mediaSourceInfo.mediaIndex;startOfSegment=_mediaSourceInfo.startTime}return this.generateSegmentInfo_(playlist,mediaIndex,startOfSegment,false)};SegmentLoader.prototype.getSyncSegmentCandidate_=function getSyncSegmentCandidate_(playlist){var _this23=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===_this23.currentTimeline_});if(segmentIndexArray.length){return segmentIndexArray[Math.min(segmentIndexArray.length-1,1)].segmentIndex}return Math.max(playlist.segments.length-1,0)};SegmentLoader.prototype.generateSegmentInfo_=function generateSegmentInfo_(playlist,mediaIndex,startOfSegment,isSyncRequest){if(mediaIndex<0||mediaIndex>=playlist.segments.length){return null}var segment=playlist.segments[mediaIndex];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}};SegmentLoader.prototype.abortRequestEarly_=function abortRequestEarly_(stats){if(this.hls_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH){return false}if(Date.now()-(stats.firstBytesReceivedAt||Date.now())<1e3){return false}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.hls_.tech_.playbackRate())-1;if(requestTimeRemaining<=timeUntilRebuffer$$1){return false}var switchCandidate=minRebufferMaxBandwidthSelector({master:this.hls_.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=.5;if(timeUntilRebuffer$$1<=TIME_FUDGE_FACTOR){minimumTimeSaving=1}if(!switchCandidate.playlist||switchCandidate.playlist.uri===this.playlist_.uri||timeSavedBySwitching0){this.remove(0,removeToTime)}};SegmentLoader.prototype.createSimplifiedSegmentObj_=function createSimplifiedSegmentObj_(segmentInfo){var segment=segmentInfo.segment;var simpleSegment={resolvedUri:segment.resolvedUri,byterange:segment.byterange,requestId:segmentInfo.requestId};if(segment.key){var iv=segment.key.iv||new Uint32Array([0,0,0,segmentInfo.mediaIndex+segmentInfo.playlist.mediaSequence]);simpleSegment.key={resolvedUri:segment.key.resolvedUri,iv:iv}}if(segment.map){simpleSegment.map=this.initSegment(segment.map)}return simpleSegment};SegmentLoader.prototype.segmentRequestFinished_=function segmentRequestFinished_(error,simpleSegment){this.mediaRequests+=1;if(simpleSegment.stats){this.mediaBytesTransferred+=simpleSegment.stats.bytesReceived;this.mediaTransferDuration+=simpleSegment.stats.roundTripTime}if(!this.pendingSegment_){this.mediaRequestsAborted+=1;return}if(simpleSegment.requestId!==this.pendingSegment_.requestId){return}if(error){this.pendingSegment_=null;this.state="READY";if(error.code===REQUEST_ERRORS.ABORTED){this.mediaRequestsAborted+=1;return}this.pause();if(error.code===REQUEST_ERRORS.TIMEOUT){this.mediaRequestsTimedout+=1;this.bandwidth=1;this.roundTrip=NaN;this.trigger("bandwidthupdate");return}this.mediaRequestsErrored+=1;this.error(error);this.trigger("error");return}this.bandwidth=simpleSegment.stats.bandwidth;this.roundTrip=simpleSegment.stats.roundTripTime;if(simpleSegment.map){simpleSegment.map=this.initSegment(simpleSegment.map,true)}this.processSegmentResponse_(simpleSegment)};SegmentLoader.prototype.processSegmentResponse_=function processSegmentResponse_(simpleSegment){var segmentInfo=this.pendingSegment_;segmentInfo.bytes=simpleSegment.bytes;if(simpleSegment.map){segmentInfo.segment.map.bytes=simpleSegment.map.bytes}segmentInfo.endOfAllRequests=simpleSegment.endOfAllRequests;this.handleSegment_()};SegmentLoader.prototype.handleSegment_=function handleSegment_(){var _this24=this;if(!this.pendingSegment_){this.state="READY";return}var segmentInfo=this.pendingSegment_;var segment=segmentInfo.segment;var timingInfo=this.syncController_.probeSegmentInfo(segmentInfo);if(typeof this.startingMedia_==="undefined"&&timingInfo&&(timingInfo.containsAudio||timingInfo.containsVideo)){this.startingMedia_={containsAudio:timingInfo.containsAudio,containsVideo:timingInfo.containsVideo}}var illegalMediaSwitchError=illegalMediaSwitch(this.loaderType_,this.startingMedia_,timingInfo);if(illegalMediaSwitchError){this.error({message:illegalMediaSwitchError,blacklistDuration:Infinity});this.trigger("error");return}if(segmentInfo.isSyncRequest){this.trigger("syncinfoupdate");this.pendingSegment_=null;this.state="READY";return}if(segmentInfo.timestampOffset!==null&&segmentInfo.timestampOffset!==this.sourceUpdater_.timestampOffset()){this.sourceUpdater_.timestampOffset(segmentInfo.timestampOffset);this.trigger("timestampoffset")}var timelineMapping=this.syncController_.mappingForTimeline(segmentInfo.timeline);if(timelineMapping!==null){this.trigger({type:"segmenttimemapping",mapping:timelineMapping})}this.state="APPENDING";if(segment.map){var initId=initSegmentId(segment.map);if(!this.activeInitSegmentId_||this.activeInitSegmentId_!==initId){var initSegment=this.initSegment(segment.map);this.sourceUpdater_.appendBuffer(initSegment.bytes,function(){_this24.activeInitSegmentId_=initId})}}segmentInfo.byteLength=segmentInfo.bytes.byteLength;if(typeof segment.start==="number"&&typeof segment.end==="number"){this.mediaSecondsLoaded+=segment.end-segment.start}else{this.mediaSecondsLoaded+=segment.duration}this.logger_(segmentInfoString(segmentInfo));this.sourceUpdater_.appendBuffer(segmentInfo.bytes,this.handleUpdateEnd_.bind(this))};SegmentLoader.prototype.handleUpdateEnd_=function handleUpdateEnd_(){if(!this.pendingSegment_){this.state="READY";if(!this.paused()){this.monitorBuffer_()}return}var segmentInfo=this.pendingSegment_;var segment=segmentInfo.segment;var isWalkingForward=this.mediaIndex!==null;this.pendingSegment_=null;this.recordThroughput_(segmentInfo);this.addSegmentMetadataCue_(segmentInfo);this.state="READY";this.mediaIndex=segmentInfo.mediaIndex;this.fetchAtBuffer_=true;this.currentTimeline_=segmentInfo.timeline;this.trigger("syncinfoupdate");if(segment.end&&this.currentTime_()-segment.end>segmentInfo.playlist.targetDuration*3){this.resetEverything();return}if(isWalkingForward){this.trigger("bandwidthupdate")}this.trigger("progress");var isEndOfStream=detectEndOfStream(segmentInfo.playlist,this.mediaSource_,segmentInfo.mediaIndex+1);if(isEndOfStream){this.endOfStream()}if(!this.paused()){this.monitorBuffer_()}};SegmentLoader.prototype.recordThroughput_=function recordThroughput_(segmentInfo){var rate=this.throughput.rate;var segmentProcessingTime=Date.now()-segmentInfo.endOfAllRequests+1;var segmentProcessingThroughput=Math.floor(segmentInfo.byteLength/segmentProcessingTime*8*1e3);this.throughput.rate+=(segmentProcessingThroughput-rate)/++this.throughput.count};SegmentLoader.prototype.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.WebKitDataCue||window_1.VTTCue;var value={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.uri,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);var VTT_LINE_TERMINATORS=new Uint8Array("\n\n".split("").map(function(char){return char.charCodeAt(0)}));var uintToString=function uintToString(uintArray){return String.fromCharCode.apply(null,uintArray)};var VTTSegmentLoader=function(_SegmentLoader){inherits(VTTSegmentLoader,_SegmentLoader);function VTTSegmentLoader(settings){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};classCallCheck(this,VTTSegmentLoader);var _this25=possibleConstructorReturn(this,_SegmentLoader.call(this,settings,options));_this25.mediaSource_=null;_this25.subtitlesTrack_=null;return _this25}VTTSegmentLoader.prototype.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]])};VTTSegmentLoader.prototype.initSegment=function initSegment(map){var set$$1=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!map){return null}var id=initSegmentId(map);var storedMap=this.initSegments_[id];if(set$$1&&!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};VTTSegmentLoader.prototype.couldBeginLoading_=function couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()};VTTSegmentLoader.prototype.init_=function init_(){this.state="READY";this.resetEverything();return this.monitorBuffer_()};VTTSegmentLoader.prototype.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_};VTTSegmentLoader.prototype.remove=function remove(start,end){removeCuesFromTrack(start,end,this.subtitlesTrack_)};VTTSegmentLoader.prototype.fillBuffer_=function fillBuffer_(){var _this26=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(){_this26.state="READY";if(!_this26.paused()){_this26.monitorBuffer_()}};this.syncController_.one("timestampoffset",checkTimestampOffset);this.state="WAITING_ON_TIMELINE";return}this.loadSegment_(segmentInfo)};VTTSegmentLoader.prototype.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};VTTSegmentLoader.prototype.handleSegment_=function handleSegment_(){var _this27=this;if(!this.pendingSegment_||!this.subtitlesTrack_){this.state="READY";return}this.state="APPENDING";var segmentInfo=this.pendingSegment_;var segment=segmentInfo.segment;if(typeof window_1.WebVTT!=="function"&&this.subtitlesTrack_&&this.subtitlesTrack_.tech_){var loadHandler=function loadHandler(){_this27.handleSegment_()};this.state="WAITING_ON_VTTJS";this.subtitlesTrack_.tech_.one("vttjsloaded",loadHandler);this.subtitlesTrack_.tech_.one("vttjserror",function(){_this27.subtitlesTrack_.tech_.off("vttjsloaded",loadHandler);_this27.error({message:"Error loading vtt.js"});_this27.state="READY";_this27.pause();_this27.trigger("error")});return}segment.requested=true;try{this.parseVTTCues_(segmentInfo)}catch(e){this.error({message:e.message});this.state="READY";this.pause();return this.trigger("error")}this.updateTimeMapping_(segmentInfo,this.syncController_.timelines[segmentInfo.timeline],this.playlist_);if(segmentInfo.isSyncRequest){this.trigger("syncinfoupdate");this.pendingSegment_=null;this.state="READY";return}segmentInfo.byteLength=segmentInfo.bytes.byteLength;this.mediaSecondsLoaded+=segment.duration;if(segmentInfo.cues.length){this.remove(segmentInfo.cues[0].endTime,segmentInfo.cues[segmentInfo.cues.length-1].endTime)}segmentInfo.cues.forEach(function(cue){_this27.subtitlesTrack_.addCue(cue)});this.handleUpdateEnd_()};VTTSegmentLoader.prototype.parseVTTCues_=function parseVTTCues_(segmentInfo){var decoder=void 0;var decodeBytesToString=false;if(typeof window_1.TextDecoder==="function"){decoder=new window_1.TextDecoder("utf8")}else{decoder=window_1.WebVTT.StringDecoder();decodeBytesToString=true}var parser=new window_1.WebVTT.Parser(window_1,window_1.vttjs,decoder);segmentInfo.cues=[];segmentInfo.timestampmap={MPEGTS:0,LOCAL:0};parser.oncue=segmentInfo.cues.push.bind(segmentInfo.cues);parser.ontimestampmap=function(map){return 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=uintToString(mapData)}parser.parse(mapData)}var segmentData=segmentInfo.bytes;if(decodeBytesToString){segmentData=uintToString(segmentData)}parser.parse(segmentData);parser.flush()};VTTSegmentLoader.prototype.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/9e4-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=cue.adStartTime&&mediaTime<=cue.adEndTime){return cue}}return null};var updateAdCues=function updateAdCues(media,track){var offset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;if(!media.segments){return}var mediaTime=offset;var cue=void 0;for(var i=0;i=distance){lastDistance=distance;syncPoint={time:segment.start,segmentIndex:i}}}}return syncPoint}},{name:"Discontinuity",run:function run(syncController,playlist,duration$$1,currentTimeline,currentTime){var syncPoint=null;currentTime=currentTime||0;if(playlist.discontinuityStarts&&playlist.discontinuityStarts.length){var lastDistance=null;for(var i=0;i=distance){lastDistance=distance;syncPoint={time:discontinuitySync.time,segmentIndex:segmentIndex}}}}}return syncPoint}},{name:"Playlist",run:function run(syncController,playlist,duration$$1,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$EventTarget4){inherits(SyncController,_videojs$EventTarget4);function SyncController(){classCallCheck(this,SyncController);var _this28=possibleConstructorReturn(this,_videojs$EventTarget4.call(this));_this28.inspectCache_=undefined;_this28.timelines=[];_this28.discontinuities=[];_this28.datetimeToDisplayTime=null;_this28.logger_=logger("SyncController");return _this28}SyncController.prototype.getSyncPoint=function getSyncPoint(playlist,duration$$1,currentTimeline,currentTime){var syncPoints=this.runStrategies_(playlist,duration$$1,currentTimeline,currentTime);if(!syncPoints.length){return null}return this.selectSyncPoint_(syncPoints,{key:"time",value:currentTime})};SyncController.prototype.getExpiredTime=function getExpiredTime(playlist,duration$$1){if(!playlist||!playlist.segments){return null}var syncPoints=this.runStrategies_(playlist,duration$$1,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))};SyncController.prototype.runStrategies_=function runStrategies_(playlist,duration$$1,currentTimeline,currentTime){var syncPoints=[];for(var i=0;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}}};SyncController.prototype.setDateTimeMapping=function setDateTimeMapping(playlist){if(!this.datetimeToDisplayTime&&playlist.segments&&playlist.segments.length&&playlist.segments[0].dateTimeObject){var playlistTimestamp=playlist.segments[0].dateTimeObject.getTime()/1e3;this.datetimeToDisplayTime=-playlistTimestamp}};SyncController.prototype.reset=function reset(){this.inspectCache_=undefined};SyncController.prototype.probeSegmentInfo=function probeSegmentInfo(segmentInfo){var segment=segmentInfo.segment;var playlist=segmentInfo.playlist;var timingInfo=void 0;if(segment.map){timingInfo=this.probeMp4Segment_(segmentInfo)}else{timingInfo=this.probeTsSegment_(segmentInfo)}if(timingInfo){if(this.calculateSegmentTimeMapping_(segmentInfo,timingInfo)){this.saveDiscontinuitySyncInfo_(segmentInfo);if(!playlist.syncInfo){playlist.syncInfo={mediaSequence:playlist.mediaSequence+segmentInfo.mediaIndex,time:segment.start}}}}return timingInfo};SyncController.prototype.probeMp4Segment_=function probeMp4Segment_(segmentInfo){var segment=segmentInfo.segment;var timescales=probe.timescale(segment.map.bytes);var startTime=probe.startTime(timescales,segmentInfo.bytes);if(segmentInfo.timestampOffset!==null){segmentInfo.timestampOffset-=startTime}return{start:startTime,end:startTime+segment.duration}};SyncController.prototype.probeTsSegment_=function probeTsSegment_(segmentInfo){var timeInfo=tsprobe(segmentInfo.bytes,this.inspectCache_);var segmentStartTime=void 0;var segmentEndTime=void 0;if(!timeInfo){return null}if(timeInfo.video&&timeInfo.video.length===2){this.inspectCache_=timeInfo.video[1].dts;segmentStartTime=timeInfo.video[0].dtsTime;segmentEndTime=timeInfo.video[1].dtsTime}else if(timeInfo.audio&&timeInfo.audio.length===2){this.inspectCache_=timeInfo.audio[1].dts;segmentStartTime=timeInfo.audio[0].dtsTime;segmentEndTime=timeInfo.audio[1].dtsTime}return{start:segmentStartTime,end:segmentEndTime,containsVideo:timeInfo.video&&timeInfo.video.length===2,containsAudio:timeInfo.audio&&timeInfo.audio.length===2}};SyncController.prototype.timestampOffsetForTimeline=function timestampOffsetForTimeline(timeline){if(typeof this.timelines[timeline]==="undefined"){return null}return this.timelines[timeline].time};SyncController.prototype.mappingForTimeline=function mappingForTimeline(timeline){if(typeof this.timelines[timeline]==="undefined"){return null}return this.timelines[timeline].mapping};SyncController.prototype.calculateSegmentTimeMapping_=function calculateSegmentTimeMapping_(segmentInfo,timingInfo){var segment=segmentInfo.segment;var mappingObj=this.timelines[segmentInfo.timeline];if(segmentInfo.timestampOffset!==null){mappingObj={time:segmentInfo.startOfSegment,mapping:segmentInfo.startOfSegment-timingInfo.start};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};SyncController.prototype.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;iaccuracy){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}}}}};return SyncController}(videojs$1.EventTarget);var Decrypter$1=new shimWorker("./decrypter-worker.worker.js",function(window,document$$1){var self=this;var decrypterWorker=function(){var commonjsGlobal=typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};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$$1=win;function unpad(padded){return padded.subarray(0,padded.byteLength-padded[padded.byteLength-1])}var classCallCheck$$1=function classCallCheck$$1(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var createClass$$1=function(){function defineProperties(target,props){for(var i=0;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*16843009^x4*65537^x2*257^x*16843008;tEnc=d[s]*257^s*16843008;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){classCallCheck$$1(this,AES);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=void 0;var j=void 0;var tmp=void 0;var encKey=void 0;var decKey=void 0;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")}encKey=key.slice(0);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]]}}}AES.prototype.decrypt=function decrypt$$1(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=void 0;var b2=void 0;var c2=void 0;var nInnerRounds=key.length/4-2;var i=void 0;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>>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 Stream=function(){function Stream(){classCallCheck$$1(this,Stream);this.listeners={}}Stream.prototype.on=function on(type,listener){if(!this.listeners[type]){this.listeners[type]=[]}this.listeners[type].push(listener)};Stream.prototype.off=function off(type,listener){if(!this.listeners[type]){return false}var index=this.listeners[type].indexOf(listener);this.listeners[type].splice(index,1);return index>-1};Stream.prototype.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>8|word>>>24};var decrypt$$1=function decrypt$$1(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=void 0;var init1=void 0;var init2=void 0;var init3=void 0;var encrypted0=void 0;var encrypted1=void 0;var encrypted2=void 0;var encrypted3=void 0;var wordIx=void 0;init0=initVector[0];init1=initVector[1];init2=initVector[2];init3=initVector[3];for(wordIx=0;wordIx=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 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(!activeGroup.playlistLoader){mainSegmentLoader.resetEverything();return}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 byGroupId=function byGroupId(type,groupId){return function(playlist){return playlist.attributes[type]===groupId}};var byResolvedUri=function byResolvedUri(resolvedUri){return function(playlist){return playlist.resolvedUri===resolvedUri}};var initialize={AUDIO:function AUDIO(type,settings){var hls=settings.hls,sourceType=settings.sourceType,segmentLoader=settings.segmentLoaders[type],withCredentials=settings.requestOptions.withCredentials,_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}}}}for(var groupId in mediaGroups[type]){if(!groups[groupId]){groups[groupId]=[]}var groupPlaylists=playlists.filter(byGroupId(type,groupId));for(var variantLabel in mediaGroups[type][groupId]){var properties=mediaGroups[type][groupId][variantLabel];var matchingPlaylists=groupPlaylists.filter(byResolvedUri(properties.resolvedUri));if(matchingPlaylists.length){delete properties.resolvedUri}var playlistLoader=void 0;if(properties.resolvedUri){playlistLoader=new PlaylistLoader(properties.resolvedUri,hls,withCredentials)}else if(properties.playlists&&sourceType==="dash"){playlistLoader=new DashPlaylistLoader(properties.playlists[0],hls,withCredentials,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}}}segmentLoader.on("error",onError[type](type,settings))},SUBTITLES:function SUBTITLES(type,settings){var tech=settings.tech,hls=settings.hls,sourceType=settings.sourceType,segmentLoader=settings.segmentLoaders[type],withCredentials=settings.requestOptions.withCredentials,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,hls,withCredentials)}else if(sourceType==="dash"){playlistLoader=new DashPlaylistLoader(properties.playlists[0],hls,withCredentials,masterPlaylistLoader)}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",enabled:false,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",enabled:false,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"){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,hls=settings.hls;["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].onTrackChanged=onTrackChanged(type,settings)});var audioGroup=mediaTypes.AUDIO.activeGroup();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()})});var onAudioTrackChanged=function onAudioTrackChanged(){mediaTypes.AUDIO.onTrackChanged();tech.trigger({type:"usage",name:"hls-audio-change"})};tech.audioTracks().addEventListener("change",onAudioTrackChanged);tech.remoteTextTracks().addEventListener("change",mediaTypes.SUBTITLES.onTrackChanged);hls.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 Hls=void 0;var loaderStats=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred"];var sumLoaderStat=function sumLoaderStat(stat){return this.audioSegmentLoader_[stat]+this.mainSegmentLoader_[stat]};var MasterPlaylistController=function(_videojs$EventTarget5){inherits(MasterPlaylistController,_videojs$EventTarget5);function MasterPlaylistController(options){classCallCheck(this,MasterPlaylistController);var _this29=possibleConstructorReturn(this,_videojs$EventTarget5.call(this));var url=options.url,withCredentials=options.withCredentials,tech=options.tech,bandwidth=options.bandwidth,externHls=options.externHls,useCueTags=options.useCueTags,blacklistDuration=options.blacklistDuration,enableLowInitialPlaylist=options.enableLowInitialPlaylist,sourceType=options.sourceType;if(!url){throw new Error("A non-empty playlist URL is required")}Hls=externHls;_this29.withCredentials=withCredentials;_this29.tech_=tech;_this29.hls_=tech.hls;_this29.sourceType_=sourceType;_this29.useCueTags_=useCueTags;_this29.blacklistDuration=blacklistDuration;_this29.enableLowInitialPlaylist=enableLowInitialPlaylist;if(_this29.useCueTags_){_this29.cueTagsTrack_=_this29.tech_.addTextTrack("metadata","ad-cues");_this29.cueTagsTrack_.inBandMetadataTrackDispatchType=""}_this29.requestOptions_={withCredentials:_this29.withCredentials,timeout:null};_this29.mediaTypes_=createMediaTypes();_this29.mediaSource=new videojs$1.MediaSource;_this29.mediaSource.addEventListener("sourceopen",_this29.handleSourceOpen_.bind(_this29));_this29.seekable_=videojs$1.createTimeRanges();_this29.hasPlayed_=function(){return false};_this29.syncController_=new SyncController(options);_this29.segmentMetadataTrack_=tech.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},false).track;_this29.decrypter_=new Decrypter$1;var segmentLoaderSettings={hls:_this29.hls_,mediaSource:_this29.mediaSource,currentTime:_this29.tech_.currentTime.bind(_this29.tech_),seekable:function seekable(){return _this29.seekable()},seeking:function seeking(){return _this29.tech_.seeking()},duration:function duration(){return _this29.mediaSource.duration},hasPlayed:function hasPlayed(){return _this29.hasPlayed_()},goalBufferLength:function goalBufferLength(){return _this29.goalBufferLength()},bandwidth:bandwidth,syncController:_this29.syncController_,decrypter:_this29.decrypter_,sourceType:_this29.sourceType_};_this29.masterPlaylistLoader_=_this29.sourceType_==="dash"?new DashPlaylistLoader(url,_this29.hls_,_this29.withCredentials):new PlaylistLoader(url,_this29.hls_,_this29.withCredentials);_this29.setupMasterPlaylistLoaderListeners_();_this29.mainSegmentLoader_=new SegmentLoader(videojs$1.mergeOptions(segmentLoaderSettings,{segmentMetadataTrack:_this29.segmentMetadataTrack_,loaderType:"main"}),options);_this29.audioSegmentLoader_=new SegmentLoader(videojs$1.mergeOptions(segmentLoaderSettings,{loaderType:"audio"}),options);_this29.subtitleSegmentLoader_=new VTTSegmentLoader(videojs$1.mergeOptions(segmentLoaderSettings,{loaderType:"vtt"}),options);_this29.setupSegmentLoaderListeners_();loaderStats.forEach(function(stat){_this29[stat+"_"]=sumLoaderStat.bind(_this29,stat)});_this29.logger_=logger("MPC");_this29.masterPlaylistLoader_.load();return _this29}MasterPlaylistController.prototype.setupMasterPlaylistLoaderListeners_=function setupMasterPlaylistLoaderListeners_(){var _this30=this;this.masterPlaylistLoader_.on("loadedmetadata",function(){var media=_this30.masterPlaylistLoader_.media();var requestTimeout=_this30.masterPlaylistLoader_.targetDuration*1.5*1e3;if(isLowestEnabledRendition(_this30.masterPlaylistLoader_.master,_this30.masterPlaylistLoader_.media())){_this30.requestOptions_.timeout=0}else{_this30.requestOptions_.timeout=requestTimeout}if(media.endList&&_this30.tech_.preload()!=="none"){_this30.mainSegmentLoader_.playlist(media,_this30.requestOptions_);_this30.mainSegmentLoader_.load()}setupMediaGroups({sourceType:_this30.sourceType_,segmentLoaders:{AUDIO:_this30.audioSegmentLoader_,SUBTITLES:_this30.subtitleSegmentLoader_,main:_this30.mainSegmentLoader_},tech:_this30.tech_,requestOptions:_this30.requestOptions_,masterPlaylistLoader:_this30.masterPlaylistLoader_,hls:_this30.hls_,master:_this30.master(),mediaTypes:_this30.mediaTypes_,blacklistCurrentPlaylist:_this30.blacklistCurrentPlaylist.bind(_this30)});_this30.triggerPresenceUsage_(_this30.master(),media);try{_this30.setupSourceBuffers_()}catch(e){videojs$1.log.warn("Failed to create SourceBuffers",e);return _this30.mediaSource.endOfStream("decode")}_this30.setupFirstPlay();_this30.trigger("selectedinitialmedia")});this.masterPlaylistLoader_.on("loadedplaylist",function(){var updatedPlaylist=_this30.masterPlaylistLoader_.media();if(!updatedPlaylist){_this30.excludeUnsupportedVariants_();var selectedMedia=void 0;if(_this30.enableLowInitialPlaylist){selectedMedia=_this30.selectInitialPlaylist()}if(!selectedMedia){selectedMedia=_this30.selectPlaylist()}_this30.initialMedia_=selectedMedia;_this30.masterPlaylistLoader_.media(_this30.initialMedia_);return}if(_this30.useCueTags_){_this30.updateAdCues_(updatedPlaylist)}_this30.mainSegmentLoader_.playlist(updatedPlaylist,_this30.requestOptions_);_this30.updateDuration();if(!_this30.tech_.paused()){_this30.mainSegmentLoader_.load()}if(!updatedPlaylist.endList){var addSeekableRange=function addSeekableRange(){var seekable$$1=_this30.seekable();if(seekable$$1.length!==0){_this30.mediaSource.addSeekableRange_(seekable$$1.start(0),seekable$$1.end(0))}};if(_this30.duration()!==Infinity){var onDurationchange=function onDurationchange(){if(_this30.duration()===Infinity){addSeekableRange()}else{_this30.tech_.one("durationchange",onDurationchange)}};_this30.tech_.one("durationchange",onDurationchange)}else{addSeekableRange()}}});this.masterPlaylistLoader_.on("error",function(){_this30.blacklistCurrentPlaylist(_this30.masterPlaylistLoader_.error)});this.masterPlaylistLoader_.on("mediachanging",function(){_this30.mainSegmentLoader_.abort();_this30.mainSegmentLoader_.pause()});this.masterPlaylistLoader_.on("mediachange",function(){var media=_this30.masterPlaylistLoader_.media();var requestTimeout=_this30.masterPlaylistLoader_.targetDuration*1.5*1e3;if(isLowestEnabledRendition(_this30.masterPlaylistLoader_.master,_this30.masterPlaylistLoader_.media())){_this30.requestOptions_.timeout=0}else{_this30.requestOptions_.timeout=requestTimeout}_this30.mainSegmentLoader_.playlist(media,_this30.requestOptions_);_this30.mainSegmentLoader_.load();_this30.tech_.trigger({type:"mediachange",bubbles:true})});this.masterPlaylistLoader_.on("playlistunchanged",function(){var updatedPlaylist=_this30.masterPlaylistLoader_.media();var playlistOutdated=_this30.stuckAtPlaylistEnd_(updatedPlaylist);if(playlistOutdated){_this30.blacklistCurrentPlaylist({message:"Playlist no longer updating."});_this30.tech_.trigger("playliststuck")}});this.masterPlaylistLoader_.on("renditiondisabled",function(){_this30.tech_.trigger({type:"usage",name:"hls-rendition-disabled"})});this.masterPlaylistLoader_.on("renditionenabled",function(){_this30.tech_.trigger({type:"usage",name:"hls-rendition-enabled"})})};MasterPlaylistController.prototype.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:"hls-demuxed"})}if(Object.keys(mediaGroups.SUBTITLES).length){this.tech_.trigger({type:"usage",name:"hls-webvtt"})}if(Hls.Playlist.isAes(media)){this.tech_.trigger({type:"usage",name:"hls-aes"})}if(Hls.Playlist.isFmp4(media)){this.tech_.trigger({type:"usage",name:"hls-fmp4"})}if(audioGroupKeys.length&&Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length>1){this.tech_.trigger({type:"usage",name:"hls-alternate-audio"})}if(this.useCueTags_){this.tech_.trigger({type:"usage",name:"hls-playlist-cue-tags"})}};MasterPlaylistController.prototype.setupSegmentLoaderListeners_=function setupSegmentLoaderListeners_(){var _this31=this;this.mainSegmentLoader_.on("bandwidthupdate",function(){var nextPlaylist=_this31.selectPlaylist();var currentPlaylist=_this31.masterPlaylistLoader_.media();var buffered=_this31.tech_.buffered();var forwardBuffer=buffered.length?buffered.end(buffered.length-1)-_this31.tech_.currentTime():0;var bufferLowWaterLine=_this31.bufferLowWaterLine();if(!currentPlaylist.endList||_this31.duration()=bufferLowWaterLine){_this31.masterPlaylistLoader_.media(nextPlaylist)}_this31.tech_.trigger("bandwidthupdate")});this.mainSegmentLoader_.on("progress",function(){_this31.trigger("progress")});this.mainSegmentLoader_.on("error",function(){_this31.blacklistCurrentPlaylist(_this31.mainSegmentLoader_.error())});this.mainSegmentLoader_.on("syncinfoupdate",function(){_this31.onSyncInfoUpdate_()});this.mainSegmentLoader_.on("timestampoffset",function(){_this31.tech_.trigger({type:"usage",name:"hls-timestamp-offset"})});this.audioSegmentLoader_.on("syncinfoupdate",function(){_this31.onSyncInfoUpdate_()});this.mainSegmentLoader_.on("ended",function(){_this31.onEndOfStream()});this.mainSegmentLoader_.on("earlyabort",function(){_this31.blacklistCurrentPlaylist({message:"Aborted early because there isn't enough bandwidth to complete the "+"request without rebuffering."},ABORT_EARLY_BLACKLIST_SECONDS)});this.mainSegmentLoader_.on("reseteverything",function(){_this31.tech_.trigger("hls-reset")});this.mainSegmentLoader_.on("segmenttimemapping",function(event){_this31.tech_.trigger({type:"hls-segment-time-mapping",mapping:event.mapping})});this.audioSegmentLoader_.on("ended",function(){_this31.onEndOfStream()})};MasterPlaylistController.prototype.mediaSecondsLoaded_=function mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)};MasterPlaylistController.prototype.load=function load(){this.mainSegmentLoader_.load();if(this.mediaTypes_.AUDIO.activePlaylistLoader){this.audioSegmentLoader_.load()}if(this.mediaTypes_.SUBTITLES.activePlaylistLoader){this.subtitleSegmentLoader_.load()}};MasterPlaylistController.prototype.fastQualityChange_=function fastQualityChange_(){var media=this.selectPlaylist();if(media!==this.masterPlaylistLoader_.media()){this.masterPlaylistLoader_.media(media);this.mainSegmentLoader_.resetLoader()}};MasterPlaylistController.prototype.play=function play(){if(this.setupFirstPlay()){return}if(this.tech_.ended()){this.tech_.setCurrentTime(0)}if(this.hasPlayed_()){this.load()}var seekable$$1=this.tech_.seekable();if(this.tech_.duration()===Infinity){if(this.tech_.currentTime()0&&arguments[0]!==undefined?arguments[0]:{};var blacklistDuration=arguments[1];var currentPlaylist=void 0;var nextPlaylist=void 0;currentPlaylist=error.playlist||this.masterPlaylistLoader_.media();blacklistDuration=blacklistDuration||error.blacklistDuration||this.blacklistDuration;if(!currentPlaylist){this.error=error;try{return this.mediaSource.endOfStream("network")}catch(e){return this.trigger("error")}}var isFinalRendition=this.masterPlaylistLoader_.master.playlists.filter(isEnabled).length===1;if(isFinalRendition){videojs$1.log.warn("Problem encountered with the current "+"HLS playlist. Trying again since it is the final playlist.");this.tech_.trigger("retryplaylist");return this.masterPlaylistLoader_.load(isFinalRendition)}currentPlaylist.excludeUntil=Date.now()+blacklistDuration*1e3;this.tech_.trigger("blacklistplaylist");this.tech_.trigger({type:"usage",name:"hls-rendition-blacklisted"});nextPlaylist=this.selectPlaylist();videojs$1.log.warn("Problem encountered with the current HLS playlist."+(error.message?" "+error.message:"")+" Switching to another playlist.");return this.masterPlaylistLoader_.media(nextPlaylist)};MasterPlaylistController.prototype.pauseLoading=function pauseLoading(){this.mainSegmentLoader_.pause();if(this.mediaTypes_.AUDIO.activePlaylistLoader){this.audioSegmentLoader_.pause()}if(this.mediaTypes_.SUBTITLES.activePlaylistLoader){this.subtitleSegmentLoader_.pause()}};MasterPlaylistController.prototype.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()};MasterPlaylistController.prototype.duration=function duration(){if(!this.masterPlaylistLoader_){return 0}if(this.mediaSource){return this.mediaSource.duration}return Hls.Playlist.duration(this.masterPlaylistLoader_.media())};MasterPlaylistController.prototype.seekable=function seekable(){return this.seekable_};MasterPlaylistController.prototype.onSyncInfoUpdate_=function onSyncInfoUpdate_(){var mainSeekable=void 0;var audioSeekable=void 0;if(!this.masterPlaylistLoader_){return}var media=this.masterPlaylistLoader_.media();if(!media){return}var expired=this.syncController_.getExpiredTime(media,this.mediaSource.duration);if(expired===null){return}mainSeekable=Hls.Playlist.seekable(media,expired);if(mainSeekable.length===0){return}if(this.mediaTypes_.AUDIO.activePlaylistLoader){media=this.mediaTypes_.AUDIO.activePlaylistLoader.media();expired=this.syncController_.getExpiredTime(media,this.mediaSource.duration);if(expired===null){return}audioSeekable=Hls.Playlist.seekable(media,expired);if(audioSeekable.length===0){return}}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)0){newDuration=Math.max(newDuration,buffered.end(buffered.length-1))}if(oldDuration!==newDuration){if(this.mediaSource.readyState!=="open"){this.mediaSource.addEventListener("sourceopen",setDuration)}else{setDuration()}}};MasterPlaylistController.prototype.dispose=function dispose(){var _this34=this;this.decrypter_.terminate();this.masterPlaylistLoader_.dispose();this.mainSegmentLoader_.dispose();["AUDIO","SUBTITLES"].forEach(function(type){var groups=_this34.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()};MasterPlaylistController.prototype.master=function master(){return this.masterPlaylistLoader_.master};MasterPlaylistController.prototype.media=function media(){return this.masterPlaylistLoader_.media()||this.initialMedia_};MasterPlaylistController.prototype.setupSourceBuffers_=function setupSourceBuffers_(){var media=this.masterPlaylistLoader_.media();var mimeTypes=void 0;if(!media||this.mediaSource.readyState!=="open"){return}mimeTypes=mimeTypesForPlaylist(this.masterPlaylistLoader_.master,media);if(mimeTypes.length<1){this.error="No compatible SourceBuffer configuration for the variant stream:"+media.resolvedUri;return this.mediaSource.endOfStream("decode")}this.configureLoaderMimeTypes_(mimeTypes);this.excludeIncompatibleVariants_(media)};MasterPlaylistController.prototype.configureLoaderMimeTypes_=function configureLoaderMimeTypes_(mimeTypes){var sourceBufferEmitter=mimeTypes.length>1&&mimeTypes[0].indexOf(",")===-1&&mimeTypes[0]!==mimeTypes[1]?new videojs$1.EventTarget:null;this.mainSegmentLoader_.mimeType(mimeTypes[0],sourceBufferEmitter);if(mimeTypes[1]){this.audioSegmentLoader_.mimeType(mimeTypes[1],sourceBufferEmitter)}};MasterPlaylistController.prototype.excludeUnsupportedVariants_=function excludeUnsupportedVariants_(){this.master().playlists.forEach(function(variant){if(variant.attributes.CODECS&&window_1.MediaSource&&window_1.MediaSource.isTypeSupported&&!window_1.MediaSource.isTypeSupported('video/mp4; codecs="'+mapLegacyAvcCodecs(variant.attributes.CODECS)+'"')){variant.excludeUntil=Infinity}})};MasterPlaylistController.prototype.excludeIncompatibleVariants_=function excludeIncompatibleVariants_(media){var codecCount=2;var videoCodec=null;var codecs=void 0;if(media.attributes.CODECS){codecs=parseCodecs(media.attributes.CODECS);videoCodec=codecs.videoCodec;codecCount=codecs.codecCount}this.master().playlists.forEach(function(variant){var variantCodecs={codecCount:2,videoCodec:null};if(variant.attributes.CODECS){variantCodecs=parseCodecs(variant.attributes.CODECS)}if(variantCodecs.codecCount!==codecCount){variant.excludeUntil=Infinity}if(variantCodecs.videoCodec!==videoCodec){variant.excludeUntil=Infinity}})};MasterPlaylistController.prototype.updateAdCues_=function updateAdCues_(media){var offset=0;var seekable$$1=this.seekable();if(seekable$$1.length){offset=seekable$$1.start(0)}updateAdCues(media,this.cueTagsTrack_,offset)};MasterPlaylistController.prototype.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)};MasterPlaylistController.prototype.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);return Math.min(initial+currentTime*rate,max)};return MasterPlaylistController}(videojs$1.EventTarget);var enableFunction=function enableFunction(loader,playlistUri,changePlaylistFn){return function(enable){var playlist=loader.master.playlists[playlistUri];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(hlsHandler,playlist,id){classCallCheck(this,Representation);var fastChangeFunction=hlsHandler.masterPlaylistController_.fastQualityChange_.bind(hlsHandler.masterPlaylistController_);if(playlist.attributes.RESOLUTION){var resolution=playlist.attributes.RESOLUTION;this.width=resolution.width;this.height=resolution.height}this.bandwidth=playlist.attributes.BANDWIDTH;this.id=id;this.enabled=enableFunction(hlsHandler.playlists,playlist.uri,fastChangeFunction)};var renditionSelectionMixin=function renditionSelectionMixin(hlsHandler){var playlists=hlsHandler.playlists;hlsHandler.representations=function(){return playlists.master.playlists.filter(function(media){return!isIncompatible(media)}).map(function(e,i){return new Representation(hlsHandler,e,e.uri)})}};var timerCancelEvents=["seeking","seeked","pause","playing","error"];var PlaybackWatcher=function(){function PlaybackWatcher(options){var _this35=this;classCallCheck(this,PlaybackWatcher);this.tech_=options.tech;this.seekable=options.seekable;this.consecutiveUpdates=0;this.lastRecordedTime=null;this.timer_=null;this.checkCurrentTimeTimeout_=null;this.logger_=logger("PlaybackWatcher");this.logger_("initialize");var canPlayHandler=function canPlayHandler(){return _this35.monitorCurrentTime_()};var waitingHandler=function waitingHandler(){return _this35.techWaiting_()};var cancelTimerHandler=function cancelTimerHandler(){return _this35.cancelTimer_()};var fixesBadSeeksHandler=function fixesBadSeeksHandler(){return _this35.fixesBadSeeks_()};this.tech_.on("seekablechanged",fixesBadSeeksHandler);this.tech_.on("waiting",waitingHandler);this.tech_.on(timerCancelEvents,cancelTimerHandler);this.tech_.on("canplay",canPlayHandler);this.dispose=function(){_this35.logger_("dispose");_this35.tech_.off("seekablechanged",fixesBadSeeksHandler);_this35.tech_.off("waiting",waitingHandler);_this35.tech_.off(timerCancelEvents,cancelTimerHandler);_this35.tech_.off("canplay",canPlayHandler);if(_this35.checkCurrentTimeTimeout_){window_1.clearTimeout(_this35.checkCurrentTimeTimeout_)}_this35.cancelTimer_()}}PlaybackWatcher.prototype.monitorCurrentTime_=function monitorCurrentTime_(){this.checkCurrentTime_();if(this.checkCurrentTimeTimeout_){window_1.clearTimeout(this.checkCurrentTimeTimeout_)}this.checkCurrentTimeTimeout_=window_1.setTimeout(this.monitorCurrentTime_.bind(this),250)};PlaybackWatcher.prototype.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&¤tTime===this.lastRecordedTime){this.consecutiveUpdates++;this.waiting_()}else if(currentTime===this.lastRecordedTime){this.consecutiveUpdates++}else{this.consecutiveUpdates=0;this.lastRecordedTime=currentTime}};PlaybackWatcher.prototype.cancelTimer_=function cancelTimer_(){this.consecutiveUpdates=0;if(this.timer_){this.logger_("cancelTimer_");clearTimeout(this.timer_)}this.timer_=null};PlaybackWatcher.prototype.fixesBadSeeks_=function fixesBadSeeks_(){var seeking=this.tech_.seeking();var seekable=this.seekable();var currentTime=this.tech_.currentTime();var seekTo=void 0;if(seeking&&this.afterSeekableWindow_(seekable,currentTime)){var seekableEnd=seekable.end(seekable.length-1);seekTo=seekableEnd}if(seeking&&this.beforeSeekableWindow_(seekable,currentTime)){var seekableStart=seekable.start(0);seekTo=seekableStart+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}return false};PlaybackWatcher.prototype.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&¤tTime+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:"hls-unknown-waiting"});return}};PlaybackWatcher.prototype.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:"hls-live-resync"});return true}var buffered=this.tech_.buffered();var nextRange=findNextRange(buffered,currentTime);if(this.videoUnderflow_(nextRange,buffered,currentTime)){this.cancelTimer_();this.tech_.setCurrentTime(currentTime);this.tech_.trigger({type:"usage",name:"hls-video-underflow"});return true}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.timer_=setTimeout(this.skipTheGap_.bind(this),difference*1e3,currentTime);return true}return false};PlaybackWatcher.prototype.afterSeekableWindow_=function afterSeekableWindow_(seekable,currentTime){if(!seekable.length){return false}if(currentTime>seekable.end(seekable.length-1)+SAFE_TIME_DELTA){return true}return false};PlaybackWatcher.prototype.beforeSeekableWindow_=function beforeSeekableWindow_(seekable,currentTime){if(seekable.length&&seekable.start(0)>0&¤tTime2){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_;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:"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:"hls-error-reload"});player.play()};var errorHandler=function errorHandler(){if(Date.now()-lastCalled0){invThroughput=1/this.throughput}else{invThroughput=0}var systemBitrate=Math.floor(1/(invBandwidth+invThroughput));return systemBitrate},set:function set$$1(){videojs$1.log.error('The "systemBandwidth" property is read-only')}}});Object.defineProperties(this.stats,{bandwidth:{get:function get$$1(){return _this38.bandwidth||0},enumerable:true},mediaRequests:{get:function get$$1(){return _this38.masterPlaylistController_.mediaRequests_()||0},enumerable:true},mediaRequestsAborted:{get:function get$$1(){return _this38.masterPlaylistController_.mediaRequestsAborted_()||0},enumerable:true},mediaRequestsTimedout:{get:function get$$1(){return _this38.masterPlaylistController_.mediaRequestsTimedout_()||0},enumerable:true},mediaRequestsErrored:{get:function get$$1(){return _this38.masterPlaylistController_.mediaRequestsErrored_()||0},enumerable:true},mediaTransferDuration:{get:function get$$1(){return _this38.masterPlaylistController_.mediaTransferDuration_()||0},enumerable:true},mediaBytesTransferred:{get:function get$$1(){return _this38.masterPlaylistController_.mediaBytesTransferred_()||0},enumerable:true},mediaSecondsLoaded:{get:function get$$1(){return _this38.masterPlaylistController_.mediaSecondsLoaded_()||0},enumerable:true},buffered:{get:function get$$1(){return timeRangesToArray(_this38.tech_.buffered())},enumerable:true},currentTime:{get:function get$$1(){return _this38.tech_.currentTime()},enumerable:true},currentSource:{get:function get$$1(){return _this38.tech_.currentSource_},enumerable:true},currentTech:{get:function get$$1(){return _this38.tech_.name_},enumerable:true},duration:{get:function get$$1(){return _this38.tech_.duration()},enumerable:true},master:{get:function get$$1(){return _this38.playlists.master},enumerable:true},playerDimensions:{get:function get$$1(){return _this38.tech_.currentDimensions()},enumerable:true},seekable:{get:function get$$1(){return timeRangesToArray(_this38.tech_.seekable())},enumerable:true},timestamp:{get:function get$$1(){return Date.now()},enumerable:true},videoPlaybackQuality:{get:function get$$1(){return _this38.tech_.getVideoPlaybackQuality()},enumerable:true}});this.tech_.one("canplay",this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));this.masterPlaylistController_.on("selectedinitialmedia",function(){renditionSelectionMixin(_this38);setupEmeOptions(_this38)});this.on(this.masterPlaylistController_,"progress",function(){this.tech_.trigger("progress")});this.on(this.masterPlaylistController_,"firstplay",function(){this.ignoreNextSeekingEvent_=true});this.tech_.ready(function(){return _this38.setupQualityLevels_()});if(!this.tech_.el()){return}this.tech_.src(videojs$1.URL.createObjectURL(this.masterPlaylistController_.mediaSource))};HlsHandler.prototype.setupQualityLevels_=function setupQualityLevels_(){var _this39=this;var player=videojs$1.players[this.tech_.options_.playerId];if(player&&player.qualityLevels){this.qualityLevels_=player.qualityLevels();this.masterPlaylistController_.on("selectedinitialmedia",function(){handleHlsLoadedMetadata(_this39.qualityLevels_,_this39)});this.playlists.on("mediachange",function(){handleHlsMediaChange(_this39.qualityLevels_,_this39.playlists)})}};HlsHandler.prototype.play=function play(){this.masterPlaylistController_.play()};HlsHandler.prototype.setCurrentTime=function setCurrentTime(currentTime){this.masterPlaylistController_.setCurrentTime(currentTime)};HlsHandler.prototype.duration=function duration(){return this.masterPlaylistController_.duration()};HlsHandler.prototype.seekable=function seekable(){return this.masterPlaylistController_.seekable()};HlsHandler.prototype.dispose=function dispose(){if(this.playbackWatcher_){this.playbackWatcher_.dispose()}if(this.masterPlaylistController_){this.masterPlaylistController_.dispose()}if(this.qualityLevels_){this.qualityLevels_.dispose()}_Component.prototype.dispose.call(this)};return HlsHandler}(Component$1);var HlsSourceHandler={name:"videojs-http-streaming",VERSION:version$3,canHandleSource:function canHandleSource(srcObj){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var localOptions=videojs$1.mergeOptions(videojs$1.options,options);return HlsSourceHandler.canPlayType(srcObj.type,localOptions)},handleSource:function handleSource(source,tech){var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var localOptions=videojs$1.mergeOptions(videojs$1.options,options);tech.hls=new HlsHandler(source,tech,localOptions);tech.hls.xhr=xhrFactory();tech.hls.src(source.src,source.type);return tech.hls},canPlayType:function canPlayType(type){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var _videojs$mergeOptions=videojs$1.mergeOptions(videojs$1.options,options),overrideNative=_videojs$mergeOptions.hls.overrideNative;var supportedType=simpleTypeFromSourceType(type);var canUseMsePlayback=supportedType&&(!Hls$1.supportsTypeNatively(supportedType)||overrideNative);return canUseMsePlayback?"maybe":""}};if(typeof videojs$1.MediaSource==="undefined"||typeof videojs$1.URL==="undefined"){videojs$1.MediaSource=MediaSource;videojs$1.URL=URL$1}if(MediaSource.supportsNativeMediaSources()){videojs$1.getTech("Html5").registerSourceHandler(HlsSourceHandler,0)}videojs$1.HlsHandler=HlsHandler;videojs$1.HlsSourceHandler=HlsSourceHandler;videojs$1.Hls=Hls$1;if(!videojs$1.use){videojs$1.registerComponent("Hls",Hls$1)}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(root,factory){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=factory(require("video.js"))}else if(typeof define==="function"&&define.amd){define(["videojs"],function(videojs){return root.Youtube=factory(videojs)})}else{root.Youtube=factory(root.videojs)}})(this,function(videojs){"use strict";var _isOnMobile=videojs.browser.IS_IOS||videojs.browser.IS_ANDROID;var Tech=videojs.getTech("Tech");var Youtube=videojs.extend(Tech,{constructor:function(options,ready){Tech.call(this,options,ready);this.setPoster(options.poster);this.setSrc(this.options_.source,true);this.setTimeout(function(){if(this.el_){this.el_.parentNode.className+=" vjs-youtube";if(_isOnMobile){this.el_.parentNode.className+=" vjs-youtube-mobile"}if(Youtube.isApiReady){this.initYTPlayer()}else{Youtube.apiReadyQueue.push(this)}}}.bind(this))},dispose:function(){if(this.ytPlayer){if(this.ytPlayer.stopVideo){this.ytPlayer.stopVideo()}if(this.ytPlayer.destroy){this.ytPlayer.destroy()}}else{var index=Youtube.apiReadyQueue.indexOf(this);if(index!==-1){Youtube.apiReadyQueue.splice(index,1)}}this.ytPlayer=null;this.el_.parentNode.className=this.el_.parentNode.className.replace(" vjs-youtube","").replace(" vjs-youtube-mobile","");this.el_.parentNode.removeChild(this.el_);Tech.prototype.dispose.call(this)},createEl:function(){var div=document.createElement("div");div.setAttribute("id",this.options_.techId);div.setAttribute("style","width:100%;height:100%;top:0;left:0;position:absolute");div.setAttribute("class","vjs-tech");var divWrapper=document.createElement("div");divWrapper.appendChild(div);if(!_isOnMobile&&!this.options_.ytControls){var divBlocker=document.createElement("div");divBlocker.setAttribute("class","vjs-iframe-blocker");divBlocker.setAttribute("style","position:absolute;top:0;left:0;width:100%;height:100%");divBlocker.onclick=function(){this.pause()}.bind(this);divWrapper.appendChild(divBlocker)}if(_isOnMobile&&!this.options_.ytControls&&this.options_.playsinline){var divBlocker=document.createElement("div");divBlocker.setAttribute("class","vjs-iframe-blocker");divBlocker.setAttribute("style","position:absolute;top:0;left:0;width:100%;height:100%");divWrapper.appendChild(divBlocker)}return divWrapper},initYTPlayer:function(){var playerVars={controls:0,modestbranding:1,rel:0,showinfo:0,loop:this.options_.loop?1:0};if(typeof this.options_.autohide!=="undefined"){playerVars.autohide=this.options_.autohide}if(typeof this.options_["cc_load_policy"]!=="undefined"){playerVars["cc_load_policy"]=this.options_["cc_load_policy"]}if(typeof this.options_.ytControls!=="undefined"){playerVars.controls=this.options_.ytControls}if(typeof this.options_.disablekb!=="undefined"){playerVars.disablekb=this.options_.disablekb}if(typeof this.options_.end!=="undefined"){playerVars.end=this.options_.end}if(typeof this.options_.color!=="undefined"){playerVars.color=this.options_.color}if(!playerVars.controls){playerVars.fs=0}else if(typeof this.options_.fs!=="undefined"){playerVars.fs=this.options_.fs}if(typeof this.options_.end!=="undefined"){playerVars.end=this.options_.end}if(typeof this.options_.hl!=="undefined"){playerVars.hl=this.options_.hl}else if(typeof this.options_.language!=="undefined"){playerVars.hl=this.options_.language.substr(0,2)}if(typeof this.options_["iv_load_policy"]!=="undefined"){playerVars["iv_load_policy"]=this.options_["iv_load_policy"]}if(typeof this.options_.list!=="undefined"){playerVars.list=this.options_.list}else if(this.url&&typeof this.url.listId!=="undefined"){playerVars.list=this.url.listId}if(typeof this.options_.listType!=="undefined"){playerVars.listType=this.options_.listType}if(typeof this.options_.modestbranding!=="undefined"){playerVars.modestbranding=this.options_.modestbranding}if(typeof this.options_.playlist!=="undefined"){playerVars.playlist=this.options_.playlist}if(typeof this.options_.playsinline!=="undefined"){if(!!this.options_.playsinline){playerVars.playsinline=1}}if(typeof this.options_.rel!=="undefined"){playerVars.rel=this.options_.rel}if(typeof this.options_.showinfo!=="undefined"){playerVars.showinfo=this.options_.showinfo}if(typeof this.options_.start!=="undefined"){playerVars.start=this.options_.start}if(typeof this.options_.theme!=="undefined"){playerVars.theme=this.options_.theme}if(typeof this.options_.customVars!=="undefined"){var customVars=this.options_.customVars;Object.keys(customVars).forEach(function(key){playerVars[key]=customVars[key]})}this.activeVideoId=this.url?this.url.videoId:null;this.activeList=playerVars.list;this.ytPlayer=new YT.Player(this.options_.techId,{videoId:this.activeVideoId,playerVars:playerVars,events:{onReady:this.onPlayerReady.bind(this),onPlaybackQualityChange:this.onPlayerPlaybackQualityChange.bind(this),onPlaybackRateChange:this.onPlayerPlaybackRateChange.bind(this),onStateChange:this.onPlayerStateChange.bind(this),onVolumeChange:this.onPlayerVolumeChange.bind(this),onError:this.onPlayerError.bind(this)}})},onPlayerReady:function(){if(this.options_.muted){this.ytPlayer.mute()}var playbackRates=this.ytPlayer.getAvailablePlaybackRates();if(playbackRates.length>1){this.featuresPlaybackRate=true}this.playerReady_=true;this.triggerReady();if(this.playOnReady){this.play()}else if(this.cueOnReady){this.cueVideoById_(this.url.videoId);this.activeVideoId=this.url.videoId}},onPlayerPlaybackQualityChange:function(){},onPlayerPlaybackRateChange:function(){this.trigger("ratechange")},onPlayerStateChange:function(e){var state=e.data;if(state===this.lastState||this.errorNumber){return}this.lastState=state;switch(state){case-1:this.trigger("loadstart");this.trigger("loadedmetadata");this.trigger("durationchange");this.trigger("ratechange");break;case YT.PlayerState.ENDED:this.trigger("ended");break;case YT.PlayerState.PLAYING:this.trigger("timeupdate");this.trigger("durationchange");this.trigger("playing");this.trigger("play");if(this.isSeeking){this.onSeeked()}break;case YT.PlayerState.PAUSED:this.trigger("canplay");if(this.isSeeking){this.onSeeked()}else{this.trigger("pause")}break;case YT.PlayerState.BUFFERING:this.player_.trigger("timeupdate");this.player_.trigger("waiting");break}},onPlayerVolumeChange:function(){this.trigger("volumechange")},onPlayerError:function(e){this.errorNumber=e.data;this.trigger("pause");this.trigger("error")},error:function(){var code=1e3+this.errorNumber;switch(this.errorNumber){case 5:return{code:code,message:"Error while trying to play the video"};case 2:case 100:return{code:code,message:"Unable to find the video"};case 101:case 150:return{code:code,message:"Playback on other Websites has been disabled by the video owner."}}return{code:code,message:"YouTube unknown error ("+this.errorNumber+")"}},loadVideoById_:function(id){var options={videoId:id};if(this.options_.start){options.startSeconds=this.options_.start}if(this.options_.end){options.endEnd=this.options_.end}this.ytPlayer.loadVideoById(options)},cueVideoById_:function(id){var options={videoId:id};if(this.options_.start){options.startSeconds=this.options_.start}if(this.options_.end){options.endEnd=this.options_.end}this.ytPlayer.cueVideoById(options)},src:function(src){if(src){this.setSrc({src:src})}return this.source},poster:function(){if(_isOnMobile){return null}return this.poster_},setPoster:function(poster){this.poster_=poster},setSrc:function(source){if(!source||!source.src){return}delete this.errorNumber;this.source=source;this.url=Youtube.parseUrl(source.src);if(!this.options_.poster){if(this.url.videoId){this.poster_="https://img.youtube.com/vi/"+this.url.videoId+"/0.jpg";this.trigger("posterchange");this.checkHighResPoster()}}if(this.options_.autoplay&&!_isOnMobile){if(this.isReady_){this.play()}else{this.playOnReady=true}}else if(this.activeVideoId!==this.url.videoId){if(this.isReady_){this.cueVideoById_(this.url.videoId);this.activeVideoId=this.url.videoId}else{this.cueOnReady=true}}},autoplay:function(){return this.options_.autoplay},setAutoplay:function(val){this.options_.autoplay=val},loop:function(){return this.options_.loop},setLoop:function(val){this.options_.loop=val},play:function(){if(!this.url||!this.url.videoId){return}this.wasPausedBeforeSeek=false;if(this.isReady_){if(this.url.listId){if(this.activeList===this.url.listId){this.ytPlayer.playVideo()}else{this.ytPlayer.loadPlaylist(this.url.listId);this.activeList=this.url.listId}}if(this.activeVideoId===this.url.videoId){this.ytPlayer.playVideo()}else{this.loadVideoById_(this.url.videoId);this.activeVideoId=this.url.videoId}}else{this.trigger("waiting");this.playOnReady=true}},pause:function(){if(this.ytPlayer){this.ytPlayer.pauseVideo()}},paused:function(){return this.ytPlayer?this.lastState!==YT.PlayerState.PLAYING&&this.lastState!==YT.PlayerState.BUFFERING:true},currentTime:function(){return this.ytPlayer?this.ytPlayer.getCurrentTime():0},setCurrentTime:function(seconds){if(this.lastState===YT.PlayerState.PAUSED){this.timeBeforeSeek=this.currentTime()}if(!this.isSeeking){this.wasPausedBeforeSeek=this.paused()}this.ytPlayer.seekTo(seconds,true);this.trigger("timeupdate");this.trigger("seeking");this.isSeeking=true;if(this.lastState===YT.PlayerState.PAUSED&&this.timeBeforeSeek!==seconds){clearInterval(this.checkSeekedInPauseInterval);this.checkSeekedInPauseInterval=setInterval(function(){if(this.lastState!==YT.PlayerState.PAUSED||!this.isSeeking){clearInterval(this.checkSeekedInPauseInterval)}else if(this.currentTime()!==this.timeBeforeSeek){this.trigger("timeupdate");this.onSeeked()}}.bind(this),250)}},seeking:function(){return this.isSeeking},seekable:function(){if(!this.ytPlayer){return videojs.createTimeRange()}return videojs.createTimeRange(0,this.ytPlayer.getDuration())},onSeeked:function(){clearInterval(this.checkSeekedInPauseInterval);this.isSeeking=false;if(this.wasPausedBeforeSeek){this.pause()}this.trigger("seeked")},playbackRate:function(){return this.ytPlayer?this.ytPlayer.getPlaybackRate():1},setPlaybackRate:function(suggestedRate){if(!this.ytPlayer){return}this.ytPlayer.setPlaybackRate(suggestedRate)},duration:function(){return this.ytPlayer?this.ytPlayer.getDuration():0},currentSrc:function(){return this.source&&this.source.src},ended:function(){return this.ytPlayer?this.lastState===YT.PlayerState.ENDED:false},volume:function(){return this.ytPlayer?this.ytPlayer.getVolume()/100:1},setVolume:function(percentAsDecimal){if(!this.ytPlayer){return}this.ytPlayer.setVolume(percentAsDecimal*100)},muted:function(){return this.ytPlayer?this.ytPlayer.isMuted():false},setMuted:function(mute){if(!this.ytPlayer){return}else{this.muted(true)}if(mute){this.ytPlayer.mute()}else{this.ytPlayer.unMute()}this.setTimeout(function(){this.trigger("volumechange")},50)},buffered:function(){if(!this.ytPlayer||!this.ytPlayer.getVideoLoadedFraction){return videojs.createTimeRange()}var bufferedEnd=this.ytPlayer.getVideoLoadedFraction()*this.ytPlayer.getDuration();return videojs.createTimeRange(0,bufferedEnd)},preload:function(){},load:function(){},reset:function(){},supportsFullScreen:function(){return true},checkHighResPoster:function(){var uri="https://img.youtube.com/vi/"+this.url.videoId+"/maxresdefault.jpg";try{var image=new Image;image.onload=function(){if("naturalHeight"in image){if(image.naturalHeight<=90||image.naturalWidth<=120){return}}else if(image.height<=90||image.width<=120){return}this.poster_=uri;this.trigger("posterchange")}.bind(this);image.onerror=function(){};image.src=uri}catch(e){}}});Youtube.isSupported=function(){return true};Youtube.canPlaySource=function(e){return Youtube.canPlayType(e.type)};Youtube.canPlayType=function(e){return e==="video/youtube"};Youtube.parseUrl=function(url){var result={videoId:null};var regex=/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;var match=url.match(regex);if(match&&match[2].length===11){result.videoId=match[2]}var regPlaylist=/[?&]list=([^#\&\?]+)/;match=url.match(regPlaylist);if(match&&match[1]){result.listId=match[1]}return result};function apiLoaded(){YT.ready(function(){Youtube.isApiReady=true;for(var i=0;i=n.length)break;i=n[o++]}else{if(o=n.next(),o.done)break;i=o.value}var a=i,u=e.getAttribute("data-vimeo-"+a);(u||""===u)&&(t[a]=""===u?1:u)}return t}function l(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return new Promise(function(n,r){if(!s(e))throw new TypeError("“"+e+"” is not a vimeo.com url.");var o="https://vimeo.com/api/oembed.json?url="+encodeURIComponent(e);for(var i in t)t.hasOwnProperty(i)&&(o+="&"+i+"="+encodeURIComponent(t[i]));var a="XDomainRequest"in window?new XDomainRequest:new XMLHttpRequest;a.open("GET",o,!0),a.onload=function(){if(404===a.status)return void r(new Error("“"+e+"” was not found."));if(403===a.status)return void r(new Error("“"+e+"” is not embeddable."));try{var t=JSON.parse(a.responseText);n(t)}catch(e){r(e)}},a.onerror=function(){var e=a.status?" ("+a.status+")":"";r(new Error("There was an error fetching the embed code from Vimeo"+e+"."))},a.send()})}function h(e,t){var n=e.html;if(!t)throw new TypeError("An element must be provided");if(null!==t.getAttribute("data-vimeo-initialized"))return t.querySelector("iframe");var r=document.createElement("div");return r.innerHTML=n,t.appendChild(r.firstChild),t.setAttribute("data-vimeo-initialized","true"),t.querySelector("iframe")}function d(){var e=arguments.length<=0||void 0===arguments[0]?document:arguments[0],t=[].slice.call(e.querySelectorAll("[data-vimeo-id], [data-vimeo-url]")),n=function(e){"console"in window&&console.error&&console.error("There was an error creating an embed: "+e)},r=function(){if(i){if(a>=o.length)return"break";u=o[a++]}else{if(a=o.next(),a.done)return"break";u=a.value}var e=u;try{if(null!==e.getAttribute("data-vimeo-defer"))return"continue";var t=f(e),r=c(t);l(r,t).then(function(t){return h(t,e)}).catch(n)}catch(e){n(e)}};e:for(var o=t,i=Array.isArray(o),a=0,o=i?o:o[Symbol.iterator]();;){var u,s=r();switch(s){case"break":break e;case"continue":continue}}}function p(e){return"string"==typeof e&&(e=JSON.parse(e)),e}function v(e,t,n){if(e.element.contentWindow.postMessage){var r={method:t};void 0!==n&&(r.value=n);var o=parseFloat(navigator.userAgent.toLowerCase().replace(/^.*msie (\d+).*$/,"$1"));o>=8&&o<10&&(r=JSON.stringify(r)),e.element.contentWindow.postMessage(r,e.origin)}}function y(e,t){t=p(t);var o=[],i=void 0;if(t.event){if("error"===t.event)for(var a=n(e,t.data.method),u=a,s=Array.isArray(u),c=0,u=s?u:u[Symbol.iterator]();;){var f;if(s){if(c>=u.length)break;f=u[c++]}else{if(c=u.next(),c.done)break;f=c.value}var l=f,h=new Error(t.data.message);h.name=t.data.name,l.reject(h),r(e,t.data.method,l)}o=n(e,"event:"+t.event),i=t.data}else t.method&&(o=n(e,t.method),i=t.value,r(e,t.method));for(var d=o,v=Array.isArray(d),y=0,d=v?d:d[Symbol.iterator]();;){var m;if(v){if(y>=d.length)break;m=d[y++]}else{if(y=d.next(),y.done)break;m=y.value}var g=m;try{if("function"==typeof g){g.call(e,i);continue}g.resolve(i)}catch(e){}}}var m="undefined"!=typeof Array.prototype.indexOf,g="undefined"!=typeof window.postMessage;if(!m||!g)throw new Error("Sorry, the Vimeo Player API is not available in this browser.");var w="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},b=(e(function(e,t){!function(e){function t(e,t){function r(e){return this&&this.constructor===r?(this._keys=[],this._values=[],this._itp=[],this.objectOnly=t,void(e&&n.call(this,e))):new r(e)}return t||w(e,"size",{get:y}),e.constructor=r,r.prototype=e,r}function n(e){this.add?e.forEach(this.add,this):e.forEach(function(e){this.set(e[0],e[1])},this)}function r(e){return this.has(e)&&(this._keys.splice(g,1),this._values.splice(g,1),this._itp.forEach(function(e){g0&&e(n,s))}catch(e){i.call(new u(s),e)}}}function i(t){var r=this;r.triggered||(r.triggered=!0,r.def&&(r=r.def),r.msg=t,r.state=2,r.chain.length>0&&e(n,r))}function a(e,t,n,r){for(var o=0;o1&&window.console&&console.warn&&console.warn("A jQuery object with multiple elements was passed, using the first element."),e=e[0]),"string"==typeof e&&(e=document.getElementById(e)),!a(e))throw new TypeError("You must pass either a valid element or a valid id.");if("IFRAME"!==e.nodeName){var r=e.querySelector("iframe");r&&(e=r)}if("IFRAME"===e.nodeName&&!s(e.getAttribute("src")||""))throw new Error("The player element passed isn’t a Vimeo embed.");if(x.has(e))return x.get(e);this.element=e,this.origin="*";var i=new E(function(r,i){var a=function(e){if(s(e.origin)&&t.element.contentWindow===e.source){"*"===t.origin&&(t.origin=e.origin);var n=p(e.data),o="event"in n&&"ready"===n.event,i="method"in n&&"ping"===n.method;return o||i?(t.element.setAttribute("data-ready","true"),void r()):void y(t,n)}};if(window.addEventListener?window.addEventListener("message",a,!1):window.attachEvent&&window.attachEvent("onmessage",a),"IFRAME"!==t.element.nodeName){var u=f(e,n),d=c(u);l(d,u).then(function(n){var r=h(n,e);return t.element=r,o(e,r),n}).catch(function(e){return i(e)})}});return j.set(this,i),x.set(this.element,this),"IFRAME"===this.element.nodeName&&v(this,"ping"),this}return Player.prototype.then=function(e){var t=arguments.length<=1||void 0===arguments[1]?function(){}:arguments[1];return this.ready().then(e,t)},Player.prototype.callMethod=function(e){var n=this,r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return new E(function(o,i){return n.ready().then(function(){t(n,e,{resolve:o,reject:i}),v(n,e,r)})})},Player.prototype.get=function(e){var n=this;return new E(function(r,o){return e=i(e,"get"),n.ready().then(function(){t(n,e,{resolve:r,reject:o}),v(n,e)})})},Player.prototype.set=function(e,n){var r=this;return E.resolve(n).then(function(n){if(e=i(e,"set"),void 0===n||null===n)throw new TypeError("There must be a value to set.");return r.ready().then(function(){return new E(function(o,i){t(r,e,{resolve:o,reject:i}),v(r,e,n)})})})},Player.prototype.on=function(e,r){if(!e)throw new TypeError("You must pass an event name.");if(!r)throw new TypeError("You must pass a callback function.");if("function"!=typeof r)throw new TypeError("The callback must be a function.");var o=n(this,"event:"+e);0===o.length&&this.callMethod("addEventListener",e).catch(function(){}),t(this,"event:"+e,r)},Player.prototype.off=function(e,t){if(!e)throw new TypeError("You must pass an event name.");if(t&&"function"!=typeof t)throw new TypeError("The callback must be a function.");var n=r(this,"event:"+e,t);n&&this.callMethod("removeEventListener",e).catch(function(e){})},Player.prototype.loadVideo=function(e){return this.callMethod("loadVideo",e)},Player.prototype.ready=function(){var e=j.get(this);return E.resolve(e)},Player.prototype.enableTextTrack=function(e,t){if(!e)throw new TypeError("You must pass a language.");return this.callMethod("enableTextTrack",{language:e,kind:t})},Player.prototype.disableTextTrack=function(){return this.callMethod("disableTextTrack")},Player.prototype.pause=function(){return this.callMethod("pause")},Player.prototype.play=function(){return this.callMethod("play")},Player.prototype.unload=function(){return this.callMethod("unload")},Player.prototype.getAutopause=function(){return this.get("autopause")},Player.prototype.setAutopause=function(e){return this.set("autopause",e)},Player.prototype.getColor=function(){return this.get("color")},Player.prototype.setColor=function(e){return this.set("color",e)},Player.prototype.getCurrentTime=function(){return this.get("currentTime")},Player.prototype.setCurrentTime=function(e){return this.set("currentTime",e)},Player.prototype.getDuration=function(){return this.get("duration")},Player.prototype.getEnded=function(){return this.get("ended")},Player.prototype.getLoop=function(){return this.get("loop")},Player.prototype.setLoop=function(e){return this.set("loop",e)},Player.prototype.getPaused=function(){return this.get("paused")},Player.prototype.getTextTracks=function(){return this.get("textTracks")},Player.prototype.getVideoEmbedCode=function(){return this.get("videoEmbedCode")},Player.prototype.getVideoId=function(){return this.get("videoId")},Player.prototype.getVideoTitle=function(){return this.get("videoTitle")},Player.prototype.getVideoWidth=function(){return this.get("videoWidth")},Player.prototype.getVideoHeight=function(){return this.get("videoHeight")},Player.prototype.getVideoUrl=function(){return this.get("videoUrl")},Player.prototype.getVolume=function(){return this.get("volume")},Player.prototype.setVolume=function(e){return this.set("volume",e)},Player}();return d(),Player})}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],2:[function(require,module,exports){(function(global){"use strict";exports.__esModule=true;var _video=typeof window!=="undefined"?window["videojs"]:typeof global!=="undefined"?global["videojs"]:null;var _video2=_interopRequireDefault(_video);var _player=require("@vimeo/player");var _player2=_interopRequireDefault(_player);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var Component=_video2.default.getComponent("Component");var Tech=_video2.default.getComponent("Tech");var cssInjected=false;var Vimeo=function(_Tech){_inherits(Vimeo,_Tech);function Vimeo(options,ready){_classCallCheck(this,Vimeo);var _this=_possibleConstructorReturn(this,_Tech.call(this,options,ready));injectCss();_this.setPoster(options.poster);_this.initVimeoPlayer();return _this}Vimeo.prototype.initVimeoPlayer=function initVimeoPlayer(){var _this2=this;var vimeoOptions={url:this.options_.source.src,byline:false,portrait:false,title:false};if(this.options_.autoplay){vimeoOptions.autoplay=true}if(this.options_.height){vimeoOptions.height=this.options_.height}if(this.options_.width){vimeoOptions.width=this.options_.width}if(this.options_.maxheight){vimeoOptions.maxheight=this.options_.maxheight}if(this.options_.maxwidth){vimeoOptions.maxwidth=this.options_.maxwidth}if(this.options_.loop){vimeoOptions.loop=this.options_.loop}this._player=new _player2.default(this.el(),vimeoOptions);this.initVimeoState();["play","pause","ended","timeupdate","progress","seeked"].forEach(function(e){_this2._player.on(e,function(progress){if(_this2._vimeoState.progress.duration!=progress.duration){_this2.trigger("durationchange")}_this2._vimeoState.progress=progress;_this2.trigger(e)})});this._player.on("pause",function(){return _this2._vimeoState.playing=false});this._player.on("play",function(){_this2._vimeoState.playing=true;_this2._vimeoState.ended=false});this._player.on("ended",function(){_this2._vimeoState.playing=false;_this2._vimeoState.ended=true});this._player.on("volumechange",function(v){return _this2._vimeoState.volume=v});this._player.on("error",function(e){return _this2.trigger("error",e)});this.triggerReady()};Vimeo.prototype.initVimeoState=function initVimeoState(){var state=this._vimeoState={ended:false,playing:false,volume:0,progress:{seconds:0,percent:0,duration:0}};this._player.getCurrentTime().then(function(time){return state.progress.seconds=time});this._player.getDuration().then(function(time){return state.progress.duration=time});this._player.getPaused().then(function(paused){return state.playing=!paused});this._player.getVolume().then(function(volume){return state.volume=volume})};Vimeo.prototype.createEl=function createEl(){var div=_video2.default.createEl("div",{id:this.options_.techId});div.style.cssText="width:100%;height:100%;top:0;left:0;position:absolute";div.className="vjs-vimeo";return div};Vimeo.prototype.controls=function controls(){return true};Vimeo.prototype.supportsFullScreen=function supportsFullScreen(){return true};Vimeo.prototype.src=function src(){return this.options_.source};Vimeo.prototype.currentSrc=function currentSrc(){return this.options_.source.src};Vimeo.prototype.currentTime=function currentTime(){return this._vimeoState.progress.seconds};Vimeo.prototype.setCurrentTime=function setCurrentTime(time){this._player.setCurrentTime(time)};Vimeo.prototype.volume=function volume(){return this._vimeoState.volume};Vimeo.prototype.setVolume=function setVolume(volume){return this._player.setVolume(volume)};Vimeo.prototype.duration=function duration(){return this._vimeoState.progress.duration};Vimeo.prototype.buffered=function buffered(){var progress=this._vimeoState.progress;return _video2.default.createTimeRange(0,progress.percent*progress.duration)};Vimeo.prototype.paused=function paused(){return!this._vimeoState.playing};Vimeo.prototype.pause=function pause(){this._player.pause()};Vimeo.prototype.play=function play(){this._player.play()};Vimeo.prototype.muted=function muted(){return this._vimeoState.volume===0};Vimeo.prototype.ended=function ended(){return this._vimeoState.ended};Vimeo.prototype.playbackRate=function playbackRate(){return 1};return Vimeo}(Tech);Vimeo.prototype.featuresTimeupdateEvents=true;Vimeo.isSupported=function(){return true};Tech.withSourceHandlers(Vimeo);Vimeo.nativeSourceHandler={};Vimeo.nativeSourceHandler.canPlayType=function(source){if(source==="video/vimeo"){return"maybe"}return""};Vimeo.nativeSourceHandler.canHandleSource=function(source){if(source.type){return Vimeo.nativeSourceHandler.canPlayType(source.type)}else if(source.src){return Vimeo.nativeSourceHandler.canPlayType(source.src)}return""};Vimeo.nativeSourceHandler.handleSource=function(source,tech){tech.src(source.src)};Vimeo.nativeSourceHandler.dispose=function(){};Vimeo.registerSourceHandler(Vimeo.nativeSourceHandler);function injectCss(){if(cssInjected){return}cssInjected=true;var css="\n .vjs-vimeo iframe {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n }\n ";var head=document.head||document.getElementsByTagName("head")[0];var style=document.createElement("style");style.type="text/css";if(style.styleSheet){style.styleSheet.cssText=css}else{style.appendChild(document.createTextNode(css))}head.appendChild(style)}Tech.registerTech("Vimeo",Vimeo);Vimeo.VERSION="0.0.1";exports.default=Vimeo}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"@vimeo/player":1}]},{},[2])(2)});(function(global,factory){if(typeof define==="function"&&define.amd){define(["video.js"],factory)}else if(typeof exports!=="undefined"){factory(require("video.js"))}else{var mod={exports:{}};factory(global.videojs);global.videojsMarkers=mod.exports}})(this,function(_video){"use strict";var _video2=_interopRequireDefault(_video);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};var defaultSetting={markerStyle:{width:"7px","border-radius":"30%","background-color":"red"},markerTip:{display:true,text:function text(marker){return"Break: "+marker.text},time:function time(marker){return marker.time}},breakOverlay:{display:false,displayTime:3,text:function text(marker){return"Break overlay: "+marker.overlayText},style:{width:"100%",height:"20%","background-color":"rgba(0,0,0,0.7)",color:"white","font-size":"17px"}},onMarkerClick:function onMarkerClick(marker){},onMarkerMouseover:function onMarkerMouseover(marker){},onMarkerReached:function onMarkerReached(marker,index){},markers:[]};function generateUUID(){var d=(new Date).getTime();var uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=(d+Math.random()*16)%16|0;d=Math.floor(d/16);return(c=="x"?r:r&3|8).toString(16)});return uuid}function getElementBounding(element){var elementBounding;var defaultBoundingRect={top:0,bottom:0,left:0,width:0,height:0,right:0};try{elementBounding=element.getBoundingClientRect()}catch(e){elementBounding=defaultBoundingRect}return elementBounding}var NULL_INDEX=-1;function registerVideoJsMarkersPlugin(options){if(!_video2.default.mergeOptions){var isPlain=function isPlain(value){return!!value&&(typeof value==="undefined"?"undefined":_typeof(value))==="object"&&toString.call(value)==="[object Object]"&&value.constructor===Object};var mergeOptions=function mergeOptions(source1,source2){var result={};var sources=[source1,source2];sources.forEach(function(source){if(!source){return}Object.keys(source).forEach(function(key){var value=source[key];if(!isPlain(value)){result[key]=value;return}if(!isPlain(result[key])){result[key]={}}result[key]=mergeOptions(result[key],value)})});return result};_video2.default.mergeOptions=mergeOptions}if(!_video2.default.createEl){_video2.default.createEl=function(tagName,props,attrs){var el=_video2.default.Player.prototype.createEl(tagName,props);if(!!attrs){Object.keys(attrs).forEach(function(key){el.setAttribute(key,attrs[key])})}return el}}var setting=_video2.default.mergeOptions(defaultSetting,options),markersMap={},markersList=[],currentMarkerIndex=NULL_INDEX,player=this,markerTip=null,breakOverlay=null,overlayIndex=NULL_INDEX;function sortMarkersList(){markersList.sort(function(a,b){return setting.markerTip.time(a)-setting.markerTip.time(b)})}function addMarkers(newMarkers){newMarkers.forEach(function(marker){marker.key=generateUUID();player.el().querySelector(".vjs-progress-holder").appendChild(createMarkerDiv(marker));markersMap[marker.key]=marker;markersList.push(marker)});sortMarkersList()}function getPosition(marker){return setting.markerTip.time(marker)/player.duration()*100}function setMarkderDivStyle(marker,markerDiv){markerDiv.className="vjs-marker "+(marker.class||"");Object.keys(setting.markerStyle).forEach(function(key){markerDiv.style[key]=setting.markerStyle[key]});var ratio=marker.time/player.duration();if(ratio<0||ratio>1){markerDiv.style.display="none"}markerDiv.style.left=getPosition(marker)+"%";if(marker.duration){markerDiv.style.width=marker.duration/player.duration()*100+"%";markerDiv.style.marginLeft="0px"}else{var markerDivBounding=getElementBounding(markerDiv);markerDiv.style.marginLeft=markerDivBounding.width/2+"px"}}function createMarkerDiv(marker){var markerDiv=_video2.default.dom.createEl("div",{},{"data-marker-key":marker.key,"data-marker-time":setting.markerTip.time(marker)});setMarkderDivStyle(marker,markerDiv);markerDiv.addEventListener("click",function(e){var preventDefault=false;if(typeof setting.onMarkerClick==="function"){preventDefault=setting.onMarkerClick(marker)===false}if(!preventDefault){var key=this.getAttribute("data-marker-key");player.currentTime(setting.markerTip.time(markersMap[key]))}});if(setting.markerTip.display){registerMarkerTipHandler(markerDiv)}if(typeof setting.onMarkerMouseover==="function"){markerDiv.addEventListener("mouseover",function(e){setting.onMarkerMouseover(marker)})}if(typeof setting.onMarkerMouseout==="function"){markerDiv.addEventListener("mouseout",function(e){setting.onMarkerMouseout(marker)})}return markerDiv}function updateMarkers(force){markersList.forEach(function(marker){var markerDiv=player.el().querySelector(".vjs-marker[data-marker-key='"+marker.key+"']");var markerTime=setting.markerTip.time(marker);if(force||markerDiv.getAttribute("data-marker-time")!==markerTime){setMarkderDivStyle(marker,markerDiv);markerDiv.setAttribute("data-marker-time",markerTime)}});sortMarkersList()}function removeMarkers(indexArray){if(!!breakOverlay){overlayIndex=NULL_INDEX;breakOverlay.style.visibility="hidden"}currentMarkerIndex=NULL_INDEX;var deleteIndexList=[];indexArray.forEach(function(index){var marker=markersList[index];if(marker){delete markersMap[marker.key];deleteIndexList.push(index);var el=player.el().querySelector(".vjs-marker[data-marker-key='"+marker.key+"']");el&&el.parentNode.removeChild(el)}});deleteIndexList.reverse();deleteIndexList.forEach(function(deleteIndex){markersList.splice(deleteIndex,1)});sortMarkersList()}function registerMarkerTipHandler(markerDiv){markerDiv.addEventListener("mouseover",function(){var marker=markersMap[markerDiv.getAttribute("data-marker-key")];if(!!markerTip){markerTip.querySelector(".vjs-tip-inner").innerText=setting.markerTip.text(marker);markerTip.style.left=getPosition(marker)+"%";var markerTipBounding=getElementBounding(markerTip);var markerDivBounding=getElementBounding(markerDiv);markerTip.style.marginLeft=-parseFloat(markerTipBounding.width/2)+parseFloat(markerDivBounding.width/4)+"px";markerTip.style.visibility="visible"}});markerDiv.addEventListener("mouseout",function(){if(!!markerTip){markerTip.style.visibility="hidden"}})}function initializeMarkerTip(){markerTip=_video2.default.createEl("div",{className:"vjs-tip",innerHTML:""});player.el().querySelector(".vjs-progress-holder").appendChild(markerTip)}function updateBreakOverlay(){if(!setting.breakOverlay.display||currentMarkerIndex<0){return}var currentTime=player.currentTime();var marker=markersList[currentMarkerIndex];var markerTime=setting.markerTip.time(marker);if(currentTime>=markerTime&¤tTime<=markerTime+setting.breakOverlay.displayTime){if(overlayIndex!==currentMarkerIndex){overlayIndex=currentMarkerIndex;if(breakOverlay){breakOverlay.querySelector(".vjs-break-overlay-text").innerHTML=setting.breakOverlay.text(marker)}}if(breakOverlay){breakOverlay.style.visibility="visible"}}else{overlayIndex=NULL_INDEX;if(breakOverlay){breakOverlay.style.visibility="hidden"}}}function initializeOverlay(){breakOverlay=_video2.default.createEl("div",{className:"vjs-break-overlay",innerHTML:""});Object.keys(setting.breakOverlay.style).forEach(function(key){if(breakOverlay){breakOverlay.style[key]=setting.breakOverlay.style[key]}});player.el().appendChild(breakOverlay);overlayIndex=NULL_INDEX}function onTimeUpdate(){onUpdateMarker();updateBreakOverlay();options.onTimeUpdateAfterMarkerUpdate&&options.onTimeUpdateAfterMarkerUpdate()}function onUpdateMarker(){if(!markersList.length){return}var getNextMarkerTime=function getNextMarkerTime(index){if(index=setting.markerTip.time(markersList[currentMarkerIndex])&¤tTime=setting.markerTip.time(markersList[i])&¤tTimecurrentTime){player.currentTime(markerTime);break}}},prev:function prev(){var currentTime=player.currentTime();for(var i=markersList.length-1;i>=0;i--){var markerTime=setting.markerTip.time(markersList[i]);if(markerTime+.5 {
if(this._player.paused()) {
this._player.play();
} else {
this._player.pause();
}
});
}
}
return this._player;
};
ELCVideoJS.prototype.init = function() {
if (this.inited) {
return;
}
this.inited = true;
this._init_markers();
this._init_player_events();
};
/*
* Conceptually there is the play and the ELCVideoJS play. Renamed
* ELCVideoJS.play to startVideo to help denote the difference.
*
* startVideo handles making sure the element is initialized and
* ready to go.
*/
ELCVideoJS.prototype.startVideo = function() {
if (!this.$videoElement.hasClass('videojs-video--loading')) {
this.init()
this.$videoElement.addClass('videojs-video--loading');
}
var player = this.getPlayer();
const readyVideoElement = () => {
let playerReady = player.isReady_;
if (playerReady) {
this.$videoElement.trigger('video-ready', [player]);
player.play();
return;
} else {
setTimeout(function(){
readyVideoElement();
}, 250);
}
}
readyVideoElement();
player.on('ready', function() {
// timeout required for techGet on videoJS to be ready as well.
setTimeout(function() {
player.play();
}, 1000);
});
};
ELCVideoJS.prototype.add_current_marker = function(marker) {
this.currentMarker[marker['mantle_key']] = marker;
};
ELCVideoJS.prototype._init_markers = function() {
var $videoElement = this.$videoElement;
var player = this.getPlayer();
var self = this;
var options = {
markerStyle: {
'background-color': '',
'width': '',
'border-radius': '',
},
markerTip: {
display: false,
},
breakOverlay: {
display: false,
},
onMarkerMouseout: function(marker) {
$videoElement.trigger('video-marker-mouseout', [marker]);
},
onMarkerMouseover: function(marker) {
$videoElement.trigger('video-marker-mouseover', [marker]);
},
onMarkerReached: function(marker, i) {
self.add_current_marker(marker);
$videoElement.trigger('video-marker-reached', [marker]);
},
onMarkerClick: function(marker, i) {
$videoElement.trigger('video-marker-click', [marker]);
return false;
},
};
player.markers(options);
player.on('timeupdate', function(e) {
if (!self.markers || self.markers.length === 0) {
return;
}
$.each(self.markers, function (key, marker) {
if (!marker.time_duration) {
return;
}
var currentTime = player.currentTime();
var initTime = marker.time;
var exitTime = initTime + marker.time_duration;
if (currentTime < initTime || currentTime >= exitTime) {
$videoElement.trigger('video-marker-exited', [marker]);
delete self.markers[marker['mantle_key']];
} else {
$videoElement.trigger('video-marker-reached', [marker]);
}
});
});
};
ELCVideoJS.prototype._init_player_events = function() {
var $videoElement = this.$videoElement;
var player = this.getPlayer();
var self = this;
$videoElement.on('video-pause', function(e) {
player.pause();
});
$videoElement.on('video-play', function(e) {
player.play();
});
player.on('pause', function() {
$videoElement.addClass('video-paused');
$videoElement.trigger('video-paused');
self.$landing.show();
});
// There is probably a better way to detect that we're clicked to play.
player.on('waiting', function() {
$videoElement.trigger('video-waiting');
if (player.isReady_ && !player.hasStarted_) {
setTimeout(function() {
$videoElement.trigger('video-play');
}, 1000);
}
});
player.bigPlayButton.on('click', function(e) {
$videoElement.trigger('start-video');
});
player.on('play', function() {
$videoElement.removeClass('videojs-video--loading');
// when video ends. we reset currentTime which trigger the play event.
// this is obviously not a real play. So we keep track of the rewind
// state via a class and don't do things like hide landing unless we're
// on a real play event.
if (!$videoElement.hasClass('video-end-process')) {
self.$landing.hide();
self.$landingImage.hide();
player.posterImage.hide();
player.controlBar.show();
player.bigPlayButton.hide();
$videoElement.trigger('video-started');
}
if (self.markers_inited) {
return;
}
// youtube doesn't have duraiton until playing.
// so we force an update on play
if (self.markers) {
self.markers_inited = true;
player.markers.reset(self.markers);
}
});
player.on('ended', function () {
// wait a sec to make sure that the user hasn't decided to play the video again.
setTimeout(function () {
if (player.isFullscreen_ && $videoElement.hasClass('vjs-user-inactive')) {
player.exitFullscreen();
}
}, 1000);
});
player.on('requestFullscreen', function(){
$videoElement.addClass('video-block--fullscreen');
closeOtherFullscreens();
});
player.on('exitFullscreen', function(){
$videoElement.removeClass('video-block--fullscreen');
});
player.on('fullscreenchange', function(){
$videoElement.toggleClass('video-block--fullscreen');
});
const closeOtherFullscreens = (el) => {
let thisVideoBlock = el.closest('.js-video-block');
let otherVideoBlocks = document.querySelectorAll('.js-video-block');
otherVideoBlocks.forEach((block) => {
if (block !== thisVideoBlock){
let thisPlayer = block.getPlayer();
thisPlayer.exitFullscreen();
}
})
}
/*
* Handle the end of video playback. We reset back to the original state so
* that we don't see the youtube related videos and such. This should
* probably be configruable as to what end behavior we want.
*/
player.on('ended', function() {
if (self.enableLoop) {
return;
}
$videoElement.trigger('video-ended');
$videoElement.addClass('video-end-process');
player.currentTime(0); // this will trigger play again
if (!self.providerHtmlFive) {
// @todo: Clean up this code or remove the following lines after all brands make the upgrade and use the new fields
player.posterImage.show();
$(player.posterImage.contentEl()).show();
$(player.bigPlayButton.contentEl()).show();
}
if (self.hasPosterMediaFile) {
self.$landing.show();
self.$landingImage.show();
}
player.bigPlayButton.show();
player.controlBar.hide();
// setting currentTime does some async stuff
// so we set a class that forces poster.
// then we remove it once we are setup
window.setTimeout(function() {
$videoElement.removeClass('video-end-process');
$videoElement.trigger('video-ended-final');
}, 300);
});
};
MantleVideo.ELCVideoJS = ELCVideoJS;
})(jQuery);
/*
* Drupal specific integrations.
*/
(function($, Drupal) {
// Top level listener. Other components like MantleVideoPlayer can intercept
// this event and have specialized start behavior. This top level is just a
// fallback to make the ELCVideoJS work independent of a containing
// component.
$(document).on('start-video', '.js-videojs-video', function(e) {
var $videoElement = $(this);
var elcVideo = $videoElement.data('video-manager');
elcVideo.startVideo();
});
Drupal.behaviors.videoJSElement = {
attachReal: function(context, force) {
force = !!force;
var $videoElements = $('.js-videojs-video', context);
$videoElements.each(function(i, obj) {
var $videoElement = $(obj);
// already inited. bye
if ($videoElement.data('video-element-initialized')) {
return;
}
// we have a parent template that wants to control this.
var $videoControllers = $videoElement.closest('[data-video-element-controller="1"]');
if ($videoControllers.length > 0 && !force) {
return;
}
var elcVideo = new MantleVideo.ELCVideoJS($videoElement);
$videoElement.data('video-element-initialized', 1);
});
},
attach: function(context, settings) {
var mod = this;
mod.attachReal(context, false);
}
};
})(jQuery, Drupal);;
var MantleBehavior=MantleBehavior||{},MantleVideo=MantleVideo||{};!function(e,o,i){var t=/iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,n=/Pad/.test(navigator.userAgent)&&!window.MSStream;e(document).on("videoBlock.reAttach",(function(e,i){o.behaviors.videoBlock.attach(i)})),e(document).on("video-ended-final","#foreground-node.colorbox--video",(function(){i.overlay.hide()})),o.behaviors.videoBlock={observer:null,setupObserver:function(){var e=this;if(!e.observer){e.observer=new IntersectionObserver((function(o){_.each(o,(function(o){if(o.isIntersecting){var i=o.target;e.initializeVideo(i)}}))}),{root:null,rootMargin:"0px",threshold:[.1]})}},initializeVideo:function(o){var i=e(o);this.observer.unobserve(o),i.data("video-manager").init()},attach:function(o){var a=this;this.setupObserver(),e(".js-video-block",o).each((function(){var o=e(this);a.getDom(o),o.nodes.$playButton.attr("tabindex","0"),o.nodes.$playButton.on("keyup",(function(o){"Enter"===o.key&&e(this).trigger("click")})),0!==o.nodes.$videoBlock.length&&(o.nodes.$videoBlock.on("video-started",(function(){o.nodes.$videoBlock.closest(".js-video-block").addClass("playing-video"),o.nodes.$videoBlock.closest(".js-video-block").closest(".js-hero-block-media-wrapper").addClass("playing-video")})),o.nodes.$videoBlock.on("video-ended, video-paused",(function(){e(this).closest(".js-video-block").removeClass("playing-video"),e(this).closest(".js-video-block").closest(".js-hero-block-media-wrapper").removeClass("playing-video")})),(t||o.settings.playInline&&n)&&a.observer.observe(o.nodes.$videoBlock.get(0)),o.settings.mute&&o.settings.playInline&&o.nodes.$videoJS.attr("muted",!0),o.settings.autoplay&&o.settings.playInline&&(new MantleVideo.MantleVideoPlayer(o.nodes.$videoPlayer),o.nodes.$videoJS.attr("autoplay",1),o.nodes.$videoBlock.data("video-manager").init()),o.settings.playInline||(t&&o.nodes.$videoJS.removeAttr("playsinline"),o.off("start-video.videoBlock").on("start-video.videoBlock",".js-videojs-video",(function(a){var s=e(this).data("video-manager");if(a.stopPropagation(),t)s.startVideo();else{var d=s.clone(),l={content:d,cssClass:"colorbox--video "+o.attr("class"),hideOnClickOutside:!0,includeBackground:!0,backgroundNodeClickHide:!0,cssStyle:{width:"100%",maxWidth:1024,maxHeight:768},onShow:function(){var e=d.data("video-manager");e.init(),n||e.startVideo()}};i.overlay.launch(l)}}))))}))},getDom:function(o){o.nodes={},o.settings={},o.nodes.$videoBlock=e(".js-videojs-video",o),o.nodes.$videoJS=e("elc-video-js, .video-js",o.nodes.$videoBlock),o.nodes.$videoPlayer=MantleVideo.MantleVideoPlayer.getVideoPlayerDom(o),o.nodes.$posterImages=e(".js-videojs-landing__image img",o),o.nodes.$playButton=e(".js-videojs-landing__play",o.nodes.$videoBlock),o.settings.playInline=o.data("play-inline"),o.settings.autoplay=o.data("autoplay-video"),o.settings.mute=o.data("mute-video-on-loading")}}}(jQuery,Drupal,window.generic||{});
;
/*!
* jQuery Cycle2; build: v20131022
* http://jquery.malsup.com/cycle2/
* Copyright (c) 2013 M. Alsup; Dual licensed: MIT/GPL
*/
/*! core engine; version: 20131003 */
(function(e){"use strict";function t(e){return(e||"").toLowerCase()}var i="20131003";e.fn.cycle=function(i){var n;return 0!==this.length||e.isReady?this.each(function(){var n,s,o,c,r=e(this),l=e.fn.cycle.log;if(!r.data("cycle.opts")){(r.data("cycle-log")===!1||i&&i.log===!1||s&&s.log===!1)&&(l=e.noop),l("--c2 init--"),n=r.data();for(var a in n)n.hasOwnProperty(a)&&/^cycle[A-Z]+/.test(a)&&(c=n[a],o=a.match(/^cycle(.*)/)[1].replace(/^[A-Z]/,t),l(o+":",c,"("+typeof c+")"),n[o]=c);s=e.extend({},e.fn.cycle.defaults,n,i||{}),s.timeoutId=0,s.paused=s.paused||!1,s.container=r,s._maxZ=s.maxZ,s.API=e.extend({_container:r},e.fn.cycle.API),s.API.log=l,s.API.trigger=function(e,t){return s.container.trigger(e,t),s.API},r.data("cycle.opts",s),r.data("cycle.API",s.API),s.API.trigger("cycle-bootstrap",[s,s.API]),s.API.addInitialSlides(),s.API.preInitSlideshow(),s.slides.length&&s.API.initSlideshow()}}):(n={s:this.selector,c:this.context},e.fn.cycle.log("requeuing slideshow (dom not ready)"),e(function(){e(n.s,n.c).cycle(i)}),this)},e.fn.cycle.API={opts:function(){return this._container.data("cycle.opts")},addInitialSlides:function(){var t=this.opts(),i=t.slides;t.slideCount=0,t.slides=e(),i=i.jquery?i:t.container.find(i),t.random&&i.sort(function(){return Math.random()-.5}),t.API.add(i)},preInitSlideshow:function(){var t=this.opts();t.API.trigger("cycle-pre-initialize",[t]);var i=e.fn.cycle.transitions[t.fx];i&&e.isFunction(i.preInit)&&i.preInit(t),t._preInitialized=!0},postInitSlideshow:function(){var t=this.opts();t.API.trigger("cycle-post-initialize",[t]);var i=e.fn.cycle.transitions[t.fx];i&&e.isFunction(i.postInit)&&i.postInit(t)},initSlideshow:function(){var t,i=this.opts(),n=i.container;i.API.calcFirstSlide(),"static"==i.container.css("position")&&i.container.css("position","relative"),e(i.slides[i.currSlide]).css("opacity",1).show(),i.API.stackSlides(i.slides[i.currSlide],i.slides[i.nextSlide],!i.reverse),i.pauseOnHover&&(i.pauseOnHover!==!0&&(n=e(i.pauseOnHover)),n.hover(function(){i.API.pause(!0)},function(){i.API.resume(!0)})),i.timeout&&(t=i.API.getSlideOpts(i.currSlide),i.API.queueTransition(t,t.timeout+i.delay)),i._initialized=!0,i.API.updateView(!0),i.API.trigger("cycle-initialized",[i]),i.API.postInitSlideshow()},pause:function(t){var i=this.opts(),n=i.API.getSlideOpts(),s=i.hoverPaused||i.paused;t?i.hoverPaused=!0:i.paused=!0,s||(i.container.addClass("cycle-paused"),i.API.trigger("cycle-paused",[i]).log("cycle-paused"),n.timeout&&(clearTimeout(i.timeoutId),i.timeoutId=0,i._remainingTimeout-=e.now()-i._lastQueue,(0>i._remainingTimeout||isNaN(i._remainingTimeout))&&(i._remainingTimeout=void 0)))},resume:function(e){var t=this.opts(),i=!t.hoverPaused&&!t.paused;e?t.hoverPaused=!1:t.paused=!1,i||(t.container.removeClass("cycle-paused"),0===t.slides.filter(":animated").length&&t.API.queueTransition(t.API.getSlideOpts(),t._remainingTimeout),t.API.trigger("cycle-resumed",[t,t._remainingTimeout]).log("cycle-resumed"))},add:function(t,i){var n,s=this.opts(),o=s.slideCount,c=!1;"string"==e.type(t)&&(t=e.trim(t)),e(t).each(function(){var t,n=e(this);i?s.container.prepend(n):s.container.append(n),s.slideCount++,t=s.API.buildSlideOpts(n),s.slides=i?e(n).add(s.slides):s.slides.add(n),s.API.initSlide(t,n,--s._maxZ),n.data("cycle.opts",t),s.API.trigger("cycle-slide-added",[s,t,n])}),s.API.updateView(!0),c=s._preInitialized&&2>o&&s.slideCount>=1,c&&(s._initialized?s.timeout&&(n=s.slides.length,s.nextSlide=s.reverse?n-1:1,s.timeoutId||s.API.queueTransition(s)):s.API.initSlideshow())},calcFirstSlide:function(){var e,t=this.opts();e=parseInt(t.startingSlide||0,10),(e>=t.slides.length||0>e)&&(e=0),t.currSlide=e,t.reverse?(t.nextSlide=e-1,0>t.nextSlide&&(t.nextSlide=t.slides.length-1)):(t.nextSlide=e+1,t.nextSlide==t.slides.length&&(t.nextSlide=0))},calcNextSlide:function(){var e,t=this.opts();t.reverse?(e=0>t.nextSlide-1,t.nextSlide=e?t.slideCount-1:t.nextSlide-1,t.currSlide=e?0:t.nextSlide+1):(e=t.nextSlide+1==t.slides.length,t.nextSlide=e?0:t.nextSlide+1,t.currSlide=e?t.slides.length-1:t.nextSlide-1)},calcTx:function(t,i){var n,s=t;return i&&s.manualFx&&(n=e.fn.cycle.transitions[s.manualFx]),n||(n=e.fn.cycle.transitions[s.fx]),n||(n=e.fn.cycle.transitions.fade,s.API.log('Transition "'+s.fx+'" not found. Using fade.')),n},prepareTx:function(e,t){var i,n,s,o,c,r=this.opts();return 2>r.slideCount?(r.timeoutId=0,void 0):(!e||r.busy&&!r.manualTrump||(r.API.stopTransition(),r.busy=!1,clearTimeout(r.timeoutId),r.timeoutId=0),r.busy||(0!==r.timeoutId||e)&&(n=r.slides[r.currSlide],s=r.slides[r.nextSlide],o=r.API.getSlideOpts(r.nextSlide),c=r.API.calcTx(o,e),r._tx=c,e&&void 0!==o.manualSpeed&&(o.speed=o.manualSpeed),r.nextSlide!=r.currSlide&&(e||!r.paused&&!r.hoverPaused&&r.timeout)?(r.API.trigger("cycle-before",[o,n,s,t]),c.before&&c.before(o,n,s,t),i=function(){r.busy=!1,r.container.data("cycle.opts")&&(c.after&&c.after(o,n,s,t),r.API.trigger("cycle-after",[o,n,s,t]),r.API.queueTransition(o),r.API.updateView(!0))},r.busy=!0,c.transition?c.transition(o,n,s,t,i):r.API.doTransition(o,n,s,t,i),r.API.calcNextSlide(),r.API.updateView()):r.API.queueTransition(o)),void 0)},doTransition:function(t,i,n,s,o){var c=t,r=e(i),l=e(n),a=function(){l.animate(c.animIn||{opacity:1},c.speed,c.easeIn||c.easing,o)};l.css(c.cssBefore||{}),r.animate(c.animOut||{},c.speed,c.easeOut||c.easing,function(){r.css(c.cssAfter||{}),c.sync||a()}),c.sync&&a()},queueTransition:function(t,i){var n=this.opts(),s=void 0!==i?i:t.timeout;return 0===n.nextSlide&&0===--n.loop?(n.API.log("terminating; loop=0"),n.timeout=0,s?setTimeout(function(){n.API.trigger("cycle-finished",[n])},s):n.API.trigger("cycle-finished",[n]),n.nextSlide=n.currSlide,void 0):(s&&(n._lastQueue=e.now(),void 0===i&&(n._remainingTimeout=t.timeout),n.paused||n.hoverPaused||(n.timeoutId=setTimeout(function(){n.API.prepareTx(!1,!n.reverse)},s))),void 0)},stopTransition:function(){var e=this.opts();e.slides.filter(":animated").length&&(e.slides.stop(!1,!0),e.API.trigger("cycle-transition-stopped",[e])),e._tx&&e._tx.stopTransition&&e._tx.stopTransition(e)},advanceSlide:function(e){var t=this.opts();return clearTimeout(t.timeoutId),t.timeoutId=0,t.nextSlide=t.currSlide+e,0>t.nextSlide?t.nextSlide=t.slides.length-1:t.nextSlide>=t.slides.length&&(t.nextSlide=0),t.API.prepareTx(!0,e>=0),!1},buildSlideOpts:function(i){var n,s,o=this.opts(),c=i.data()||{};for(var r in c)c.hasOwnProperty(r)&&/^cycle[A-Z]+/.test(r)&&(n=c[r],s=r.match(/^cycle(.*)/)[1].replace(/^[A-Z]/,t),o.API.log("["+(o.slideCount-1)+"]",s+":",n,"("+typeof n+")"),c[s]=n);c=e.extend({},e.fn.cycle.defaults,o,c),c.slideNum=o.slideCount;try{delete c.API,delete c.slideCount,delete c.currSlide,delete c.nextSlide,delete c.slides}catch(l){}return c},getSlideOpts:function(t){var i=this.opts();void 0===t&&(t=i.currSlide);var n=i.slides[t],s=e(n).data("cycle.opts");return e.extend({},i,s)},initSlide:function(t,i,n){var s=this.opts();i.css(t.slideCss||{}),n>0&&i.css("zIndex",n),isNaN(t.speed)&&(t.speed=e.fx.speeds[t.speed]||e.fx.speeds._default),t.sync||(t.speed=t.speed/2),i.addClass(s.slideClass)},updateView:function(e,t){var i=this.opts();if(i._initialized){var n=i.API.getSlideOpts(),s=i.slides[i.currSlide];!e&&t!==!0&&(i.API.trigger("cycle-update-view-before",[i,n,s]),0>i.updateView)||(i.slideActiveClass&&i.slides.removeClass(i.slideActiveClass).eq(i.currSlide).addClass(i.slideActiveClass),e&&i.hideNonActive&&i.slides.filter(":not(."+i.slideActiveClass+")").hide(),0===i.updateView&&setTimeout(function(){i.API.trigger("cycle-update-view",[i,n,s,e])},n.speed/(i.sync?2:1)),0!==i.updateView&&i.API.trigger("cycle-update-view",[i,n,s,e]),e&&i.API.trigger("cycle-update-view-after",[i,n,s]))}},getComponent:function(t){var i=this.opts(),n=i[t];return"string"==typeof n?/^\s*[\>|\+|~]/.test(n)?i.container.find(n):e(n):n.jquery?n:e(n)},stackSlides:function(t,i,n){var s=this.opts();t||(t=s.slides[s.currSlide],i=s.slides[s.nextSlide],n=!s.reverse),e(t).css("zIndex",s.maxZ);var o,c=s.maxZ-2,r=s.slideCount;if(n){for(o=s.currSlide+1;r>o;o++)e(s.slides[o]).css("zIndex",c--);for(o=0;s.currSlide>o;o++)e(s.slides[o]).css("zIndex",c--)}else{for(o=s.currSlide-1;o>=0;o--)e(s.slides[o]).css("zIndex",c--);for(o=r-1;o>s.currSlide;o--)e(s.slides[o]).css("zIndex",c--)}e(i).css("zIndex",s.maxZ-1)},getSlideIndex:function(e){return this.opts().slides.index(e)}},e.fn.cycle.log=function(){window.console&&console.log&&console.log("[cycle2] "+Array.prototype.join.call(arguments," "))},e.fn.cycle.version=function(){return"Cycle2: "+i},e.fn.cycle.transitions={custom:{},none:{before:function(e,t,i,n){e.API.stackSlides(i,t,n),e.cssBefore={opacity:1,display:"block"}}},fade:{before:function(t,i,n,s){var o=t.API.getSlideOpts(t.nextSlide).slideCss||{};t.API.stackSlides(i,n,s),t.cssBefore=e.extend(o,{opacity:0,display:"block"}),t.animIn={opacity:1},t.animOut={opacity:0}}},fadeout:{before:function(t,i,n,s){var o=t.API.getSlideOpts(t.nextSlide).slideCss||{};t.API.stackSlides(i,n,s),t.cssBefore=e.extend(o,{opacity:1,display:"block"}),t.animOut={opacity:0}}},scrollHorz:{before:function(e,t,i,n){e.API.stackSlides(t,i,n);var s=e.container.css("overflow","hidden").width();e.cssBefore={left:n?s:-s,top:0,opacity:1,display:"block"},e.cssAfter={zIndex:e._maxZ-2,left:0},e.animIn={left:0},e.animOut={left:n?-s:s}}}},e.fn.cycle.defaults={allowWrap:!0,autoSelector:".cycle-slideshow[data-cycle-auto-init!=false]",delay:0,easing:null,fx:"fade",hideNonActive:!0,loop:0,manualFx:void 0,manualSpeed:void 0,manualTrump:!0,maxZ:100,pauseOnHover:!1,reverse:!1,slideActiveClass:"cycle-slide-active",slideClass:"cycle-slide",slideCss:{position:"absolute",top:0,left:0},slides:"> img",speed:500,startingSlide:0,sync:!0,timeout:4e3,updateView:0},e(document).ready(function(){e(e.fn.cycle.defaults.autoSelector).cycle()})})(jQuery),/*! Cycle2 autoheight plugin; Copyright (c) M.Alsup, 2012; version: 20130304 */
function(e){"use strict";function t(t,n){var s,o,c,r=n.autoHeight;if("container"==r)o=e(n.slides[n.currSlide]).outerHeight(),n.container.height(o);else if(n._autoHeightRatio)n.container.height(n.container.width()/n._autoHeightRatio);else if("calc"===r||"number"==e.type(r)&&r>=0){if(c="calc"===r?i(t,n):r>=n.slides.length?0:r,c==n._sentinelIndex)return;n._sentinelIndex=c,n._sentinel&&n._sentinel.remove(),s=e(n.slides[c].cloneNode(!0)),s.removeAttr("id name rel").find("[id],[name],[rel]").removeAttr("id name rel"),s.css({position:"static",visibility:"hidden",display:"block"}).prependTo(n.container).addClass("cycle-sentinel cycle-slide").removeClass("cycle-slide-active"),s.find("*").css("visibility","hidden"),n._sentinel=s}}function i(t,i){var n=0,s=-1;return i.slides.each(function(t){var i=e(this).height();i>s&&(s=i,n=t)}),n}function n(t,i,n,s){var o=e(s).outerHeight(),c=i.sync?i.speed/2:i.speed;i.container.animate({height:o},c)}function s(i,o){o._autoHeightOnResize&&(e(window).off("resize orientationchange",o._autoHeightOnResize),o._autoHeightOnResize=null),o.container.off("cycle-slide-added cycle-slide-removed",t),o.container.off("cycle-destroyed",s),o.container.off("cycle-before",n),o._sentinel&&(o._sentinel.remove(),o._sentinel=null)}e.extend(e.fn.cycle.defaults,{autoHeight:0}),e(document).on("cycle-initialized",function(i,o){function c(){t(i,o)}var r,l=o.autoHeight,a=e.type(l),d=null;("string"===a||"number"===a)&&(o.container.on("cycle-slide-added cycle-slide-removed",t),o.container.on("cycle-destroyed",s),"container"==l?o.container.on("cycle-before",n):"string"===a&&/\d+\:\d+/.test(l)&&(r=l.match(/(\d+)\:(\d+)/),r=r[1]/r[2],o._autoHeightRatio=r),"number"!==a&&(o._autoHeightOnResize=function(){clearTimeout(d),d=setTimeout(c,50)},e(window).on("resize orientationchange",o._autoHeightOnResize)),setTimeout(c,30))})}(jQuery),/*! caption plugin for Cycle2; version: 20130306 */
function(e){"use strict";e.extend(e.fn.cycle.defaults,{caption:"> .cycle-caption",captionTemplate:"{{slideNum}} / {{slideCount}}",overlay:"> .cycle-overlay",overlayTemplate:"
{{title}}
{{desc}}
",captionModule:"caption"}),e(document).on("cycle-update-view",function(t,i,n,s){"caption"===i.captionModule&&e.each(["caption","overlay"],function(){var e=this,t=n[e+"Template"],o=i.API.getComponent(e);o.length&&t?(o.html(i.API.tmpl(t,n,i,s)),o.show()):o.hide()})}),e(document).on("cycle-destroyed",function(t,i){var n;e.each(["caption","overlay"],function(){var e=this,t=i[e+"Template"];i[e]&&t&&(n=i.API.getComponent("caption"),n.empty())})})}(jQuery),/*! command plugin for Cycle2; version: 20130707 */
function(e){"use strict";var t=e.fn.cycle;e.fn.cycle=function(i){var n,s,o,c=e.makeArray(arguments);return"number"==e.type(i)?this.cycle("goto",i):"string"==e.type(i)?this.each(function(){var r;return n=i,o=e(this).data("cycle.opts"),void 0===o?(t.log('slideshow must be initialized before sending commands; "'+n+'" ignored'),void 0):(n="goto"==n?"jump":n,s=o.API[n],e.isFunction(s)?(r=e.makeArray(c),r.shift(),s.apply(o.API,r)):(t.log("unknown command: ",n),void 0))}):t.apply(this,arguments)},e.extend(e.fn.cycle,t),e.extend(t.API,{next:function(){var e=this.opts();if(!e.busy||e.manualTrump){var t=e.reverse?-1:1;e.allowWrap===!1&&e.currSlide+t>=e.slideCount||(e.API.advanceSlide(t),e.API.trigger("cycle-next",[e]).log("cycle-next"))}},prev:function(){var e=this.opts();if(!e.busy||e.manualTrump){var t=e.reverse?1:-1;e.allowWrap===!1&&0>e.currSlide+t||(e.API.advanceSlide(t),e.API.trigger("cycle-prev",[e]).log("cycle-prev"))}},destroy:function(){this.stop();var t=this.opts(),i=e.isFunction(e._data)?e._data:e.noop;clearTimeout(t.timeoutId),t.timeoutId=0,t.API.stop(),t.API.trigger("cycle-destroyed",[t]).log("cycle-destroyed"),t.container.removeData(),i(t.container[0],"parsedAttrs",!1),t.retainStylesOnDestroy||(t.container.removeAttr("style"),t.slides.removeAttr("style"),t.slides.removeClass(t.slideActiveClass)),t.slides.each(function(){e(this).removeData(),i(this,"parsedAttrs",!1)})},jump:function(e){var t,i=this.opts();if(!i.busy||i.manualTrump){var n=parseInt(e,10);if(isNaN(n)||0>n||n>=i.slides.length)return i.API.log("goto: invalid slide index: "+n),void 0;if(n==i.currSlide)return i.API.log("goto: skipping, already on slide",n),void 0;i.nextSlide=n,clearTimeout(i.timeoutId),i.timeoutId=0,i.API.log("goto: ",n," (zero-index)"),t=i.currSlider;r++)i=s.slides[r],r==t?n=i:(o.push(i),e(i).data("cycle.opts").slideNum=c,c++);n&&(s.slides=e(o),s.slideCount--,e(n).remove(),t==s.currSlide?s.API.advanceSlide(1):s.currSlide>t?s.currSlide--:s.currSlide++,s.API.trigger("cycle-slide-removed",[s,t,n]).log("cycle-slide-removed"),s.API.updateView())}}),e(document).on("click.cycle","[data-cycle-cmd]",function(t){t.preventDefault();var i=e(this),n=i.data("cycle-cmd"),s=i.data("cycle-context")||".cycle-slideshow";e(s).cycle(n,i.data("cycle-arg"))})}(jQuery),/*! hash plugin for Cycle2; version: 20130905 */
function(e){"use strict";function t(t,i){var n;return t._hashFence?(t._hashFence=!1,void 0):(n=window.location.hash.substring(1),t.slides.each(function(s){if(e(this).data("cycle-hash")==n){if(i===!0)t.startingSlide=s;else{var o=s>t.currSlide;t.nextSlide=s,t.API.prepareTx(!0,o)}return!1}}),void 0)}e(document).on("cycle-pre-initialize",function(i,n){t(n,!0),n._onHashChange=function(){t(n,!1)},e(window).on("hashchange",n._onHashChange)}),e(document).on("cycle-update-view",function(e,t,i){i.hash&&"#"+i.hash!=window.location.hash&&(t._hashFence=!0,window.location.hash=i.hash)}),e(document).on("cycle-destroyed",function(t,i){i._onHashChange&&e(window).off("hashchange",i._onHashChange)})}(jQuery),/*! loader plugin for Cycle2; version: 20131020 */
function(e){"use strict";e.extend(e.fn.cycle.defaults,{loader:!1}),e(document).on("cycle-bootstrap",function(t,i){function n(t,n){function o(t){var o;"wait"==i.loader?(r.push(t),0===a&&(r.sort(c),s.apply(i.API,[r,n]),i.container.removeClass("cycle-loading"))):(o=e(i.slides[i.currSlide]),s.apply(i.API,[t,n]),o.show(),i.container.removeClass("cycle-loading"))}function c(e,t){return e.data("index")-t.data("index")}var r=[];if("string"==e.type(t))t=e.trim(t);else if("array"===e.type(t))for(var l=0;t.length>l;l++)t[l]=e(t[l])[0];t=e(t);var a=t.length;a&&(i.eventualSlideCount=i.slideCount+a,t.hide().appendTo("body").each(function(t){function c(){0===--l&&(--a,o(d))}var l=0,d=e(this),u=d.is("img")?d:d.find("img");return d.data("index",t),u=u.filter(":not(.cycle-loader-ignore)").filter(':not([src=""])'),u.length?(l=u.length,u.each(function(){this.complete?c():e(this).load(function(){c()}).error(function(){0===--l&&(i.API.log("slide skipped; img not loaded:",this.src),0===--a&&"wait"==i.loader&&s.apply(i.API,[r,n]))})}),void 0):(--a,r.push(d),void 0)}),a&&i.container.addClass("cycle-loading"))}var s;i.loader&&(s=i.API.add,i.API.add=n)})}(jQuery),/*! pager plugin for Cycle2; version: 20130525 */
function(e){"use strict";function t(t,i,n){var s,o=t.API.getComponent("pager");o.each(function(){var o=e(this);if(i.pagerTemplate){var c=t.API.tmpl(i.pagerTemplate,i,t,n[0]);s=e(c).appendTo(o)}else s=o.children().eq(t.slideCount-1);s.on(t.pagerEvent,function(e){e.preventDefault(),t.API.page(o,e.currentTarget)})})}function i(e,t){var i=this.opts();if(!i.busy||i.manualTrump){var n=e.children().index(t),s=n,o=s>i.currSlide;i.currSlide!=s&&(i.nextSlide=s,i.API.prepareTx(!0,o),i.API.trigger("cycle-pager-activated",[i,e,t]))}}e.extend(e.fn.cycle.defaults,{pager:"> .cycle-pager",pagerActiveClass:"cycle-pager-active",pagerEvent:"click.cycle",pagerTemplate:"•"}),e(document).on("cycle-bootstrap",function(e,i,n){n.buildPagerLink=t}),e(document).on("cycle-slide-added",function(e,t,n,s){t.pager&&(t.API.buildPagerLink(t,n,s),t.API.page=i)}),e(document).on("cycle-slide-removed",function(t,i,n){if(i.pager){var s=i.API.getComponent("pager");s.each(function(){var t=e(this);e(t.children()[n]).remove()})}}),e(document).on("cycle-update-view",function(t,i){var n;i.pager&&(n=i.API.getComponent("pager"),n.each(function(){e(this).children().removeClass(i.pagerActiveClass).eq(i.currSlide).addClass(i.pagerActiveClass)}))}),e(document).on("cycle-destroyed",function(e,t){var i=t.API.getComponent("pager");i&&(i.children().off(t.pagerEvent),t.pagerTemplate&&i.empty())})}(jQuery),/*! prevnext plugin for Cycle2; version: 20130709 */
function(e){"use strict";e.extend(e.fn.cycle.defaults,{next:"> .cycle-next",nextEvent:"click.cycle",disabledClass:"disabled",prev:"> .cycle-prev",prevEvent:"click.cycle",swipe:!1}),e(document).on("cycle-initialized",function(e,t){if(t.API.getComponent("next").on(t.nextEvent,function(e){e.preventDefault(),t.API.next()}),t.API.getComponent("prev").on(t.prevEvent,function(e){e.preventDefault(),t.API.prev()}),t.swipe){var i=t.swipeVert?"swipeUp.cycle":"swipeLeft.cycle swipeleft.cycle",n=t.swipeVert?"swipeDown.cycle":"swipeRight.cycle swiperight.cycle";t.container.on(i,function(){t.API.next()}),t.container.on(n,function(){t.API.prev()})}}),e(document).on("cycle-update-view",function(e,t){if(!t.allowWrap){var i=t.disabledClass,n=t.API.getComponent("next"),s=t.API.getComponent("prev"),o=t._prevBoundry||0,c=void 0!==t._nextBoundry?t._nextBoundry:t.slideCount-1;t.currSlide==c?n.addClass(i).prop("disabled",!0):n.removeClass(i).prop("disabled",!1),t.currSlide===o?s.addClass(i).prop("disabled",!0):s.removeClass(i).prop("disabled",!1)}}),e(document).on("cycle-destroyed",function(e,t){t.API.getComponent("prev").off(t.nextEvent),t.API.getComponent("next").off(t.prevEvent),t.container.off("swipeleft.cycle swiperight.cycle swipeLeft.cycle swipeRight.cycle swipeUp.cycle swipeDown.cycle")})}(jQuery),/*! progressive loader plugin for Cycle2; version: 20130315 */
function(e){"use strict";e.extend(e.fn.cycle.defaults,{progressive:!1}),e(document).on("cycle-pre-initialize",function(t,i){if(i.progressive){var n,s,o=i.API,c=o.next,r=o.prev,l=o.prepareTx,a=e.type(i.progressive);if("array"==a)n=i.progressive;else if(e.isFunction(i.progressive))n=i.progressive(i);else if("string"==a){if(s=e(i.progressive),n=e.trim(s.html()),!n)return;if(/^(\[)/.test(n))try{n=e.parseJSON(n)}catch(d){return o.log("error parsing progressive slides",d),void 0}else n=n.split(RegExp(s.data("cycle-split")||"\n")),n[n.length-1]||n.pop()}l&&(o.prepareTx=function(e,t){var s,o;return e||0===n.length?(l.apply(i.API,[e,t]),void 0):(t&&i.currSlide==i.slideCount-1?(o=n[0],n=n.slice(1),i.container.one("cycle-slide-added",function(e,t){setTimeout(function(){t.API.advanceSlide(1)},50)}),i.API.add(o)):t||0!==i.currSlide?l.apply(i.API,[e,t]):(s=n.length-1,o=n[s],n=n.slice(0,s),i.container.one("cycle-slide-added",function(e,t){setTimeout(function(){t.currSlide=1,t.API.advanceSlide(-1)},50)}),i.API.add(o,!0)),void 0)}),c&&(o.next=function(){var e=this.opts();if(n.length&&e.currSlide==e.slideCount-1){var t=n[0];n=n.slice(1),e.container.one("cycle-slide-added",function(e,t){c.apply(t.API),t.container.removeClass("cycle-loading")}),e.container.addClass("cycle-loading"),e.API.add(t)}else c.apply(e.API)}),r&&(o.prev=function(){var e=this.opts();if(n.length&&0===e.currSlide){var t=n.length-1,i=n[t];n=n.slice(0,t),e.container.one("cycle-slide-added",function(e,t){t.currSlide=1,t.API.advanceSlide(-1),t.container.removeClass("cycle-loading")}),e.container.addClass("cycle-loading"),e.API.add(i,!0)}else r.apply(e.API)})}})}(jQuery),/*! tmpl plugin for Cycle2; version: 20121227 */
function(e){"use strict";e.extend(e.fn.cycle.defaults,{tmplRegex:"{{((.)?.*?)}}"}),e.extend(e.fn.cycle.API,{tmpl:function(t,i){var n=RegExp(i.tmplRegex||e.fn.cycle.defaults.tmplRegex,"g"),s=e.makeArray(arguments);return s.shift(),t.replace(n,function(t,i){var n,o,c,r,l=i.split(".");for(n=0;s.length>n;n++)if(c=s[n]){if(l.length>1)for(r=c,o=0;l.length>o;o++)c=r,r=r[l[o]]||i;else r=c[i];if(e.isFunction(r))return r.apply(c,s);if(void 0!==r&&null!==r&&r!=i)return r}return i})}})}(jQuery);
/* Plugin for Cycle2; Copyright (c) 2012 M. Alsup; v20130528 */
(function(e){"use strict";e(document).on("cycle-bootstrap",function(e,i,t){"carousel"===i.fx&&(t.getSlideIndex=function(e){var i=this.opts()._carouselWrap.children(),t=i.index(e);return t%i.length},t.next=function(){var e=i.reverse?-1:1;i.allowWrap===!1&&i.currSlide+e>i.slideCount-i.carouselVisible||(i.API.advanceSlide(e),i.API.trigger("cycle-next",[i]).log("cycle-next"))})}),e.fn.cycle.transitions.carousel={preInit:function(i){i.hideNonActive=!1,i.container.on("cycle-destroyed",e.proxy(this.onDestroy,i.API)),i.API.stopTransition=this.stopTransition;for(var t=0;i.startingSlide>t;t++)i.container.append(i.slides[0])},postInit:function(i){var t,n,s,o,l=i.carouselVertical;i.carouselVisible&&i.carouselVisible>i.slideCount&&(i.carouselVisible=i.slideCount-1);var r=i.carouselVisible||i.slides.length,c={display:l?"block":"inline-block",position:"static"};if(i.container.css({position:"relative",overflow:"hidden"}),i.slides.css(c),i._currSlide=i.currSlide,o=e('').prependTo(i.container).css({margin:0,padding:0,top:0,left:0,position:"absolute"}).append(i.slides),i._carouselWrap=o,l||o.css("white-space","nowrap"),i.allowWrap!==!1){for(n=0;(void 0===i.carouselVisible?2:1)>n;n++){for(t=0;i.slideCount>t;t++)o.append(i.slides[t].cloneNode(!0));for(t=i.slideCount;t--;)o.prepend(i.slides[t].cloneNode(!0))}o.find(".cycle-slide-active").removeClass("cycle-slide-active"),i.slides.eq(i.startingSlide).addClass("cycle-slide-active")}i.pager&&i.allowWrap===!1&&(s=i.slideCount-r,e(i.pager).children().filter(":gt("+s+")").hide()),i._nextBoundry=i.slideCount-i.carouselVisible,this.prepareDimensions(i)},prepareDimensions:function(i){var t,n,s,o=i.carouselVertical,l=i.carouselVisible||i.slides.length;if(i.carouselFluid&&i.carouselVisible?i._carouselResizeThrottle||this.fluidSlides(i):i.carouselVisible&&i.carouselSlideDimension?(t=l*i.carouselSlideDimension,i.container[o?"height":"width"](t)):i.carouselVisible&&(t=l*e(i.slides[0])[o?"outerHeight":"outerWidth"](!0),i.container[o?"height":"width"](t)),n=i.carouselOffset||0,i.allowWrap!==!1)if(i.carouselSlideDimension)n-=(i.slideCount+i.currSlide)*i.carouselSlideDimension;else{s=i._carouselWrap.children();for(var r=0;i.slideCount+i.currSlide>r;r++)n-=e(s[r])[o?"outerHeight":"outerWidth"](!0)}i._carouselWrap.css(o?"top":"left",n)},fluidSlides:function(i){function t(){clearTimeout(s),s=setTimeout(n,20)}function n(){i._carouselWrap.stop(!1,!0);var e=i.container.width()/i.carouselVisible;e=Math.ceil(e-l),i._carouselWrap.children().width(e),i._sentinel&&i._sentinel.width(e),r(i)}var s,o=i.slides.eq(0),l=o.outerWidth()-o.width(),r=this.prepareDimensions;e(window).on("resize",t),i._carouselResizeThrottle=t,n()},transition:function(i,t,n,s,o){var l,r={},c=i.nextSlide-i.currSlide,a=i.carouselVertical,d=i.speed;if(i.allowWrap===!1){s=c>0;var u=i._currSlide,p=i.slideCount-i.carouselVisible;c>0&&i.nextSlide>p&&u==p?c=0:c>0&&i.nextSlide>p?c=i.nextSlide-u-(i.nextSlide-p):0>c&&i.currSlide>p&&i.nextSlide>p?c=0:0>c&&i.currSlide>p?c+=i.currSlide-p:u=i.currSlide,l=this.getScroll(i,a,u,c),i.API.opts()._currSlide=i.nextSlide>p?p:i.nextSlide}else s&&0===i.nextSlide?(l=this.getDim(i,i.currSlide,a),o=this.genCallback(i,s,a,o)):s||i.nextSlide!=i.slideCount-1?l=this.getScroll(i,a,i.currSlide,c):(l=this.getDim(i,i.currSlide,a),o=this.genCallback(i,s,a,o));r[a?"top":"left"]=s?"-="+l:"+="+l,i.throttleSpeed&&(d=l/e(i.slides[0])[a?"height":"width"]()*i.speed),i._carouselWrap.animate(r,d,i.easing,o)},getDim:function(i,t,n){var s=e(i.slides[t]);return s[n?"outerHeight":"outerWidth"](!0)},getScroll:function(e,i,t,n){var s,o=0;if(n>0)for(s=t;t+n>s;s++)o+=this.getDim(e,s,i);else for(s=t;s>t+n;s--)o+=this.getDim(e,s,i);return o},genCallback:function(i,t,n,s){return function(){var t=e(i.slides[i.nextSlide]).position(),o=0-t[n?"top":"left"]+(i.carouselOffset||0);i._carouselWrap.css(i.carouselVertical?"top":"left",o),s()}},stopTransition:function(){var e=this.opts();e.slides.stop(!1,!0),e._carouselWrap.stop(!1,!0)},onDestroy:function(){var i=this.opts();i._carouselResizeThrottle&&e(window).off("resize",i._carouselResizeThrottle),i.slides.prependTo(i.container),i._carouselWrap.remove()}}})(jQuery);;
/*!
* The Final Countdown for jQuery v2.0.4 (http://hilios.github.io/jQuery.countdown/)
* Copyright (c) 2014 Edson Hilios
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var startTimeInMilliSec;!function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)}((function(t){"use strict";var e=[],s=[];function i(t){if(t instanceof Date)return t;if(String(t).match(s))return String(t).match(/^[0-9]*$/)&&(t=Number(t)),String(t).match(/\-/)&&(t=String(t).replace(/\-/g,"/")),new Date(t);throw new Error("Couldn't cast `"+t+"` to a date object.")}s.push(/^[0-9]*$/.source),s.push(/([0-9]{1,2}\/){2}[0-9]{4}( [0-9]{1,2}(:[0-9]{2}){2})?/.source),s.push(/[0-9]{4}([\/\-][0-9]{1,2}){2}( [0-9]{1,2}(:[0-9]{2}){2})?/.source),s=new RegExp(s.join("|"));var n={Y:"years",m:"months",w:"weeks",d:"days",D:"totalDays",H:"hours",M:"minutes",S:"seconds"};function a(t,e){var s="s",i="";return t&&(1===(t=t.replace(/(:|;|\s)/gi,"").split(/\,/)).length?s=t[0]:(i=t[0],s=t[1])),1===Math.abs(e)?i:s}var o=function(s,i,n,a){this.el=s,this.$el=t(s),this.interval=null,this.offset={},this.instanceNumber=e.length,e.push(this),this.$el.data("countdown-instance",this.instanceNumber),a&&(this.$el.on("update.countdown",a),this.$el.on("stoped.countdown",a),this.$el.on("finish.countdown",a)),this.setFinalDate(n),this.setStartDate(i),this.start()};t.extend(o.prototype,{start:function(){null!==this.interval&&clearInterval(this.interval);var t=this;this.update(),this.interval=setInterval((function(){t.update.call(t),startTimeInMilliSec=parseInt(startTimeInMilliSec)+1e3}),1e3)},stop:function(){clearInterval(this.interval),this.interval=null,this.dispatchEvent("stoped")},pause:function(){this.stop.call(this)},resume:function(){this.start.call(this)},remove:function(){this.stop(),e[this.instanceNumber]=null,delete this.$el.data().countdownInstance},setFinalDate:function(t){this.finalDate=i(t)},setStartDate:function(t){this.startDate=i(t),startTimeInMilliSec=this.startDate.getTime()},update:function(){0!==this.$el.closest("html").length?(this.totalSecsLeft=this.finalDate.getTime()-startTimeInMilliSec,this.totalSecsLeft=Math.ceil(this.totalSecsLeft/1e3),this.totalSecsLeft=this.totalSecsLeft<0?0:this.totalSecsLeft,this.offset={seconds:this.totalSecsLeft%60,minutes:Math.floor(this.totalSecsLeft/60)%60,hours:Math.floor(this.totalSecsLeft/60/60)%24,days:Math.floor(this.totalSecsLeft/60/60/24)%7,totalDays:Math.floor(this.totalSecsLeft/60/60/24),weeks:Math.floor(this.totalSecsLeft/60/60/24/7),months:Math.floor(this.totalSecsLeft/60/60/24/30),years:Math.floor(this.totalSecsLeft/60/60/24/365)},0===this.totalSecsLeft?(this.stop(),this.dispatchEvent("finish")):this.dispatchEvent("update")):this.remove()},dispatchEvent:function(e){var s,i=t.Event(e+".countdown");i.finalDate=this.finalDate,i.startDate=this.startDate,i.offset=t.extend({},this.offset),i.strftime=(s=this.offset,function(t){var e=t.match(/%(-|!)?[A-Z]{1}(:[^;]+;)?/gi);if(e)for(var i=0,o=e.length;i