r.width&&(c=r.width),c=Math.round(c),this.el_.style.right=`-${c}px`,this.write(i)}write(e){Ei(this.el_,e)}updateTime(e,t,i,r){this.requestNamedAnimationFrame("TimeTooltip#updateTime",()=>{let n;const a=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){const o=this.player_.liveTracker.liveWindow(),u=o-t*o;n=(u<1?"":"-")+Zi(u,o)}else n=Zi(i,a);this.update(e,t,n),r&&r()})}}B.registerComponent("TimeTooltip",cA);class $u extends B{constructor(e,t){super(e,t),this.setIcon("circle"),this.update=zt(de(this,this.update),Et)}createEl(){return super.createEl("div",{className:"vjs-play-progress vjs-slider-bar"},{"aria-hidden":"true"})}update(e,t){const i=this.getChild("timeTooltip");if(!i)return;const r=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();i.updateTime(e,t,r)}}$u.prototype.options_={children:[]};!st&&!Ht&&$u.prototype.options_.children.push("timeTooltip");B.registerComponent("PlayProgressBar",$u);class Dm extends B{constructor(e,t){super(e,t),this.update=zt(de(this,this.update),Et)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t){const i=t*this.player_.duration();this.getChild("timeTooltip").updateTime(e,t,i,()=>{this.el_.style.left=`${e.width*t}px`})}}Dm.prototype.options_={children:["timeTooltip"]};B.registerComponent("MouseTimeDisplay",Dm);const Wn=5,yh=12;class ju extends Uu{constructor(e,t){super(e,t),this.setEventHandlers_()}setEventHandlers_(){this.update_=de(this,this.update),this.update=zt(this.update_,Et),this.on(this.player_,["durationchange","timeupdate"],this.update),this.on(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.on(this.player_.liveTracker,"liveedgechange",this.update),this.updateInterval=null,this.enableIntervalHandler_=e=>this.enableInterval_(e),this.disableIntervalHandler_=e=>this.disableInterval_(e),this.on(this.player_,["playing"],this.enableIntervalHandler_),this.on(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in $&&"visibilityState"in $&&this.on($,"visibilitychange",this.toggleVisibility_)}toggleVisibility_(e){$.visibilityState==="hidden"?(this.cancelNamedAnimationFrame("SeekBar#update"),this.cancelNamedAnimationFrame("Slider#update"),this.disableInterval_(e)):(!this.player_.ended()&&!this.player_.paused()&&this.enableInterval_(),this.update())}enableInterval_(){this.updateInterval||(this.updateInterval=this.setInterval(this.update,Et))}disableInterval_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&e&&e.type!=="ended"||this.updateInterval&&(this.clearInterval(this.updateInterval),this.updateInterval=null)}createEl(){return super.createEl("div",{className:"vjs-progress-holder"},{"aria-label":this.localize("Progress Bar")})}update(e){if($.visibilityState==="hidden")return;const t=super.update();return this.requestNamedAnimationFrame("SeekBar#update",()=>{const i=this.player_.ended()?this.player_.duration():this.getCurrentTime_(),r=this.player_.liveTracker;let n=this.player_.duration();r&&r.isLive()&&(n=this.player_.liveTracker.liveCurrentTime()),this.percent_!==t&&(this.el_.setAttribute("aria-valuenow",(t*100).toFixed(2)),this.percent_=t),(this.currentTime_!==i||this.duration_!==n)&&(this.el_.setAttribute("aria-valuetext",this.localize("progress bar timing: currentTime={1} duration={2}",[Zi(i,n),Zi(n,n)],"{1} of {2}")),this.currentTime_=i,this.duration_=n),this.bar&&this.bar.update(js(this.el()),this.getProgress())}),t}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}getCurrentTime_(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime()}getPercent(){const e=this.getCurrentTime_();let t;const i=this.player_.liveTracker;return i&&i.isLive()?(t=(e-i.seekableStart())/i.liveWindow(),i.atLiveEdge()&&(t=1)):t=e/this.player_.duration(),t}handleMouseDown(e){Qr(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){if(!Qr(e)||isNaN(this.player_.duration()))return;!t&&!this.player_.scrubbing()&&this.player_.scrubbing(!0);let i;const r=this.calculateDistance(e),n=this.player_.liveTracker;if(!n||!n.isLive())i=r*this.player_.duration(),i===this.player_.duration()&&(i=i-.1);else{if(r>=.99){n.seekToLiveEdge();return}const a=n.seekableStart(),o=n.liveCurrentTime();if(i=a+r*n.liveWindow(),i>=o&&(i=o),i<=a&&(i=a+.1),i===1/0)return}this.userSeek_(i),this.player_.options_.enableSmoothSeeking&&this.update()}enable(){super.enable();const e=this.getChild("mouseTimeDisplay");e&&e.show()}disable(){super.disable();const e=this.getChild("mouseTimeDisplay");e&&e.hide()}handleMouseUp(e){super.handleMouseUp(e),e&&e.stopPropagation(),this.player_.scrubbing(!1),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0}),this.videoWasPlaying?Mt(this.player_.play()):this.update_()}stepForward(){this.userSeek_(this.player_.currentTime()+Wn)}stepBack(){this.userSeek_(this.player_.currentTime()-Wn)}handleAction(e){this.player_.paused()?this.player_.play():this.player_.pause()}handleKeyDown(e){const t=this.player_.liveTracker;if(e.key===" "||e.key==="Enter")e.preventDefault(),e.stopPropagation(),this.handleAction(e);else if(e.key==="Home")e.preventDefault(),e.stopPropagation(),this.userSeek_(0);else if(e.key==="End")e.preventDefault(),e.stopPropagation(),t&&t.isLive()?this.userSeek_(t.liveCurrentTime()):this.userSeek_(this.player_.duration());else if(/^[0-9]$/.test(e.key)){e.preventDefault(),e.stopPropagation();const i=parseInt(e.key,10)*.1;t&&t.isLive()?this.userSeek_(t.seekableStart()+t.liveWindow()*i):this.userSeek_(this.player_.duration()*i)}else e.key==="PageDown"?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()-Wn*yh)):e.key==="PageUp"?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()+Wn*yh)):super.handleKeyDown(e)}dispose(){this.disableInterval_(),this.off(this.player_,["durationchange","timeupdate"],this.update),this.off(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.update),this.off(this.player_,["playing"],this.enableIntervalHandler_),this.off(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in $&&"visibilityState"in $&&this.off($,"visibilitychange",this.toggleVisibility_),super.dispose()}}ju.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar"};!st&&!Ht&&ju.prototype.options_.children.splice(1,0,"mouseTimeDisplay");B.registerComponent("SeekBar",ju);class km extends B{constructor(e,t){super(e,t),this.handleMouseMove=zt(de(this,this.handleMouseMove),Et),this.throttledHandleMouseSeek=zt(de(this,this.handleMouseSeek),Et),this.handleMouseUpHandler_=i=>this.handleMouseUp(i),this.handleMouseDownHandler_=i=>this.handleMouseDown(i),this.enable()}createEl(){return super.createEl("div",{className:"vjs-progress-control vjs-control"})}handleMouseMove(e){const t=this.getChild("seekBar");if(!t)return;const i=t.getChild("playProgressBar"),r=t.getChild("mouseTimeDisplay");if(!i&&!r)return;const n=t.el(),a=Yr(n);let o=io(n,e).x;o=hn(o,0,1),r&&r.update(a,o),i&&i.update(a,t.getProgress())}handleMouseSeek(e){const t=this.getChild("seekBar");t&&t.handleMouseMove(e)}enabled(){return this.enabled_}disable(){if(this.children().forEach(e=>e.disable&&e.disable()),!!this.enabled()&&(this.off(["mousedown","touchstart"],this.handleMouseDownHandler_),this.off(this.el_,"mousemove",this.handleMouseMove),this.removeListenersAddedOnMousedownAndTouchstart(),this.addClass("disabled"),this.enabled_=!1,this.player_.scrubbing())){const e=this.getChild("seekBar");this.player_.scrubbing(!1),e.videoWasPlaying&&Mt(this.player_.play())}}enable(){this.children().forEach(e=>e.enable&&e.enable()),!this.enabled()&&(this.on(["mousedown","touchstart"],this.handleMouseDownHandler_),this.on(this.el_,"mousemove",this.handleMouseMove),this.removeClass("disabled"),this.enabled_=!0)}removeListenersAddedOnMousedownAndTouchstart(){const e=this.el_.ownerDocument;this.off(e,"mousemove",this.throttledHandleMouseSeek),this.off(e,"touchmove",this.throttledHandleMouseSeek),this.off(e,"mouseup",this.handleMouseUpHandler_),this.off(e,"touchend",this.handleMouseUpHandler_)}handleMouseDown(e){const t=this.el_.ownerDocument,i=this.getChild("seekBar");i&&i.handleMouseDown(e),this.on(t,"mousemove",this.throttledHandleMouseSeek),this.on(t,"touchmove",this.throttledHandleMouseSeek),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){const t=this.getChild("seekBar");t&&t.handleMouseUp(e),this.removeListenersAddedOnMousedownAndTouchstart()}}km.prototype.options_={children:["seekBar"]};B.registerComponent("ProgressControl",km);class Im extends Ge{constructor(e,t){super(e,t),this.setIcon("picture-in-picture-enter"),this.on(e,["enterpictureinpicture","leavepictureinpicture"],i=>this.handlePictureInPictureChange(i)),this.on(e,["disablepictureinpicturechanged","loadedmetadata"],i=>this.handlePictureInPictureEnabledChange(i)),this.on(e,["loadedmetadata","audioonlymodechange","audiopostermodechange"],()=>this.handlePictureInPictureAudioModeChange()),this.disable()}buildCSSClass(){return`vjs-picture-in-picture-control vjs-hidden ${super.buildCSSClass()}`}handlePictureInPictureAudioModeChange(){if(!(this.player_.currentType().substring(0,5)==="audio"||this.player_.audioPosterMode()||this.player_.audioOnlyMode())){this.show();return}this.player_.isInPictureInPicture()&&this.player_.exitPictureInPicture(),this.hide()}handlePictureInPictureEnabledChange(){$.pictureInPictureEnabled&&this.player_.disablePictureInPicture()===!1||this.player_.options_.enableDocumentPictureInPicture&&"documentPictureInPicture"in E?this.enable():this.disable()}handlePictureInPictureChange(e){this.player_.isInPictureInPicture()?(this.setIcon("picture-in-picture-exit"),this.controlText("Exit Picture-in-Picture")):(this.setIcon("picture-in-picture-enter"),this.controlText("Picture-in-Picture")),this.handlePictureInPictureEnabledChange()}handleClick(e){this.player_.isInPictureInPicture()?this.player_.exitPictureInPicture():this.player_.requestPictureInPicture()}show(){typeof $.exitPictureInPicture=="function"&&super.show()}}Im.prototype.controlText_="Picture-in-Picture";B.registerComponent("PictureInPictureToggle",Im);class Pm extends Ge{constructor(e,t){super(e,t),this.setIcon("fullscreen-enter"),this.on(e,"fullscreenchange",i=>this.handleFullscreenChange(i)),$[e.fsApi_.fullscreenEnabled]===!1&&this.disable()}buildCSSClass(){return`vjs-fullscreen-control ${super.buildCSSClass()}`}handleFullscreenChange(e){this.player_.isFullscreen()?(this.controlText("Exit Fullscreen"),this.setIcon("fullscreen-exit")):(this.controlText("Fullscreen"),this.setIcon("fullscreen-enter"))}handleClick(e){this.player_.isFullscreen()?this.player_.exitFullscreen():this.player_.requestFullscreen()}}Pm.prototype.controlText_="Fullscreen";B.registerComponent("FullscreenToggle",Pm);const dA=function(s,e){e.tech_&&!e.tech_.featuresVolumeControl&&s.addClass("vjs-hidden"),s.on(e,"loadstart",function(){e.tech_.featuresVolumeControl?s.removeClass("vjs-hidden"):s.addClass("vjs-hidden")})};class hA extends B{createEl(){const e=super.createEl("div",{className:"vjs-volume-level"});return this.setIcon("circle",e),e.appendChild(super.createEl("span",{className:"vjs-control-text"})),e}}B.registerComponent("VolumeLevel",hA);class fA extends B{constructor(e,t){super(e,t),this.update=zt(de(this,this.update),Et)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(e,t,i,r){if(!i){const n=js(this.el_),a=js(this.player_.el()),o=e.width*t;if(!a||!n)return;const u=e.left-a.left+o,c=e.width-o+(a.right-e.right);let p=n.width/2;un.width&&(p=n.width),this.el_.style.right=`-${p}px`}this.write(`${r}%`)}write(e){Ei(this.el_,e)}updateVolume(e,t,i,r,n){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",()=>{this.update(e,t,i,r.toFixed(0)),n&&n()})}}B.registerComponent("VolumeLevelTooltip",fA);class Lm extends B{constructor(e,t){super(e,t),this.update=zt(de(this,this.update),Et)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t,i){const r=100*t;this.getChild("volumeLevelTooltip").updateVolume(e,t,i,r,()=>{i?this.el_.style.bottom=`${e.height*t}px`:this.el_.style.left=`${e.width*t}px`})}}Lm.prototype.options_={children:["volumeLevelTooltip"]};B.registerComponent("MouseVolumeLevelDisplay",Lm);class uo extends Uu{constructor(e,t){super(e,t),this.on("slideractive",i=>this.updateLastVolume_(i)),this.on(e,"volumechange",i=>this.updateARIAAttributes(i)),e.ready(()=>this.updateARIAAttributes())}createEl(){return super.createEl("div",{className:"vjs-volume-bar vjs-slider-bar"},{"aria-label":this.localize("Volume Level"),"aria-live":"polite"})}handleMouseDown(e){Qr(e)&&super.handleMouseDown(e)}handleMouseMove(e){const t=this.getChild("mouseVolumeLevelDisplay");if(t){const i=this.el(),r=js(i),n=this.vertical();let a=io(i,e);a=n?a.y:a.x,a=hn(a,0,1),t.update(r,a,n)}Qr(e)&&(this.checkMuted(),this.player_.volume(this.calculateDistance(e)))}checkMuted(){this.player_.muted()&&this.player_.muted(!1)}getPercent(){return this.player_.muted()?0:this.player_.volume()}stepForward(){this.checkMuted(),this.player_.volume(this.player_.volume()+.1)}stepBack(){this.checkMuted(),this.player_.volume(this.player_.volume()-.1)}updateARIAAttributes(e){const t=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute("aria-valuenow",t),this.el_.setAttribute("aria-valuetext",t+"%")}volumeAsPercentage_(){return Math.round(this.player_.volume()*100)}updateLastVolume_(){const e=this.player_.volume();this.one("sliderinactive",()=>{this.player_.volume()===0&&this.player_.lastVolume_(e)})}}uo.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"};!st&&!Ht&&uo.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay");uo.prototype.playerEvent="volumechange";B.registerComponent("VolumeBar",uo);class Om extends B{constructor(e,t={}){t.vertical=t.vertical||!1,(typeof t.volumeBar>"u"||Us(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),dA(this,e),this.throttledHandleMouseMove=zt(de(this,this.handleMouseMove),Et),this.handleMouseUpHandler_=i=>this.handleMouseUp(i),this.on("mousedown",i=>this.handleMouseDown(i)),this.on("touchstart",i=>this.handleMouseDown(i)),this.on("mousemove",i=>this.handleMouseMove(i)),this.on(this.volumeBar,["focus","slideractive"],()=>{this.volumeBar.addClass("vjs-slider-active"),this.addClass("vjs-slider-active"),this.trigger("slideractive")}),this.on(this.volumeBar,["blur","sliderinactive"],()=>{this.volumeBar.removeClass("vjs-slider-active"),this.removeClass("vjs-slider-active"),this.trigger("sliderinactive")})}createEl(){let e="vjs-volume-horizontal";return this.options_.vertical&&(e="vjs-volume-vertical"),super.createEl("div",{className:`vjs-volume-control vjs-control ${e}`})}handleMouseDown(e){const t=this.el_.ownerDocument;this.on(t,"mousemove",this.throttledHandleMouseMove),this.on(t,"touchmove",this.throttledHandleMouseMove),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){const t=this.el_.ownerDocument;this.off(t,"mousemove",this.throttledHandleMouseMove),this.off(t,"touchmove",this.throttledHandleMouseMove),this.off(t,"mouseup",this.handleMouseUpHandler_),this.off(t,"touchend",this.handleMouseUpHandler_)}handleMouseMove(e){this.volumeBar.handleMouseMove(e)}}Om.prototype.options_={children:["volumeBar"]};B.registerComponent("VolumeControl",Om);const pA=function(s,e){e.tech_&&!e.tech_.featuresMuteControl&&s.addClass("vjs-hidden"),s.on(e,"loadstart",function(){e.tech_.featuresMuteControl?s.removeClass("vjs-hidden"):s.addClass("vjs-hidden")})};class Rm extends Ge{constructor(e,t){super(e,t),pA(this,e),this.on(e,["loadstart","volumechange"],i=>this.update(i))}buildCSSClass(){return`vjs-mute-control ${super.buildCSSClass()}`}handleClick(e){const t=this.player_.volume(),i=this.player_.lastVolume_();if(t===0){const r=i<.1?.1:i;this.player_.volume(r),this.player_.muted(!1)}else this.player_.muted(!this.player_.muted())}update(e){this.updateIcon_(),this.updateControlText_()}updateIcon_(){const e=this.player_.volume();let t=3;this.setIcon("volume-high"),st&&this.player_.tech_&&this.player_.tech_.el_&&this.player_.muted(this.player_.tech_.el_.muted),e===0||this.player_.muted()?(this.setIcon("volume-mute"),t=0):e<.33?(this.setIcon("volume-low"),t=1):e<.67&&(this.setIcon("volume-medium"),t=2),eo(this.el_,[0,1,2,3].reduce((i,r)=>i+`${r?" ":""}vjs-vol-${r}`,"")),zi(this.el_,`vjs-vol-${t}`)}updateControlText_(){const t=this.player_.muted()||this.player_.volume()===0?"Unmute":"Mute";this.controlText()!==t&&this.controlText(t)}}Rm.prototype.controlText_="Mute";B.registerComponent("MuteToggle",Rm);class Nm extends B{constructor(e,t={}){typeof t.inline<"u"?t.inline=t.inline:t.inline=!0,(typeof t.volumeControl>"u"||Us(t.volumeControl))&&(t.volumeControl=t.volumeControl||{},t.volumeControl.vertical=!t.inline),super(e,t),this.handleKeyPressHandler_=i=>this.handleKeyPress(i),this.on(e,["loadstart"],i=>this.volumePanelState_(i)),this.on(this.muteToggle,"keyup",i=>this.handleKeyPress(i)),this.on(this.volumeControl,"keyup",i=>this.handleVolumeControlKeyUp(i)),this.on("keydown",i=>this.handleKeyPress(i)),this.on("mouseover",i=>this.handleMouseOver(i)),this.on("mouseout",i=>this.handleMouseOut(i)),this.on(this.volumeControl,["slideractive"],this.sliderActive_),this.on(this.volumeControl,["sliderinactive"],this.sliderInactive_)}sliderActive_(){this.addClass("vjs-slider-active")}sliderInactive_(){this.removeClass("vjs-slider-active")}volumePanelState_(){this.volumeControl.hasClass("vjs-hidden")&&this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-hidden"),this.volumeControl.hasClass("vjs-hidden")&&!this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-mute-toggle-only")}createEl(){let e="vjs-volume-panel-horizontal";return this.options_.inline||(e="vjs-volume-panel-vertical"),super.createEl("div",{className:`vjs-volume-panel vjs-control ${e}`})}dispose(){this.handleMouseOut(),super.dispose()}handleVolumeControlKeyUp(e){e.key==="Escape"&&this.muteToggle.focus()}handleMouseOver(e){this.addClass("vjs-hover"),gt($,"keyup",this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass("vjs-hover"),ze($,"keyup",this.handleKeyPressHandler_)}handleKeyPress(e){e.key==="Escape"&&this.handleMouseOut()}}Nm.prototype.options_={children:["muteToggle","volumeControl"]};B.registerComponent("VolumePanel",Nm);class Mm extends Ge{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipForwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`forward-${this.skipTime}`),this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipForwardTime(){const e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.forward}buildCSSClass(){return`vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`}handleClick(e){if(isNaN(this.player_.duration()))return;const t=this.player_.currentTime(),i=this.player_.liveTracker,r=i&&i.isLive()?i.seekableEnd():this.player_.duration();let n;t+this.skipTime<=r?n=t+this.skipTime:n=r,this.player_.currentTime(n)}handleLanguagechange(){this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime]))}}Mm.prototype.controlText_="Skip Forward";B.registerComponent("SkipForward",Mm);class Bm extends Ge{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipBackwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`replay-${this.skipTime}`),this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipBackwardTime(){const e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.backward}buildCSSClass(){return`vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`}handleClick(e){const t=this.player_.currentTime(),i=this.player_.liveTracker,r=i&&i.isLive()&&i.seekableStart();let n;r&&t-this.skipTime<=r?n=r:t>=this.skipTime?n=t-this.skipTime:n=0,this.player_.currentTime(n)}handleLanguagechange(){this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime]))}}Bm.prototype.controlText_="Skip Backward";B.registerComponent("SkipBackward",Bm);class Fm extends B{constructor(e,t){super(e,t),t&&(this.menuButton_=t.menuButton),this.focusedChild_=-1,this.on("keydown",i=>this.handleKeyDown(i)),this.boundHandleBlur_=i=>this.handleBlur(i),this.boundHandleTapClick_=i=>this.handleTapClick(i)}addEventListenerForItem(e){e instanceof B&&(this.on(e,"blur",this.boundHandleBlur_),this.on(e,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof B&&(this.off(e,"blur",this.boundHandleBlur_),this.off(e,["tap","click"],this.boundHandleTapClick_))}removeChild(e){typeof e=="string"&&(e=this.getChild(e)),this.removeEventListenerForItem(e),super.removeChild(e)}addItem(e){const t=this.addChild(e);t&&this.addEventListenerForItem(t)}createEl(){const e=this.options_.contentElType||"ul";this.contentEl_=X(e,{className:"vjs-menu-content"}),this.contentEl_.setAttribute("role","menu");const t=super.createEl("div",{append:this.contentEl_,className:"vjs-menu"});return t.appendChild(this.contentEl_),gt(t,"click",function(i){i.preventDefault(),i.stopImmediatePropagation()}),t}dispose(){this.contentEl_=null,this.boundHandleBlur_=null,this.boundHandleTapClick_=null,super.dispose()}handleBlur(e){const t=e.relatedTarget||$.activeElement;if(!this.children().some(i=>i.el()===t)){const i=this.menuButton_;i&&i.buttonPressed_&&t!==i.el().firstChild&&i.unpressButton()}}handleTapClick(e){if(this.menuButton_){this.menuButton_.unpressButton();const t=this.children();if(!Array.isArray(t))return;const i=t.filter(r=>r.el()===e.target)[0];if(!i)return;i.name()!=="CaptionSettingsMenuItem"&&this.menuButton_.focus()}}handleKeyDown(e){e.key==="ArrowLeft"||e.key==="ArrowDown"?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(e.key==="ArrowRight"||e.key==="ArrowUp")&&(e.preventDefault(),e.stopPropagation(),this.stepBack())}stepForward(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_+1),this.focus(e)}stepBack(){let e=0;this.focusedChild_!==void 0&&(e=this.focusedChild_-1),this.focus(e)}focus(e=0){const t=this.children().slice();t.length&&t[0].hasClass("vjs-menu-title")&&t.shift(),t.length>0&&(e<0?e=0:e>=t.length&&(e=t.length-1),this.focusedChild_=e,t[e].el_.focus())}}B.registerComponent("Menu",Fm);class qu extends B{constructor(e,t={}){super(e,t),this.menuButton_=new Ge(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");const i=Ge.prototype.buildCSSClass();this.menuButton_.el_.className=this.buildCSSClass()+" "+i,this.menuButton_.removeClass("vjs-control"),this.addChild(this.menuButton_),this.update(),this.enabled_=!0;const r=n=>this.handleClick(n);this.handleMenuKeyUp_=n=>this.handleMenuKeyUp(n),this.on(this.menuButton_,"tap",r),this.on(this.menuButton_,"click",r),this.on(this.menuButton_,"keydown",n=>this.handleKeyDown(n)),this.on(this.menuButton_,"mouseenter",()=>{this.addClass("vjs-hover"),this.menu.show(),gt($,"keyup",this.handleMenuKeyUp_)}),this.on("mouseleave",n=>this.handleMouseLeave(n)),this.on("keydown",n=>this.handleSubmenuKeyDown(n))}update(){const e=this.createMenu();this.menu&&(this.menu.dispose(),this.removeChild(this.menu)),this.menu=e,this.addChild(e),this.buttonPressed_=!1,this.menuButton_.el_.setAttribute("aria-expanded","false"),this.items&&this.items.length<=this.hideThreshold_?(this.hide(),this.menu.contentEl_.removeAttribute("role")):(this.show(),this.menu.contentEl_.setAttribute("role","menu"))}createMenu(){const e=new Fm(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){const t=X("li",{className:"vjs-menu-title",textContent:Se(this.options_.title),tabIndex:-1}),i=new B(this.player_,{el:t});e.addItem(i)}if(this.items=this.createItems(),this.items)for(let t=0;t{this.handleTracksChange.apply(this,o)},a=(...o)=>{this.handleSelectedLanguageChange.apply(this,o)};if(e.on(["loadstart","texttrackchange"],n),r.addEventListener("change",n),r.addEventListener("selectedlanguagechange",a),this.on("dispose",function(){e.off(["loadstart","texttrackchange"],n),r.removeEventListener("change",n),r.removeEventListener("selectedlanguagechange",a)}),r.onchange===void 0){let o;this.on(["tap","click"],function(){if(typeof E.Event!="object")try{o=new E.Event("change")}catch{}o||(o=$.createEvent("Event"),o.initEvent("change",!0,!0)),r.dispatchEvent(o)})}this.handleTracksChange()}handleClick(e){const t=this.track,i=this.player_.textTracks();if(super.handleClick(e),!!i)for(let r=0;r-1&&a.mode==="showing"){i=!1;break}}i!==this.isSelected_&&this.selected(i)}handleSelectedLanguageChange(e){const t=this.player().textTracks();let i=!0;for(let r=0,n=t.length;r-1&&a.mode==="showing"){i=!1;break}}i&&(this.player_.cache_.selectedLanguage={enabled:!1})}handleLanguagechange(){this.$(".vjs-menu-item-text").textContent=this.player_.localize(this.options_.label),super.handleLanguagechange()}}B.registerComponent("OffTextTrackMenuItem",Um);class Zs extends Hu{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=pn){let i;this.label_&&(i=`${this.label_} off`),e.push(new Um(this.player_,{kinds:this.kinds_,kind:this.kind_,label:i})),this.hideThreshold_+=1;const r=this.player_.textTracks();Array.isArray(this.kinds_)||(this.kinds_=[this.kind_]);for(let n=0;n-1){const o=new t(this.player_,{track:a,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});o.addClass(`vjs-${a.kind}-menu-item`),e.push(o)}}return e}}B.registerComponent("TextTrackButton",Zs);class $m extends fn{constructor(e,t){const i=t.track,r=t.cue,n=e.currentTime();t.selectable=!0,t.multiSelectable=!1,t.label=r.text,t.selected=r.startTime<=n&&n{this.items.forEach(r=>{r.selected(this.track_.activeCues[0]===r.cue)})}}buildCSSClass(){return`vjs-chapters-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-chapters-button ${super.buildWrapperCSSClass()}`}update(e){if(e&&e.track&&e.track.kind!=="chapters")return;const t=this.findChaptersTrack();t!==this.track_?(this.setTrack(t),super.update()):(!this.items||t&&t.cues&&t.cues.length!==this.items.length)&&super.update()}setTrack(e){if(this.track_!==e){if(this.updateHandler_||(this.updateHandler_=this.update.bind(this)),this.track_){const t=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);t&&t.removeEventListener("load",this.updateHandler_),this.track_.removeEventListener("cuechange",this.selectCurrentItem_),this.track_=null}if(this.track_=e,this.track_){this.track_.mode="hidden";const t=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);t&&t.addEventListener("load",this.updateHandler_),this.track_.addEventListener("cuechange",this.selectCurrentItem_)}}}findChaptersTrack(){const e=this.player_.textTracks()||[];for(let t=e.length-1;t>=0;t--){const i=e[t];if(i.kind===this.kind_)return i}}getMenuCaption(){return this.track_&&this.track_.label?this.track_.label:this.localize(Se(this.kind_))}createMenu(){return this.options_.title=this.getMenuCaption(),super.createMenu()}createItems(){const e=[];if(!this.track_)return e;const t=this.track_.cues;if(!t)return e;for(let i=0,r=t.length;i-1&&(this.label_="captions",this.setIcon("captions")),this.menuButton_.controlText(Se(this.label_))}buildCSSClass(){return`vjs-subs-caps-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-subs-caps-button ${super.buildWrapperCSSClass()}`}createItems(){let e=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild("textTrackSettings")&&(e.push(new Wu(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,jm),e}}Xu.prototype.kinds_=["captions","subtitles"];Xu.prototype.controlText_="Subtitles";B.registerComponent("SubsCapsButton",Xu);class qm extends fn{constructor(e,t){const i=t.track,r=e.audioTracks();t.label=i.label||i.language||"Unknown",t.selected=i.enabled,super(e,t),this.track=i,this.addClass(`vjs-${i.kind}-menu-item`);const n=(...a)=>{this.handleTracksChange.apply(this,a)};r.addEventListener("change",n),this.on("dispose",()=>{r.removeEventListener("change",n)})}createEl(e,t,i){const r=super.createEl(e,t,i),n=r.querySelector(".vjs-menu-item-text");return["main-desc","descriptions"].indexOf(this.options_.track.kind)>=0&&(n.appendChild(X("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),n.appendChild(X("span",{className:"vjs-control-text",textContent:" "+this.localize("Descriptions")}))),r}handleClick(e){if(super.handleClick(e),this.track.enabled=!0,this.player_.tech_.featuresNativeAudioTracks){const t=this.player_.audioTracks();for(let i=0;ithis.update(n))}handleClick(e){super.handleClick(),this.player().playbackRate(this.rate)}update(e){this.selected(this.player().playbackRate()===this.rate)}}Yu.prototype.contentElType="button";B.registerComponent("PlaybackRateMenuItem",Yu);class Vm extends qu{constructor(e,t){super(e,t),this.menuButton_.el_.setAttribute("aria-describedby",this.labelElId_),this.updateVisibility(),this.updateLabel(),this.on(e,"loadstart",i=>this.updateVisibility(i)),this.on(e,"ratechange",i=>this.updateLabel(i)),this.on(e,"playbackrateschange",i=>this.handlePlaybackRateschange(i))}createEl(){const e=super.createEl();return this.labelElId_="vjs-playback-rate-value-label-"+this.id_,this.labelEl_=X("div",{className:"vjs-playback-rate-value",id:this.labelElId_,textContent:"1x"}),e.appendChild(this.labelEl_),e}dispose(){this.labelEl_=null,super.dispose()}buildCSSClass(){return`vjs-playback-rate ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-playback-rate ${super.buildWrapperCSSClass()}`}createItems(){const e=this.playbackRates(),t=[];for(let i=e.length-1;i>=0;i--)t.push(new Yu(this.player(),{rate:e[i]+"x"}));return t}handlePlaybackRateschange(e){this.update()}playbackRates(){const e=this.player();return e.playbackRates&&e.playbackRates()||[]}playbackRateSupported(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0}updateVisibility(e){this.playbackRateSupported()?this.removeClass("vjs-hidden"):this.addClass("vjs-hidden")}updateLabel(e){this.playbackRateSupported()&&(this.labelEl_.textContent=this.player().playbackRate()+"x")}}Vm.prototype.controlText_="Playback Rate";B.registerComponent("PlaybackRateMenuButton",Vm);class zm extends B{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e="div",t={},i={}){return t.className||(t.className=this.buildCSSClass()),super.createEl(e,t,i)}}B.registerComponent("Spacer",zm);class mA extends zm{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:" "})}}B.registerComponent("CustomControlSpacer",mA);class Gm extends B{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}Gm.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]};B.registerComponent("ControlBar",Gm);class Wm extends Qs{constructor(e,t){super(e,t),this.on(e,"error",i=>{this.open(i)})}buildCSSClass(){return`vjs-error-display ${super.buildCSSClass()}`}content(){const e=this.player().error();return e?this.localize(e.message):""}}Wm.prototype.options_=Object.assign({},Qs.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0});B.registerComponent("ErrorDisplay",Wm);class Km extends B{constructor(e,t={}){super(e,t),this.el_.setAttribute("aria-labelledby",this.selectLabelledbyIds)}createEl(){return this.selectLabelledbyIds=[this.options_.legendId,this.options_.labelId].join(" ").trim(),X("select",{id:this.options_.id},{},this.options_.SelectOptions.map(t=>{const i=(this.options_.labelId?this.options_.labelId:`vjs-track-option-${xt()}`)+"-"+t[1].replace(/\W+/g,""),r=X("option",{id:i,value:this.localize(t[0]),textContent:t[1]});return r.setAttribute("aria-labelledby",`${this.selectLabelledbyIds} ${i}`),r}))}}B.registerComponent("TextTrackSelect",Km);class Wi extends B{constructor(e,t={}){super(e,t);const i=X("legend",{textContent:this.localize(this.options_.legendText),id:this.options_.legendId});this.el().appendChild(i);const r=this.options_.selects;for(const n of r){const a=this.options_.selectConfigs[n],o=a.className,u=a.id.replace("%s",this.options_.id_);let c=null;const p=`vjs_select_${xt()}`;if(this.options_.type==="colors"){c=X("span",{className:o});const v=X("label",{id:u,className:"vjs-label",textContent:a.label});v.setAttribute("for",p),c.appendChild(v)}const y=new Km(e,{SelectOptions:a.options,legendId:this.options_.legendId,id:p,labelId:u});this.addChild(y),this.options_.type==="colors"&&(c.appendChild(y.el()),this.el().appendChild(c))}}createEl(){return X("fieldset",{className:this.options_.className})}}B.registerComponent("TextTrackFieldset",Wi);class Xm extends B{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,r=new Wi(e,{id_:i,legendId:`captions-text-legend-${i}`,legendText:this.localize("Text"),className:"vjs-fg vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(r);const n=new Wi(e,{id_:i,legendId:`captions-background-${i}`,legendText:this.localize("Text Background"),className:"vjs-bg vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(n);const a=new Wi(e,{id_:i,legendId:`captions-window-${i}`,legendText:this.localize("Caption Area Background"),className:"vjs-window vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(a)}createEl(){return X("div",{className:"vjs-track-settings-colors"})}}B.registerComponent("TextTrackSettingsColors",Xm);class Ym extends B{constructor(e,t={}){super(e,t);const i=this.options_.textTrackComponentid,r=new Wi(e,{id_:i,legendId:`captions-font-size-${i}`,legendText:"Font Size",className:"vjs-font-percent vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(r);const n=new Wi(e,{id_:i,legendId:`captions-edge-style-${i}`,legendText:this.localize("Text Edge Style"),className:"vjs-edge-style vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(n);const a=new Wi(e,{id_:i,legendId:`captions-font-family-${i}`,legendText:this.localize("Font Family"),className:"vjs-font-family vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(a)}createEl(){return X("div",{className:"vjs-track-settings-font"})}}B.registerComponent("TextTrackSettingsFont",Ym);class Qm extends B{constructor(e,t={}){super(e,t);const i=this.localize("restore all settings to the default values"),r=new Ge(e,{controlText:i,className:"vjs-default-button"});r.el().classList.remove("vjs-control","vjs-button"),r.el().textContent=this.localize("Reset"),this.addChild(r);const n=new Ge(e,{controlText:i,className:"vjs-done-button"});n.el().classList.remove("vjs-control","vjs-button"),n.el().textContent=this.localize("Done"),this.addChild(n)}createEl(){return X("div",{className:"vjs-track-settings-controls"})}}B.registerComponent("TrackSettingsControls",Qm);const nl="vjs-text-track-settings",_h=["#000","Black"],vh=["#00F","Blue"],Th=["#0FF","Cyan"],bh=["#0F0","Green"],Sh=["#F0F","Magenta"],xh=["#F00","Red"],Eh=["#FFF","White"],Ch=["#FF0","Yellow"],al=["1","Opaque"],ol=["0.5","Semi-Transparent"],Ah=["0","Transparent"],mi={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[_h,Eh,xh,bh,vh,Ch,Sh,Th],className:"vjs-bg-color"},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[al,ol,Ah],className:"vjs-bg-opacity vjs-opacity"},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[Eh,_h,xh,bh,vh,Ch,Sh,Th],className:"vjs-text-color"},edgeStyle:{selector:".vjs-edge-style > select",id:"",label:"Text Edge Style",options:[["none","None"],["raised","Raised"],["depressed","Depressed"],["uniform","Uniform"],["dropshadow","Drop shadow"]]},fontFamily:{selector:".vjs-font-family > select",id:"",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:"",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:s=>s==="1.00"?null:Number(s)},textOpacity:{selector:".vjs-text-opacity > select",id:"captions-foreground-opacity-%s",label:"Opacity",options:[al,ol],className:"vjs-text-opacity vjs-opacity"},windowColor:{selector:".vjs-window-color > select",id:"captions-window-color-%s",label:"Color",className:"vjs-window-color"},windowOpacity:{selector:".vjs-window-opacity > select",id:"captions-window-opacity-%s",label:"Opacity",options:[Ah,ol,al],className:"vjs-window-opacity vjs-opacity"}};mi.windowColor.options=mi.backgroundColor.options;function Jm(s,e){if(e&&(s=e(s)),s&&s!=="none")return s}function gA(s,e){const t=s.options[s.options.selectedIndex].value;return Jm(t,e)}function yA(s,e,t){if(e){for(let i=0;i{this.saveSettings(),this.close()}),this.on(this.$(".vjs-default-button"),["click","tap"],()=>{this.setDefaults(),this.updateDisplay()}),xs(mi,e=>{this.on(this.$(e.selector),"change",this.updateDisplay)})}dispose(){this.endDialog=null,super.dispose()}label(){return this.localize("Caption Settings Dialog")}description(){return this.localize("Beginning of dialog window. Escape will cancel and close the window.")}buildCSSClass(){return super.buildCSSClass()+" vjs-text-track-settings"}getValues(){return qp(mi,(e,t,i)=>{const r=gA(this.$(t.selector),t.parser);return r!==void 0&&(e[i]=r),e},{})}setValues(e){xs(mi,(t,i)=>{yA(this.$(t.selector),e[i],t.parser)})}setDefaults(){xs(mi,e=>{const t=e.hasOwnProperty("default")?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(E.localStorage.getItem(nl))}catch(t){Z.warn(t)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;const e=this.getValues();try{Object.keys(e).length?E.localStorage.setItem(nl,JSON.stringify(e)):E.localStorage.removeItem(nl)}catch(t){Z.warn(t)}}updateDisplay(){const e=this.player_.getChild("textTrackDisplay");e&&e.updateDisplay()}handleLanguagechange(){this.fill(),this.renderModalComponents(this.player_),this.bindFunctionsToSelectsAndButtons()}}B.registerComponent("TextTrackSettings",_A);class vA extends B{constructor(e,t){let i=t.ResizeObserver||E.ResizeObserver;t.ResizeObserver===null&&(i=!1);const r=ce({createEl:!i,reportTouchActivity:!1},t);super(e,r),this.ResizeObserver=t.ResizeObserver||E.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=dm(()=>{this.resizeHandler()},100,!1,this),i?(this.resizeObserver_=new this.ResizeObserver(this.debouncedHandler_),this.resizeObserver_.observe(e.el())):(this.loadListener_=()=>{if(!this.el_||!this.el_.contentWindow)return;const n=this.debouncedHandler_;let a=this.unloadListener_=function(){ze(this,"resize",n),ze(this,"unload",a),a=null};gt(this.el_.contentWindow,"unload",a),gt(this.el_.contentWindow,"resize",n)},this.one("load",this.loadListener_))}createEl(){return super.createEl("iframe",{className:"vjs-resize-manager",tabIndex:-1,title:this.localize("No content")},{"aria-hidden":"true"})}resizeHandler(){!this.player_||!this.player_.trigger||this.player_.trigger("playerresize")}dispose(){this.debouncedHandler_&&this.debouncedHandler_.cancel(),this.resizeObserver_&&(this.player_.el()&&this.resizeObserver_.unobserve(this.player_.el()),this.resizeObserver_.disconnect()),this.loadListener_&&this.off("load",this.loadListener_),this.el_&&this.el_.contentWindow&&this.unloadListener_&&this.unloadListener_.call(this.el_.contentWindow),this.ResizeObserver=null,this.resizeObserver=null,this.debouncedHandler_=null,this.loadListener_=null,super.dispose()}}B.registerComponent("ResizeManager",vA);const TA={trackingThreshold:20,liveTolerance:15};class bA extends B{constructor(e,t){const i=ce(TA,t,{createEl:!1});super(e,i),this.trackLiveHandler_=()=>this.trackLive_(),this.handlePlay_=r=>this.handlePlay(r),this.handleFirstTimeupdate_=r=>this.handleFirstTimeupdate(r),this.handleSeeked_=r=>this.handleSeeked(r),this.seekToLiveEdge_=r=>this.seekToLiveEdge(r),this.reset_(),this.on(this.player_,"durationchange",r=>this.handleDurationchange(r)),this.on(this.player_,"canplay",()=>this.toggleTracking())}trackLive_(){const e=this.player_.seekable();if(!e||!e.length)return;const t=Number(E.performance.now().toFixed(4)),i=this.lastTime_===-1?0:(t-this.lastTime_)/1e3;this.lastTime_=t,this.pastSeekEnd_=this.pastSeekEnd()+i;const r=this.liveCurrentTime(),n=this.player_.currentTime();let a=this.player_.paused()||this.seekedBehindLive_||Math.abs(r-n)>this.options_.liveTolerance;(!this.timeupdateSeen_||r===1/0)&&(a=!1),a!==this.behindLiveEdge_&&(this.behindLiveEdge_=a,this.trigger("liveedgechange"))}handleDurationchange(){this.toggleTracking()}toggleTracking(){this.player_.duration()===1/0&&this.liveWindow()>=this.options_.trackingThreshold?(this.player_.options_.liveui&&this.player_.addClass("vjs-liveui"),this.startTracking()):(this.player_.removeClass("vjs-liveui"),this.stopTracking())}startTracking(){this.isTracking()||(this.timeupdateSeen_||(this.timeupdateSeen_=this.player_.hasStarted()),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,Et),this.trackLive_(),this.on(this.player_,["play","pause"],this.trackLiveHandler_),this.timeupdateSeen_?this.on(this.player_,"seeked",this.handleSeeked_):(this.one(this.player_,"play",this.handlePlay_),this.one(this.player_,"timeupdate",this.handleFirstTimeupdate_)))}handleFirstTimeupdate(){this.timeupdateSeen_=!0,this.on(this.player_,"seeked",this.handleSeeked_)}handleSeeked(){const e=Math.abs(this.liveCurrentTime()-this.player_.currentTime());this.seekedBehindLive_=this.nextSeekedFromUser_&&e>2,this.nextSeekedFromUser_=!1,this.trackLive_()}handlePlay(){this.one(this.player_,"timeupdate",this.seekToLiveEdge_)}reset_(){this.lastTime_=-1,this.pastSeekEnd_=0,this.lastSeekEnd_=-1,this.behindLiveEdge_=!0,this.timeupdateSeen_=!1,this.seekedBehindLive_=!1,this.nextSeekedFromUser_=!1,this.clearInterval(this.trackingInterval_),this.trackingInterval_=null,this.off(this.player_,["play","pause"],this.trackLiveHandler_),this.off(this.player_,"seeked",this.handleSeeked_),this.off(this.player_,"play",this.handlePlay_),this.off(this.player_,"timeupdate",this.handleFirstTimeupdate_),this.off(this.player_,"timeupdate",this.seekToLiveEdge_)}nextSeekedFromUser(){this.nextSeekedFromUser_=!0}stopTracking(){this.isTracking()&&(this.reset_(),this.trigger("liveedgechange"))}seekableEnd(){const e=this.player_.seekable(),t=[];let i=e?e.length:0;for(;i--;)t.push(e.end(i));return t.length?t.sort()[t.length-1]:1/0}seekableStart(){const e=this.player_.seekable(),t=[];let i=e?e.length:0;for(;i--;)t.push(e.start(i));return t.length?t.sort()[0]:0}liveWindow(){const e=this.liveCurrentTime();return e===1/0?0:e-this.seekableStart()}isLive(){return this.isTracking()}atLiveEdge(){return!this.behindLiveEdge()}liveCurrentTime(){return this.pastSeekEnd()+this.seekableEnd()}pastSeekEnd(){const e=this.seekableEnd();return this.lastSeekEnd_!==-1&&e!==this.lastSeekEnd_&&(this.pastSeekEnd_=0),this.lastSeekEnd_=e,this.pastSeekEnd_}behindLiveEdge(){return this.behindLiveEdge_}isTracking(){return typeof this.trackingInterval_=="number"}seekToLiveEdge(){this.seekedBehindLive_=!1,!this.atLiveEdge()&&(this.nextSeekedFromUser_=!1,this.player_.currentTime(this.liveCurrentTime()))}dispose(){this.stopTracking(),super.dispose()}}B.registerComponent("LiveTracker",bA);class SA extends B{constructor(e,t){super(e,t),this.on("statechanged",i=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:X("div",{className:"vjs-title-bar-title",id:`vjs-title-bar-title-${xt()}`}),description:X("div",{className:"vjs-title-bar-description",id:`vjs-title-bar-description-${xt()}`})},X("div",{className:"vjs-title-bar"},{},Hp(this.els))}updateDom_(){const e=this.player_.tech_,t=e&&e.el_,i={title:"aria-labelledby",description:"aria-describedby"};["title","description"].forEach(r=>{const n=this.state[r],a=this.els[r],o=i[r];so(a),n&&Ei(a,n),t&&(t.removeAttribute(o),n&&t.setAttribute(o,a.id))}),this.state.title||this.state.description?this.show():this.hide()}update(e){this.setState(e)}dispose(){const e=this.player_.tech_,t=e&&e.el_;t&&(t.removeAttribute("aria-labelledby"),t.removeAttribute("aria-describedby")),super.dispose(),this.els=null}}B.registerComponent("TitleBar",SA);const xA={initialDisplay:4e3,position:[],takeFocus:!1};class EA extends Ge{constructor(e,t){t=ce(xA,t),super(e,t),this.controlText(t.controlText),this.hide(),this.on(this.player_,["useractive","userinactive"],i=>{this.removeClass("force-display")})}buildCSSClass(){return`vjs-transient-button focus-visible ${this.options_.position.map(e=>`vjs-${e}`).join(" ")}`}createEl(){const e=X("button",{},{type:"button",class:this.buildCSSClass()},X("span"));return this.controlTextEl_=e.querySelector("span"),e}show(){super.show(),this.addClass("force-display"),this.options_.takeFocus&&this.el().focus({preventScroll:!0}),this.forceDisplayTimeout=this.player_.setTimeout(()=>{this.removeClass("force-display")},this.options_.initialDisplay)}hide(){this.removeClass("force-display"),super.hide()}dispose(){this.player_.clearTimeout(this.forceDisplayTimeout),super.dispose()}}B.registerComponent("TransientButton",EA);const Ol=s=>{const e=s.el();if(e.hasAttribute("src"))return s.triggerSourceset(e.src),!0;const t=s.$$("source"),i=[];let r="";if(!t.length)return!1;for(let n=0;n{let t={};for(let i=0;iZm([s.el(),E.HTMLMediaElement.prototype,E.Element.prototype,CA],"innerHTML"),wh=function(s){const e=s.el();if(e.resetSourceWatch_)return;const t={},i=AA(s),r=n=>(...a)=>{const o=n.apply(e,a);return Ol(s),o};["append","appendChild","insertAdjacentHTML"].forEach(n=>{e[n]&&(t[n]=e[n],e[n]=r(t[n]))}),Object.defineProperty(e,"innerHTML",ce(i,{set:r(i.set)})),e.resetSourceWatch_=()=>{e.resetSourceWatch_=null,Object.keys(t).forEach(n=>{e[n]=t[n]}),Object.defineProperty(e,"innerHTML",i)},s.one("sourceset",e.resetSourceWatch_)},wA=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?bm(E.Element.prototype.getAttribute.call(this,"src")):""},set(s){return E.Element.prototype.setAttribute.call(this,"src",s),s}}),DA=s=>Zm([s.el(),E.HTMLMediaElement.prototype,wA],"src"),kA=function(s){if(!s.featuresSourceset)return;const e=s.el();if(e.resetSourceset_)return;const t=DA(s),i=e.setAttribute,r=e.load;Object.defineProperty(e,"src",ce(t,{set:n=>{const a=t.set.call(e,n);return s.triggerSourceset(e.src),a}})),e.setAttribute=(n,a)=>{const o=i.call(e,n,a);return/src/i.test(n)&&s.triggerSourceset(e.src),o},e.load=()=>{const n=r.call(e);return Ol(s)||(s.triggerSourceset(""),wh(s)),n},e.currentSrc?s.triggerSourceset(e.currentSrc):Ol(s)||wh(s),e.resetSourceset_=()=>{e.resetSourceset_=null,e.load=r,e.setAttribute=i,Object.defineProperty(e,"src",t),e.resetSourceWatch_&&e.resetSourceWatch_()}};class H extends Q{constructor(e,t){super(e,t);const i=e.source;let r=!1;if(this.featuresVideoFrameCallback=this.featuresVideoFrameCallback&&this.el_.tagName==="VIDEO",i&&(this.el_.currentSrc!==i.src||e.tag&&e.tag.initNetworkState_===3)?this.setSource(i):this.handleLateInit_(this.el_),e.enableSourceset&&this.setupSourcesetHandling_(),this.isScrubbing_=!1,this.el_.hasChildNodes()){const n=this.el_.childNodes;let a=n.length;const o=[];for(;a--;){const u=n[a];u.nodeName.toLowerCase()==="track"&&(this.featuresNativeTextTracks?(this.remoteTextTrackEls().addTrackElement_(u),this.remoteTextTracks().addTrack(u.track),this.textTracks().addTrack(u.track),!r&&!this.el_.hasAttribute("crossorigin")&&oo(u.src)&&(r=!0)):o.push(u))}for(let u=0;u{t=[];for(let n=0;ne.removeEventListener("change",i));const r=()=>{for(let n=0;n{e.removeEventListener("change",i),e.removeEventListener("change",r),e.addEventListener("change",r)}),this.on("webkitendfullscreen",()=>{e.removeEventListener("change",i),e.addEventListener("change",i),e.removeEventListener("change",r)})}overrideNative_(e,t){if(t!==this[`featuresNative${e}Tracks`])return;const i=e.toLowerCase();this[`${i}TracksListeners_`]&&Object.keys(this[`${i}TracksListeners_`]).forEach(r=>{this.el()[`${i}Tracks`].removeEventListener(r,this[`${i}TracksListeners_`][r])}),this[`featuresNative${e}Tracks`]=!t,this[`${i}TracksListeners_`]=null,this.proxyNativeTracksForType_(i)}overrideNativeAudioTracks(e){this.overrideNative_("Audio",e)}overrideNativeVideoTracks(e){this.overrideNative_("Video",e)}proxyNativeTracksForType_(e){const t=St[e],i=this.el()[t.getterName],r=this[t.getterName]();if(!this[`featuresNative${t.capitalName}Tracks`]||!i||!i.addEventListener)return;const n={change:o=>{const u={type:"change",target:r,currentTarget:r,srcElement:r};r.trigger(u),e==="text"&&this[Vs.remoteText.getterName]().trigger(u)},addtrack(o){r.addTrack(o.track)},removetrack(o){r.removeTrack(o.track)}},a=function(){const o=[];for(let u=0;u{const u=n[o];i.addEventListener(o,u),this.on("dispose",c=>i.removeEventListener(o,u))}),this.on("loadstart",a),this.on("dispose",o=>this.off("loadstart",a))}proxyNativeTracks_(){St.names.forEach(e=>{this.proxyNativeTracksForType_(e)})}createEl(){let e=this.options_.tag;if(!e||!(this.options_.playerElIngest||this.movingMediaElementInDOM)){if(e){const i=e.cloneNode(!0);e.parentNode&&e.parentNode.insertBefore(i,e),H.disposeMediaElement(e),e=i}else{e=$.createElement("video");const i=this.options_.tag&&pi(this.options_.tag),r=ce({},i);(!Xr||this.options_.nativeControlsForTouch!==!0)&&delete r.controls,Jp(e,Object.assign(r,{id:this.options_.techId,class:"vjs-tech"}))}e.playerId=this.options_.playerId}typeof this.options_.preload<"u"&&$s(e,"preload",this.options_.preload),this.options_.disablePictureInPicture!==void 0&&(e.disablePictureInPicture=this.options_.disablePictureInPicture);const t=["loop","muted","playsinline","autoplay"];for(let i=0;i=2&&t.push("loadeddata"),e.readyState>=3&&t.push("canplay"),e.readyState>=4&&t.push("canplaythrough"),this.ready(function(){t.forEach(function(i){this.trigger(i)},this)})}setScrubbing(e){this.isScrubbing_=e}scrubbing(){return this.isScrubbing_}setCurrentTime(e){try{this.isScrubbing_&&this.el_.fastSeek&&Za?this.el_.fastSeek(e):this.el_.currentTime=e}catch(t){Z(t,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&Ht&&Vt&&this.el_.currentTime===0){const e=()=>{this.el_.currentTime>0&&(this.el_.duration===1/0&&this.trigger("durationchange"),this.off("timeupdate",e))};return this.on("timeupdate",e),NaN}return this.el_.duration||NaN}width(){return this.el_.offsetWidth}height(){return this.el_.offsetHeight}proxyWebkitFullscreen_(){if(!("webkitDisplayingFullscreen"in this.el_))return;const e=function(){this.trigger("fullscreenchange",{isFullscreen:!1}),this.el_.controls&&!this.options_.nativeControlsForTouch&&this.controls()&&(this.el_.controls=!1)},t=function(){"webkitPresentationMode"in this.el_&&this.el_.webkitPresentationMode!=="picture-in-picture"&&(this.one("webkitendfullscreen",e),this.trigger("fullscreenchange",{isFullscreen:!0,nativeIOSFullscreen:!0}))};this.on("webkitbeginfullscreen",t),this.on("dispose",()=>{this.off("webkitbeginfullscreen",t),this.off("webkitendfullscreen",e)})}supportsFullScreen(){return typeof this.el_.webkitEnterFullScreen=="function"}enterFullScreen(){const e=this.el_;if(e.paused&&e.networkState<=e.HAVE_METADATA)Mt(this.el_.play()),this.setTimeout(function(){e.pause();try{e.webkitEnterFullScreen()}catch(t){this.trigger("fullscreenerror",t)}},0);else try{e.webkitEnterFullScreen()}catch(t){this.trigger("fullscreenerror",t)}}exitFullScreen(){if(!this.el_.webkitDisplayingFullscreen){this.trigger("fullscreenerror",new Error("The video is not fullscreen"));return}this.el_.webkitExitFullScreen()}requestPictureInPicture(){return this.el_.requestPictureInPicture()}requestVideoFrameCallback(e){return this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.requestVideoFrameCallback(e):super.requestVideoFrameCallback(e)}cancelVideoFrameCallback(e){this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.cancelVideoFrameCallback(e):super.cancelVideoFrameCallback(e)}src(e){if(e===void 0)return this.el_.src;this.setSrc(e)}reset(){H.resetMediaElement(this.el_)}currentSrc(){return this.currentSource_?this.currentSource_.src:this.el_.currentSrc}setControls(e){this.el_.controls=!!e}addTextTrack(e,t,i){return this.featuresNativeTextTracks?this.el_.addTextTrack(e,t,i):super.addTextTrack(e,t,i)}createRemoteTextTrack(e){if(!this.featuresNativeTextTracks)return super.createRemoteTextTrack(e);const t=$.createElement("track");return e.kind&&(t.kind=e.kind),e.label&&(t.label=e.label),(e.language||e.srclang)&&(t.srclang=e.language||e.srclang),e.default&&(t.default=e.default),e.id&&(t.id=e.id),e.src&&(t.src=e.src),t}addRemoteTextTrack(e,t){const i=super.addRemoteTextTrack(e,t);return this.featuresNativeTextTracks&&this.el().appendChild(i),i}removeRemoteTextTrack(e){if(super.removeRemoteTextTrack(e),this.featuresNativeTextTracks){const t=this.$$("track");let i=t.length;for(;i--;)(e===t[i]||e===t[i].track)&&this.el().removeChild(t[i])}}getVideoPlaybackQuality(){if(typeof this.el().getVideoPlaybackQuality=="function")return this.el().getVideoPlaybackQuality();const e={};return typeof this.el().webkitDroppedFrameCount<"u"&&typeof this.el().webkitDecodedFrameCount<"u"&&(e.droppedVideoFrames=this.el().webkitDroppedFrameCount,e.totalVideoFrames=this.el().webkitDecodedFrameCount),E.performance&&(e.creationTime=E.performance.now()),e}}Xa(H,"TEST_VID",function(){if(!Ks())return;const s=$.createElement("video"),e=$.createElement("track");return e.kind="captions",e.srclang="en",e.label="English",s.appendChild(e),s});H.isSupported=function(){try{H.TEST_VID.volume=.5}catch{return!1}return!!(H.TEST_VID&&H.TEST_VID.canPlayType)};H.canPlayType=function(s){return H.TEST_VID.canPlayType(s)};H.canPlaySource=function(s,e){return H.canPlayType(s.type)};H.canControlVolume=function(){try{const s=H.TEST_VID.volume;H.TEST_VID.volume=s/2+.1;const e=s!==H.TEST_VID.volume;return e&&st?(E.setTimeout(()=>{H&&H.prototype&&(H.prototype.featuresVolumeControl=s!==H.TEST_VID.volume)}),!1):e}catch{return!1}};H.canMuteVolume=function(){try{const s=H.TEST_VID.muted;return H.TEST_VID.muted=!s,H.TEST_VID.muted?$s(H.TEST_VID,"muted","muted"):to(H.TEST_VID,"muted","muted"),s!==H.TEST_VID.muted}catch{return!1}};H.canControlPlaybackRate=function(){if(Ht&&Vt&&Ya<58)return!1;try{const s=H.TEST_VID.playbackRate;return H.TEST_VID.playbackRate=s/2+.1,s!==H.TEST_VID.playbackRate}catch{return!1}};H.canOverrideAttributes=function(){try{const s=()=>{};Object.defineProperty($.createElement("video"),"src",{get:s,set:s}),Object.defineProperty($.createElement("audio"),"src",{get:s,set:s}),Object.defineProperty($.createElement("video"),"innerHTML",{get:s,set:s}),Object.defineProperty($.createElement("audio"),"innerHTML",{get:s,set:s})}catch{return!1}return!0};H.supportsNativeTextTracks=function(){return Za||st&&Vt};H.supportsNativeVideoTracks=function(){return!!(H.TEST_VID&&H.TEST_VID.videoTracks)};H.supportsNativeAudioTracks=function(){return!!(H.TEST_VID&&H.TEST_VID.audioTracks)};H.Events=["loadstart","suspend","abort","error","emptied","stalled","loadedmetadata","loadeddata","canplay","canplaythrough","playing","waiting","seeking","seeked","ended","durationchange","timeupdate","progress","play","pause","ratechange","resize","volumechange"];[["featuresMuteControl","canMuteVolume"],["featuresPlaybackRate","canControlPlaybackRate"],["featuresSourceset","canOverrideAttributes"],["featuresNativeTextTracks","supportsNativeTextTracks"],["featuresNativeVideoTracks","supportsNativeVideoTracks"],["featuresNativeAudioTracks","supportsNativeAudioTracks"]].forEach(function([s,e]){Xa(H.prototype,s,()=>H[e](),!0)});H.prototype.featuresVolumeControl=H.canControlVolume();H.prototype.movingMediaElementInDOM=!st;H.prototype.featuresFullscreenResize=!0;H.prototype.featuresProgressEvents=!0;H.prototype.featuresTimeupdateEvents=!0;H.prototype.featuresVideoFrameCallback=!!(H.TEST_VID&&H.TEST_VID.requestVideoFrameCallback);H.disposeMediaElement=function(s){if(s){for(s.parentNode&&s.parentNode.removeChild(s);s.hasChildNodes();)s.removeChild(s.firstChild);s.removeAttribute("src"),typeof s.load=="function"&&function(){try{s.load()}catch{}}()}};H.resetMediaElement=function(s){if(!s)return;const e=s.querySelectorAll("source");let t=e.length;for(;t--;)s.removeChild(e[t]);s.removeAttribute("src"),typeof s.load=="function"&&function(){try{s.load()}catch{}}()};["muted","defaultMuted","autoplay","controls","loop","playsinline"].forEach(function(s){H.prototype[s]=function(){return this.el_[s]||this.el_.hasAttribute(s)}});["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(s){H.prototype["set"+Se(s)]=function(e){this.el_[s]=e,e?this.el_.setAttribute(s,s):this.el_.removeAttribute(s)}});["paused","currentTime","buffered","volume","poster","preload","error","seeking","seekable","ended","playbackRate","defaultPlaybackRate","disablePictureInPicture","played","networkState","readyState","videoWidth","videoHeight","crossOrigin"].forEach(function(s){H.prototype[s]=function(){return this.el_[s]}});["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(s){H.prototype["set"+Se(s)]=function(e){this.el_[s]=e}});["pause","load","play"].forEach(function(s){H.prototype[s]=function(){return this.el_[s]()}});Q.withSourceHandlers(H);H.nativeSourceHandler={};H.nativeSourceHandler.canPlayType=function(s){try{return H.TEST_VID.canPlayType(s)}catch{return""}};H.nativeSourceHandler.canHandleSource=function(s,e){if(s.type)return H.nativeSourceHandler.canPlayType(s.type);if(s.src){const t=Ru(s.src);return H.nativeSourceHandler.canPlayType(`video/${t}`)}return""};H.nativeSourceHandler.handleSource=function(s,e,t){e.setSrc(s.src)};H.nativeSourceHandler.dispose=function(){};H.registerSourceHandler(H.nativeSourceHandler);Q.registerTech("Html5",H);const eg=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],ll={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},Rl=["tiny","xsmall","small","medium","large","xlarge","huge"],sa={};Rl.forEach(s=>{const e=s.charAt(0)==="x"?`x-${s.substring(1)}`:s;sa[s]=`vjs-layout-${e}`});const IA={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};let Be=class ms extends B{constructor(e,t,i){if(e.id=e.id||t.id||`vjs_video_${xt()}`,t=Object.assign(ms.getTagSettings(e),t),t.initChildren=!1,t.createEl=!1,t.evented=!1,t.reportTouchActivity=!1,!t.language){const a=e.closest("[lang]");a&&(t.language=a.getAttribute("lang"))}if(super(null,t,i),this.boundDocumentFullscreenChange_=a=>this.documentFullscreenChange_(a),this.boundFullWindowOnEscKey_=a=>this.fullWindowOnEscKey(a),this.boundUpdateStyleEl_=a=>this.updateStyleEl_(a),this.boundApplyInitTime_=a=>this.applyInitTime_(a),this.boundUpdateCurrentBreakpoint_=a=>this.updateCurrentBreakpoint_(a),this.boundHandleTechClick_=a=>this.handleTechClick_(a),this.boundHandleTechDoubleClick_=a=>this.handleTechDoubleClick_(a),this.boundHandleTechTouchStart_=a=>this.handleTechTouchStart_(a),this.boundHandleTechTouchMove_=a=>this.handleTechTouchMove_(a),this.boundHandleTechTouchEnd_=a=>this.handleTechTouchEnd_(a),this.boundHandleTechTap_=a=>this.handleTechTap_(a),this.boundUpdatePlayerHeightOnAudioOnlyMode_=a=>this.updatePlayerHeightOnAudioOnlyMode_(a),this.isFullscreen_=!1,this.log=$p(this.id_),this.fsApi_=ma,this.isPosterFromTech_=!1,this.queuedCallbacks_=[],this.isReady_=!1,this.hasStarted_=!1,this.userActive_=!1,this.debugEnabled_=!1,this.audioOnlyMode_=!1,this.audioPosterMode_=!1,this.audioOnlyCache_={controlBarHeight:null,playerHeight:null,hiddenChildren:[]},!this.options_||!this.options_.techOrder||!this.options_.techOrder.length)throw new Error("No techOrder specified. Did you overwrite videojs.options instead of just changing the properties you want to override?");if(this.tag=e,this.tagAttributes=e&&pi(e),this.language(this.options_.language),t.languages){const a={};Object.getOwnPropertyNames(t.languages).forEach(function(o){a[o.toLowerCase()]=t.languages[o]}),this.languages_=a}else this.languages_=ms.prototype.options_.languages;this.resetCache_(),this.poster_=t.poster||"",this.controls_=!!t.controls,e.controls=!1,e.removeAttribute("controls"),this.changingSrc_=!1,this.playCallbacks_=[],this.playTerminatedQueue_=[],e.hasAttribute("autoplay")?this.autoplay(!0):this.autoplay(this.options_.autoplay),t.plugins&&Object.keys(t.plugins).forEach(a=>{if(typeof this[a]!="function")throw new Error(`plugin "${a}" does not exist`)}),this.scrubbing_=!1,this.el_=this.createEl(),Iu(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&(gt($,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&this.on(["playerreset","resize"],this.boundUpdateStyleEl_);const r=ce(this.options_);if(t.plugins&&Object.keys(t.plugins).forEach(a=>{this[a](t.plugins[a])}),t.debug&&this.debug(!0),this.options_.playerOptions=r,this.middleware_=[],this.playbackRates(t.playbackRates),t.experimentalSvgIcons){const o=new E.DOMParser().parseFromString(ZC,"image/svg+xml");if(o.querySelector("parsererror"))Z.warn("Failed to load SVG Icons. Falling back to Font Icons."),this.options_.experimentalSvgIcons=null;else{const c=o.documentElement;c.style.display="none",this.el_.appendChild(c),this.addClass("vjs-svg-icons-enabled")}}this.initChildren(),this.isAudio(e.nodeName.toLowerCase()==="audio"),this.controls()?this.addClass("vjs-controls-enabled"):this.addClass("vjs-controls-disabled"),this.el_.setAttribute("role","region"),this.isAudio()?this.el_.setAttribute("aria-label",this.localize("Audio Player")):this.el_.setAttribute("aria-label",this.localize("Video Player")),this.isAudio()&&this.addClass("vjs-audio"),t.spatialNavigation&&t.spatialNavigation.enabled&&(this.spatialNavigation=new eA(this),this.addClass("vjs-spatial-navigation-enabled")),Xr&&this.addClass("vjs-touch-enabled"),st||this.addClass("vjs-workinghover"),ms.players[this.id_]=this;const n=El.split(".")[0];this.addClass(`vjs-v${n}`),this.userActive(!0),this.reportUserActivity(),this.one("play",a=>this.listenForUserActivity_(a)),this.on("keydown",a=>this.handleKeyDown(a)),this.on("languagechange",a=>this.handleLanguagechange(a)),this.breakpoints(this.options_.breakpoints),this.responsive(this.options_.responsive),this.on("ready",()=>{this.audioPosterMode(this.options_.audioPosterMode),this.audioOnlyMode(this.options_.audioOnlyMode)})}dispose(){this.trigger("dispose"),this.off("dispose"),ze($,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),ze($,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),ms.players[this.id_]=null,this.tag&&this.tag.player&&(this.tag.player=null),this.el_&&this.el_.player&&(this.el_.player=null),this.tech_&&(this.tech_.dispose(),this.isPosterFromTech_=!1,this.poster_=""),this.playerElIngest_&&(this.playerElIngest_=null),this.tag&&(this.tag=null),XC(this),Ze.names.forEach(e=>{const t=Ze[e],i=this[t.getterName]();i&&i.off&&i.off()}),super.dispose({restoreEl:this.options_.restoreEl})}createEl(){let e=this.tag,t,i=this.playerElIngest_=e.parentNode&&e.parentNode.hasAttribute&&e.parentNode.hasAttribute("data-vjs-player");const r=this.tag.tagName.toLowerCase()==="video-js";i?t=this.el_=e.parentNode:r||(t=this.el_=super.createEl("div"));const n=pi(e);if(r){for(t=this.el_=e,e=this.tag=$.createElement("video");t.children.length;)e.appendChild(t.firstChild);Mr(t,"video-js")||zi(t,"video-js"),t.appendChild(e),i=this.playerElIngest_=t,Object.keys(t).forEach(u=>{try{e[u]=t[u]}catch{}})}e.setAttribute("tabindex","-1"),n.tabindex="-1",Vt&&Qa&&(e.setAttribute("role","application"),n.role="application"),e.removeAttribute("width"),e.removeAttribute("height"),"width"in n&&delete n.width,"height"in n&&delete n.height,Object.getOwnPropertyNames(n).forEach(function(u){r&&u==="class"||t.setAttribute(u,n[u]),r&&e.setAttribute(u,n[u])}),e.playerId=e.id,e.id+="_html5_api",e.className="vjs-tech",e.player=t.player=this,this.addClass("vjs-paused");const a=["IS_SMART_TV","IS_TIZEN","IS_WEBOS","IS_ANDROID","IS_IPAD","IS_IPHONE","IS_CHROMECAST_RECEIVER"].filter(u=>Kp[u]).map(u=>"vjs-device-"+u.substring(3).toLowerCase().replace(/\_/g,"-"));if(this.addClass(...a),E.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=um("vjs-styles-dimensions");const u=Si(".vjs-styles-defaults"),c=Si("head");c.insertBefore(this.styleEl_,u?u.nextSibling:c.firstChild)}this.fill_=!1,this.fluid_=!1,this.width(this.options_.width),this.height(this.options_.height),this.fill(this.options_.fill),this.fluid(this.options_.fluid),this.aspectRatio(this.options_.aspectRatio),this.crossOrigin(this.options_.crossOrigin||this.options_.crossorigin);const o=e.getElementsByTagName("a");for(let u=0;u"u")return this.techGet_("crossOrigin");if(e!==null&&e!=="anonymous"&&e!=="use-credentials"){Z.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${e}"`);return}this.techCall_("setCrossOrigin",e),this.posterImage&&this.posterImage.crossOrigin(e)}width(e){return this.dimension("width",e)}height(e){return this.dimension("height",e)}dimension(e,t){const i=e+"_";if(t===void 0)return this[i]||0;if(t===""||t==="auto"){this[i]=void 0,this.updateStyleEl_();return}const r=parseFloat(t);if(isNaN(r)){Z.error(`Improper value "${t}" supplied for for ${e}`);return}this[i]=r,this.updateStyleEl_()}fluid(e){if(e===void 0)return!!this.fluid_;this.fluid_=!!e,ii(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),e?(this.addClass("vjs-fluid"),this.fill(!1),CC(this,()=>{this.on(["playerreset","resize"],this.boundUpdateStyleEl_)})):this.removeClass("vjs-fluid"),this.updateStyleEl_()}fill(e){if(e===void 0)return!!this.fill_;this.fill_=!!e,e?(this.addClass("vjs-fill"),this.fluid(!1)):this.removeClass("vjs-fill")}aspectRatio(e){if(e===void 0)return this.aspectRatio_;if(!/^\d+\:\d+$/.test(e))throw new Error("Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.");this.aspectRatio_=e,this.fluid(!0),this.updateStyleEl_()}updateStyleEl_(){if(E.VIDEOJS_NO_DYNAMIC_STYLE===!0){const o=typeof this.width_=="number"?this.width_:this.options_.width,u=typeof this.height_=="number"?this.height_:this.options_.height,c=this.tech_&&this.tech_.el();c&&(o>=0&&(c.width=o),u>=0&&(c.height=u));return}let e,t,i,r;this.aspectRatio_!==void 0&&this.aspectRatio_!=="auto"?i=this.aspectRatio_:this.videoWidth()>0?i=this.videoWidth()+":"+this.videoHeight():i="16:9";const n=i.split(":"),a=n[1]/n[0];this.width_!==void 0?e=this.width_:this.height_!==void 0?e=this.height_/a:e=this.videoWidth()||300,this.height_!==void 0?t=this.height_:t=e*a,/^[^a-zA-Z]/.test(this.id())?r="dimensions-"+this.id():r=this.id()+"-dimensions",this.addClass(r),cm(this.styleEl_,`
+ .${r} {
+ width: ${e}px;
+ height: ${t}px;
+ }
+
+ .${r}.vjs-fluid:not(.vjs-audio-only-mode) {
+ padding-top: ${a*100}%;
+ }
+ `)}loadTech_(e,t){this.tech_&&this.unloadTech_();const i=Se(e),r=e.charAt(0).toLowerCase()+e.slice(1);i!=="Html5"&&this.tag&&(Q.getTech("Html5").disposeMediaElement(this.tag),this.tag.player=null,this.tag=null),this.techName_=i,this.isReady_=!1;let n=this.autoplay();(typeof this.autoplay()=="string"||this.autoplay()===!0&&this.options_.normalizeAutoplay)&&(n=!1);const a={source:t,autoplay:n,nativeControlsForTouch:this.options_.nativeControlsForTouch,playerId:this.id(),techId:`${this.id()}_${r}_api`,playsinline:this.options_.playsinline,preload:this.options_.preload,loop:this.options_.loop,disablePictureInPicture:this.options_.disablePictureInPicture,muted:this.options_.muted,poster:this.poster(),language:this.language(),playerElIngest:this.playerElIngest_||!1,"vtt.js":this.options_["vtt.js"],canOverridePoster:!!this.options_.techCanOverridePoster,enableSourceset:this.options_.enableSourceset};Ze.names.forEach(u=>{const c=Ze[u];a[c.getterName]=this[c.privateName]}),Object.assign(a,this.options_[i]),Object.assign(a,this.options_[r]),Object.assign(a,this.options_[e.toLowerCase()]),this.tag&&(a.tag=this.tag),t&&t.src===this.cache_.src&&this.cache_.currentTime>0&&(a.startTime=this.cache_.currentTime);const o=Q.getTech(e);if(!o)throw new Error(`No Tech named '${i}' exists! '${i}' should be registered using videojs.registerTech()'`);this.tech_=new o(a),this.tech_.ready(de(this,this.handleTechReady_),!0),ah.jsonToTextTracks(this.textTracksJson_||[],this.tech_),eg.forEach(u=>{this.on(this.tech_,u,c=>this[`handleTech${Se(u)}_`](c))}),Object.keys(ll).forEach(u=>{this.on(this.tech_,u,c=>{if(this.tech_.playbackRate()===0&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${ll[u]}_`].bind(this),event:c});return}this[`handleTech${ll[u]}_`](c)})}),this.on(this.tech_,"loadstart",u=>this.handleTechLoadStart_(u)),this.on(this.tech_,"sourceset",u=>this.handleTechSourceset_(u)),this.on(this.tech_,"waiting",u=>this.handleTechWaiting_(u)),this.on(this.tech_,"ended",u=>this.handleTechEnded_(u)),this.on(this.tech_,"seeking",u=>this.handleTechSeeking_(u)),this.on(this.tech_,"play",u=>this.handleTechPlay_(u)),this.on(this.tech_,"pause",u=>this.handleTechPause_(u)),this.on(this.tech_,"durationchange",u=>this.handleTechDurationChange_(u)),this.on(this.tech_,"fullscreenchange",(u,c)=>this.handleTechFullscreenChange_(u,c)),this.on(this.tech_,"fullscreenerror",(u,c)=>this.handleTechFullscreenError_(u,c)),this.on(this.tech_,"enterpictureinpicture",u=>this.handleTechEnterPictureInPicture_(u)),this.on(this.tech_,"leavepictureinpicture",u=>this.handleTechLeavePictureInPicture_(u)),this.on(this.tech_,"error",u=>this.handleTechError_(u)),this.on(this.tech_,"posterchange",u=>this.handleTechPosterChange_(u)),this.on(this.tech_,"textdata",u=>this.handleTechTextData_(u)),this.on(this.tech_,"ratechange",u=>this.handleTechRateChange_(u)),this.on(this.tech_,"loadedmetadata",this.boundUpdateStyleEl_),this.usingNativeControls(this.techGet_("controls")),this.controls()&&!this.usingNativeControls()&&this.addTechControlsListeners_(),this.tech_.el().parentNode!==this.el()&&(i!=="Html5"||!this.tag)&&Al(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){Ze.names.forEach(e=>{const t=Ze[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=ah.textTracksToJson(this.tech_),this.isReady_=!1,this.tech_.dispose(),this.tech_=!1,this.isPosterFromTech_&&(this.poster_="",this.trigger("posterchange")),this.isPosterFromTech_=!1}tech(e){return e===void 0&&Z.warn(`Using the tech directly can be dangerous. I hope you know what you're doing.
+See https://github.com/videojs/video.js/issues/2617 for more info.
+`),this.tech_}version(){return{"video.js":El}}addTechControlsListeners_(){this.removeTechControlsListeners_(),this.on(this.tech_,"click",this.boundHandleTechClick_),this.on(this.tech_,"dblclick",this.boundHandleTechDoubleClick_),this.on(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.on(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.on(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.on(this.tech_,"tap",this.boundHandleTechTap_)}removeTechControlsListeners_(){this.off(this.tech_,"tap",this.boundHandleTechTap_),this.off(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.off(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.off(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.off(this.tech_,"click",this.boundHandleTechClick_),this.off(this.tech_,"dblclick",this.boundHandleTechDoubleClick_)}handleTechReady_(){this.triggerReady(),this.cache_.volume&&this.techCall_("setVolume",this.cache_.volume),this.handleTechPosterChange_(),this.handleTechDurationChange_()}handleTechLoadStart_(){this.removeClass("vjs-ended","vjs-seeking"),this.error(null),this.handleTechDurationChange_(),this.paused()?(this.hasStarted(!1),this.trigger("loadstart")):this.trigger("loadstart"),this.manualAutoplay_(this.autoplay()===!0&&this.options_.normalizeAutoplay?"play":this.autoplay())}manualAutoplay_(e){if(!this.tech_||typeof e!="string")return;const t=()=>{const r=this.muted();this.muted(!0);const n=()=>{this.muted(r)};this.playTerminatedQueue_.push(n);const a=this.play();if(Fr(a))return a.catch(o=>{throw n(),new Error(`Rejection at manualAutoplay. Restoring muted value. ${o||""}`)})};let i;if(e==="any"&&!this.muted()?(i=this.play(),Fr(i)&&(i=i.catch(t))):e==="muted"&&!this.muted()?i=t():i=this.play(),!!Fr(i))return i.then(()=>{this.trigger({type:"autoplay-success",autoplay:e})}).catch(()=>{this.trigger({type:"autoplay-failure",autoplay:e})})}updateSourceCaches_(e=""){let t=e,i="";typeof t!="string"&&(t=e.src,i=e.type),this.cache_.source=this.cache_.source||{},this.cache_.sources=this.cache_.sources||[],t&&!i&&(i=JC(this,t)),this.cache_.source=ce({},e,{src:t,type:i});const r=this.cache_.sources.filter(u=>u.src&&u.src===t),n=[],a=this.$$("source"),o=[];for(let u=0;uthis.updateSourceCaches_(n);const i=this.currentSource().src,r=e.src;i&&!/^blob:/.test(i)&&/^blob:/.test(r)&&(!this.lastSource_||this.lastSource_.tech!==r&&this.lastSource_.player!==i)&&(t=()=>{}),t(r),e.src||this.tech_.any(["sourceset","loadstart"],n=>{if(n.type==="sourceset")return;const a=this.techGet_("currentSrc");this.lastSource_.tech=a,this.updateSourceCaches_(a)})}this.lastSource_={player:this.currentSource().src,tech:e.src},this.trigger({src:e.src,type:"sourceset"})}hasStarted(e){if(e===void 0)return this.hasStarted_;e!==this.hasStarted_&&(this.hasStarted_=e,this.hasStarted_?this.addClass("vjs-has-started"):this.removeClass("vjs-has-started"))}handleTechPlay_(){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.hasStarted(!0),this.trigger("play")}handleTechRateChange_(){this.tech_.playbackRate()>0&&this.cache_.lastPlaybackRate===0&&(this.queuedCallbacks_.forEach(e=>e.callback(e.event)),this.queuedCallbacks_=[]),this.cache_.lastPlaybackRate=this.tech_.playbackRate(),this.trigger("ratechange")}handleTechWaiting_(){this.addClass("vjs-waiting"),this.trigger("waiting");const e=this.currentTime(),t=()=>{e!==this.currentTime()&&(this.removeClass("vjs-waiting"),this.off("timeupdate",t))};this.on("timeupdate",t)}handleTechCanPlay_(){this.removeClass("vjs-waiting"),this.trigger("canplay")}handleTechCanPlayThrough_(){this.removeClass("vjs-waiting"),this.trigger("canplaythrough")}handleTechPlaying_(){this.removeClass("vjs-waiting"),this.trigger("playing")}handleTechSeeking_(){this.addClass("vjs-seeking"),this.trigger("seeking")}handleTechSeeked_(){this.removeClass("vjs-seeking","vjs-ended"),this.trigger("seeked")}handleTechPause_(){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.trigger("pause")}handleTechEnded_(){this.addClass("vjs-ended"),this.removeClass("vjs-waiting"),this.options_.loop?(this.currentTime(0),this.play()):this.paused()||this.pause(),this.trigger("ended")}handleTechDurationChange_(){this.duration(this.techGet_("duration"))}handleTechClick_(e){this.controls_&&(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.click===void 0||this.options_.userActions.click!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.click=="function"?this.options_.userActions.click.call(this,e):this.paused()?Mt(this.play()):this.pause())}handleTechDoubleClick_(e){if(!this.controls_)return;Array.prototype.some.call(this.$$(".vjs-control-bar, .vjs-modal-dialog"),i=>i.contains(e.target))||(this.options_===void 0||this.options_.userActions===void 0||this.options_.userActions.doubleClick===void 0||this.options_.userActions.doubleClick!==!1)&&(this.options_!==void 0&&this.options_.userActions!==void 0&&typeof this.options_.userActions.doubleClick=="function"?this.options_.userActions.doubleClick.call(this,e):this.isFullscreen()?this.exitFullscreen():this.requestFullscreen())}handleTechTap_(){this.userActive(!this.userActive())}handleTechTouchStart_(){this.userWasActive=this.userActive()}handleTechTouchMove_(){this.userWasActive&&this.reportUserActivity()}handleTechTouchEnd_(e){e.cancelable&&e.preventDefault()}toggleFullscreenClass_(){this.isFullscreen()?this.addClass("vjs-fullscreen"):this.removeClass("vjs-fullscreen")}documentFullscreenChange_(e){const t=e.target.player;if(t&&t!==this)return;const i=this.el();let r=$[this.fsApi_.fullscreenElement]===i;!r&&i.matches&&(r=i.matches(":"+this.fsApi_.fullscreen)),this.isFullscreen(r)}handleTechFullscreenChange_(e,t){t&&(t.nativeIOSFullscreen&&(this.addClass("vjs-ios-native-fs"),this.tech_.one("webkitendfullscreen",()=>{this.removeClass("vjs-ios-native-fs")})),this.isFullscreen(t.isFullscreen))}handleTechFullscreenError_(e,t){this.trigger("fullscreenerror",t)}togglePictureInPictureClass_(){this.isInPictureInPicture()?this.addClass("vjs-picture-in-picture"):this.removeClass("vjs-picture-in-picture")}handleTechEnterPictureInPicture_(e){this.isInPictureInPicture(!0)}handleTechLeavePictureInPicture_(e){this.isInPictureInPicture(!1)}handleTechError_(){const e=this.tech_.error();e&&this.error(e)}handleTechTextData_(){let e=null;arguments.length>1&&(e=arguments[1]),this.trigger("textdata",e)}getCache(){return this.cache_}resetCache_(){this.cache_={currentTime:0,initTime:0,inactivityTimeout:this.options_.inactivityTimeout,duration:NaN,lastVolume:1,lastPlaybackRate:this.defaultPlaybackRate(),media:null,src:"",source:{},sources:[],playbackRates:[],volume:1}}techCall_(e,t){this.ready(function(){if(e in WC)return zC(this.middleware_,this.tech_,e,t);if(e in dh)return ch(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(i){throw Z(i),i}},!0)}techGet_(e){if(!(!this.tech_||!this.tech_.isReady_)){if(e in GC)return VC(this.middleware_,this.tech_,e);if(e in dh)return ch(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){throw this.tech_[e]===void 0?(Z(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t):t.name==="TypeError"?(Z(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t):(Z(t),t)}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=Mt){this.playCallbacks_.push(e);const t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),i=!!(Za||st);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!t){this.waitToPlay_=a=>{this.play_()},this.one(["ready","loadstart"],this.waitToPlay_),!t&&i&&this.load();return}const r=this.techGet_("play");i&&this.hasClass("vjs-ended")&&this.resetProgressBar_(),r===null?this.runPlayTerminatedQueue_():this.runPlayCallbacks_(r)}runPlayTerminatedQueue_(){const e=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[],e.forEach(function(t){t()})}runPlayCallbacks_(e){const t=this.playCallbacks_.slice(0);this.playCallbacks_=[],this.playTerminatedQueue_=[],t.forEach(function(i){i(e)})}pause(){this.techCall_("pause")}paused(){return this.techGet_("paused")!==!1}played(){return this.techGet_("played")||kt(0,0)}scrubbing(e){if(typeof e>"u")return this.scrubbing_;this.scrubbing_=!!e,this.techCall_("setScrubbing",this.scrubbing_),e?this.addClass("vjs-scrubbing"):this.removeClass("vjs-scrubbing")}currentTime(e){if(e===void 0)return this.cache_.currentTime=this.techGet_("currentTime")||0,this.cache_.currentTime;if(e<0&&(e=0),!this.isReady_||this.changingSrc_||!this.tech_||!this.tech_.isReady_){this.cache_.initTime=e,this.off("canplay",this.boundApplyInitTime_),this.one("canplay",this.boundApplyInitTime_);return}this.techCall_("setCurrentTime",e),this.cache_.initTime=0,isFinite(e)&&(this.cache_.currentTime=Number(e))}applyInitTime_(){this.currentTime(this.cache_.initTime)}duration(e){if(e===void 0)return this.cache_.duration!==void 0?this.cache_.duration:NaN;e=parseFloat(e),e<0&&(e=1/0),e!==this.cache_.duration&&(this.cache_.duration=e,e===1/0?this.addClass("vjs-live"):this.removeClass("vjs-live"),isNaN(e)||this.trigger("durationchange"))}remainingTime(){return this.duration()-this.currentTime()}remainingTimeDisplay(){return Math.floor(this.duration())-Math.floor(this.currentTime())}buffered(){let e=this.techGet_("buffered");return(!e||!e.length)&&(e=kt(0,0)),e}seekable(){let e=this.techGet_("seekable");return(!e||!e.length)&&(e=kt(0,0)),e}seeking(){return this.techGet_("seeking")}ended(){return this.techGet_("ended")}networkState(){return this.techGet_("networkState")}readyState(){return this.techGet_("readyState")}bufferedPercent(){return vm(this.buffered(),this.duration())}bufferedEnd(){const e=this.buffered(),t=this.duration();let i=e.end(e.length-1);return i>t&&(i=t),i}volume(e){let t;if(e!==void 0){t=Math.max(0,Math.min(1,e)),this.cache_.volume=t,this.techCall_("setVolume",t),t>0&&this.lastVolume_(t);return}return t=parseFloat(this.techGet_("volume")),isNaN(t)?1:t}muted(e){if(e!==void 0){this.techCall_("setMuted",e);return}return this.techGet_("muted")||!1}defaultMuted(e){return e!==void 0&&this.techCall_("setDefaultMuted",e),this.techGet_("defaultMuted")||!1}lastVolume_(e){if(e!==void 0&&e!==0){this.cache_.lastVolume=e;return}return this.cache_.lastVolume}supportsFullScreen(){return this.techGet_("supportsFullScreen")||!1}isFullscreen(e){if(e!==void 0){const t=this.isFullscreen_;this.isFullscreen_=!!e,this.isFullscreen_!==t&&this.fsApi_.prefixed&&this.trigger("fullscreenchange"),this.toggleFullscreenClass_();return}return this.isFullscreen_}requestFullscreen(e){this.isInPictureInPicture()&&this.exitPictureInPicture();const t=this;return new Promise((i,r)=>{function n(){t.off("fullscreenerror",o),t.off("fullscreenchange",a)}function a(){n(),i()}function o(c,p){n(),r(p)}t.one("fullscreenchange",a),t.one("fullscreenerror",o);const u=t.requestFullscreenHelper_(e);u&&(u.then(n,n),u.then(i,r))})}requestFullscreenHelper_(e){let t;if(this.fsApi_.prefixed||(t=this.options_.fullscreen&&this.options_.fullscreen.options||{},e!==void 0&&(t=e)),this.fsApi_.requestFullscreen){const i=this.el_[this.fsApi_.requestFullscreen](t);return i&&i.then(()=>this.isFullscreen(!0),()=>this.isFullscreen(!1)),i}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("enterFullScreen"):this.enterFullWindow()}exitFullscreen(){const e=this;return new Promise((t,i)=>{function r(){e.off("fullscreenerror",a),e.off("fullscreenchange",n)}function n(){r(),t()}function a(u,c){r(),i(c)}e.one("fullscreenchange",n),e.one("fullscreenerror",a);const o=e.exitFullscreenHelper_();o&&(o.then(r,r),o.then(t,i))})}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){const e=$[this.fsApi_.exitFullscreen]();return e&&Mt(e.then(()=>this.isFullscreen(!1))),e}else this.tech_.supportsFullScreen()&&!this.options_.preferFullWindow?this.techCall_("exitFullScreen"):this.exitFullWindow()}enterFullWindow(){this.isFullscreen(!0),this.isFullWindow=!0,this.docOrigOverflow=$.documentElement.style.overflow,gt($,"keydown",this.boundFullWindowOnEscKey_),$.documentElement.style.overflow="hidden",zi($.body,"vjs-full-window"),this.trigger("enterFullWindow")}fullWindowOnEscKey(e){e.key==="Escape"&&this.isFullscreen()===!0&&(this.isFullWindow?this.exitFullWindow():this.exitFullscreen())}exitFullWindow(){this.isFullscreen(!1),this.isFullWindow=!1,ze($,"keydown",this.boundFullWindowOnEscKey_),$.documentElement.style.overflow=this.docOrigOverflow,eo($.body,"vjs-full-window"),this.trigger("exitFullWindow")}disablePictureInPicture(e){if(e===void 0)return this.techGet_("disablePictureInPicture");this.techCall_("setDisablePictureInPicture",e),this.options_.disablePictureInPicture=e,this.trigger("disablepictureinpicturechanged")}isInPictureInPicture(e){if(e!==void 0){this.isInPictureInPicture_=!!e,this.togglePictureInPictureClass_();return}return!!this.isInPictureInPicture_}requestPictureInPicture(){if(this.options_.enableDocumentPictureInPicture&&E.documentPictureInPicture){const e=$.createElement(this.el().tagName);return e.classList=this.el().classList,e.classList.add("vjs-pip-container"),this.posterImage&&e.appendChild(this.posterImage.el().cloneNode(!0)),this.titleBar&&e.appendChild(this.titleBar.el().cloneNode(!0)),e.appendChild(X("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),E.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(am(t),this.el_.parentNode.insertBefore(e,this.el_),t.document.body.appendChild(this.el_),t.document.body.classList.add("vjs-pip-window"),this.player_.isInPictureInPicture(!0),this.player_.trigger({type:"enterpictureinpicture",pipWindow:t}),t.addEventListener("pagehide",i=>{const r=i.target.querySelector(".video-js");e.parentNode.replaceChild(r,e),this.player_.isInPictureInPicture(!1),this.player_.trigger("leavepictureinpicture")}),t))}return"pictureInPictureEnabled"in $&&this.disablePictureInPicture()===!1?this.techGet_("requestPictureInPicture"):Promise.reject("No PiP mode is available")}exitPictureInPicture(){if(E.documentPictureInPicture&&E.documentPictureInPicture.window)return E.documentPictureInPicture.window.close(),Promise.resolve();if("pictureInPictureEnabled"in $)return $.exitPictureInPicture()}handleKeyDown(e){const{userActions:t}=this.options_;!t||!t.hotkeys||(r=>{const n=r.tagName.toLowerCase();if(r.isContentEditable)return!0;const a=["button","checkbox","hidden","radio","reset","submit"];return n==="input"?a.indexOf(r.type)===-1:["textarea"].indexOf(n)!==-1})(this.el_.ownerDocument.activeElement)||(typeof t.hotkeys=="function"?t.hotkeys.call(this,e):this.handleHotkeys(e))}handleHotkeys(e){const t=this.options_.userActions?this.options_.userActions.hotkeys:{},{fullscreenKey:i=a=>e.key.toLowerCase()==="f",muteKey:r=a=>e.key.toLowerCase()==="m",playPauseKey:n=a=>e.key.toLowerCase()==="k"||e.key.toLowerCase()===" "}=t;if(i.call(this,e)){e.preventDefault(),e.stopPropagation();const a=B.getComponent("FullscreenToggle");$[this.fsApi_.fullscreenEnabled]!==!1&&a.prototype.handleClick.call(this,e)}else r.call(this,e)?(e.preventDefault(),e.stopPropagation(),B.getComponent("MuteToggle").prototype.handleClick.call(this,e)):n.call(this,e)&&(e.preventDefault(),e.stopPropagation(),B.getComponent("PlayToggle").prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let i=0,r=this.options_.techOrder;i[o,Q.getTech(o)]).filter(([o,u])=>u?u.isSupported():(Z.error(`The "${o}" tech is undefined. Skipped browser support check for that tech.`),!1)),i=function(o,u,c){let p;return o.some(y=>u.some(v=>{if(p=c(y,v),p)return!0})),p};let r;const n=o=>(u,c)=>o(c,u),a=([o,u],c)=>{if(u.canPlaySource(c,this.options_[o.toLowerCase()]))return{source:c,tech:o}};return this.options_.sourceOrder?r=i(e,t,n(a)):r=i(t,e,a),r||!1}handleSrc_(e,t){if(typeof e>"u")return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();const i=Em(e);if(!i.length){this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0);return}if(this.changingSrc_=!0,t||(this.cache_.sources=i),this.updateSourceCaches_(i[0]),qC(this,i[0],(r,n)=>{if(this.middleware_=n,t||(this.cache_.sources=i),this.updateSourceCaches_(r),this.src_(r)){if(i.length>1)return this.handleSrc_(i.slice(1));this.changingSrc_=!1,this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0),this.triggerReady();return}HC(n,this.tech_)}),i.length>1){const r=()=>{this.error(null),this.handleSrc_(i.slice(1),!0)},n=()=>{this.off("error",r)};this.one("error",r),this.one("playing",n),this.resetRetryOnError_=()=>{this.off("error",r),this.off("playing",n)}}}src(e){return this.handleSrc_(e,!1)}src_(e){const t=this.selectSource([e]);return t?mm(t.tech,this.techName_)?(this.ready(function(){this.tech_.constructor.prototype.hasOwnProperty("setSource")?this.techCall_("setSource",e):this.techCall_("src",e.src),this.changingSrc_=!1},!0),!1):(this.changingSrc_=!0,this.loadTech_(t.tech,t.source),this.tech_.ready(()=>{this.changingSrc_=!1}),!1):!0}load(){if(this.tech_&&this.tech_.vhs){this.src(this.currentSource());return}this.techCall_("load")}reset(){if(this.paused())this.doReset_();else{const e=this.play();Mt(e.then(()=>this.doReset_()))}}doReset_(){this.tech_&&this.tech_.clearTracks("text"),this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.resetCache_(),this.poster(""),this.loadTech_(this.options_.techOrder[0],null),this.techCall_("reset"),this.resetControlBarUI_(),this.error(null),this.titleBar&&this.titleBar.update({title:void 0,description:void 0}),ii(this)&&this.trigger("playerreset")}resetControlBarUI_(){this.resetProgressBar_(),this.resetPlaybackRate_(),this.resetVolumeBar_()}resetProgressBar_(){this.currentTime(0);const{currentTimeDisplay:e,durationDisplay:t,progressControl:i,remainingTimeDisplay:r}=this.controlBar||{},{seekBar:n}=i||{};e&&e.updateContent(),t&&t.updateContent(),r&&r.updateContent(),n&&(n.update(),n.loadProgressBar&&n.loadProgressBar.update())}resetPlaybackRate_(){this.playbackRate(this.defaultPlaybackRate()),this.handleTechRateChange_()}resetVolumeBar_(){this.volume(1),this.trigger("volumechange")}currentSources(){const e=this.currentSource(),t=[];return Object.keys(e).length!==0&&t.push(e),this.cache_.sources||t}currentSource(){return this.cache_.source||{}}currentSrc(){return this.currentSource()&&this.currentSource().src||""}currentType(){return this.currentSource()&&this.currentSource().type||""}preload(e){if(e!==void 0){this.techCall_("setPreload",e),this.options_.preload=e;return}return this.techGet_("preload")}autoplay(e){if(e===void 0)return this.options_.autoplay||!1;let t;typeof e=="string"&&/(any|play|muted)/.test(e)||e===!0&&this.options_.normalizeAutoplay?(this.options_.autoplay=e,this.manualAutoplay_(typeof e=="string"?e:"play"),t=!1):e?this.options_.autoplay=!0:this.options_.autoplay=!1,t=typeof t>"u"?this.options_.autoplay:t,this.tech_&&this.techCall_("setAutoplay",t)}playsinline(e){return e!==void 0&&(this.techCall_("setPlaysinline",e),this.options_.playsinline=e),this.techGet_("playsinline")}loop(e){if(e!==void 0){this.techCall_("setLoop",e),this.options_.loop=e;return}return this.techGet_("loop")}poster(e){if(e===void 0)return this.poster_;e||(e=""),e!==this.poster_&&(this.poster_=e,this.techCall_("setPoster",e),this.isPosterFromTech_=!1,this.trigger("posterchange"))}handleTechPosterChange_(){if((!this.poster_||this.options_.techCanOverridePoster)&&this.tech_&&this.tech_.poster){const e=this.tech_.poster()||"";e!==this.poster_&&(this.poster_=e,this.isPosterFromTech_=!0,this.trigger("posterchange"))}}controls(e){if(e===void 0)return!!this.controls_;e=!!e,this.controls_!==e&&(this.controls_=e,this.usingNativeControls()&&this.techCall_("setControls",e),this.controls_?(this.removeClass("vjs-controls-disabled"),this.addClass("vjs-controls-enabled"),this.trigger("controlsenabled"),this.usingNativeControls()||this.addTechControlsListeners_()):(this.removeClass("vjs-controls-enabled"),this.addClass("vjs-controls-disabled"),this.trigger("controlsdisabled"),this.usingNativeControls()||this.removeTechControlsListeners_()))}usingNativeControls(e){if(e===void 0)return!!this.usingNativeControls_;e=!!e,this.usingNativeControls_!==e&&(this.usingNativeControls_=e,this.usingNativeControls_?(this.addClass("vjs-using-native-controls"),this.trigger("usingnativecontrols")):(this.removeClass("vjs-using-native-controls"),this.trigger("usingcustomcontrols")))}error(e){if(e===void 0)return this.error_||null;if(bi("beforeerror").forEach(t=>{const i=t(this,e);if(!(qt(i)&&!Array.isArray(i)||typeof i=="string"||typeof i=="number"||i===null)){this.log.error("please return a value that MediaError expects in beforeerror hooks");return}e=i}),this.options_.suppressNotSupportedError&&e&&e.code===4){const t=function(){this.error(e)};this.options_.suppressNotSupportedError=!1,this.any(["click","touchstart"],t),this.one("loadstart",function(){this.off(["click","touchstart"],t)});return}if(e===null){this.error_=null,this.removeClass("vjs-error"),this.errorDisplay&&this.errorDisplay.close();return}this.error_=new Te(e),this.addClass("vjs-error"),Z.error(`(CODE:${this.error_.code} ${Te.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger("error"),bi("error").forEach(t=>t(this,this.error_))}reportUserActivity(e){this.userActivity_=!0}userActive(e){if(e===void 0)return this.userActive_;if(e=!!e,e!==this.userActive_){if(this.userActive_=e,this.userActive_){this.userActivity_=!0,this.removeClass("vjs-user-inactive"),this.addClass("vjs-user-active"),this.trigger("useractive");return}this.tech_&&this.tech_.one("mousemove",function(t){t.stopPropagation(),t.preventDefault()}),this.userActivity_=!1,this.removeClass("vjs-user-active"),this.addClass("vjs-user-inactive"),this.trigger("userinactive")}}listenForUserActivity_(){let e,t,i;const r=de(this,this.reportUserActivity),n=function(y){(y.screenX!==t||y.screenY!==i)&&(t=y.screenX,i=y.screenY,r())},a=function(){r(),this.clearInterval(e),e=this.setInterval(r,250)},o=function(y){r(),this.clearInterval(e)};this.on("mousedown",a),this.on("mousemove",n),this.on("mouseup",o),this.on("mouseleave",o);const u=this.getChild("controlBar");u&&!st&&!Ht&&(u.on("mouseenter",function(y){this.player().options_.inactivityTimeout!==0&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0}),u.on("mouseleave",function(y){this.player().options_.inactivityTimeout=this.player().cache_.inactivityTimeout})),this.on("keydown",r),this.on("keyup",r);let c;const p=function(){if(!this.userActivity_)return;this.userActivity_=!1,this.userActive(!0),this.clearTimeout(c);const y=this.options_.inactivityTimeout;y<=0||(c=this.setTimeout(function(){this.userActivity_||this.userActive(!1)},y))};this.setInterval(p,250)}playbackRate(e){if(e!==void 0){this.techCall_("setPlaybackRate",e);return}return this.tech_&&this.tech_.featuresPlaybackRate?this.cache_.lastPlaybackRate||this.techGet_("playbackRate"):1}defaultPlaybackRate(e){return e!==void 0?this.techCall_("setDefaultPlaybackRate",e):this.tech_&&this.tech_.featuresPlaybackRate?this.techGet_("defaultPlaybackRate"):1}isAudio(e){if(e!==void 0){this.isAudio_=!!e;return}return!!this.isAudio_}updatePlayerHeightOnAudioOnlyMode_(){const e=this.getChild("ControlBar");!e||this.audioOnlyCache_.controlBarHeight===e.currentHeight()||(this.audioOnlyCache_.controlBarHeight=e.currentHeight(),this.height(this.audioOnlyCache_.controlBarHeight))}enableAudioOnlyUI_(){this.addClass("vjs-audio-only-mode");const e=this.children(),t=this.getChild("ControlBar"),i=t&&t.currentHeight();e.forEach(r=>{r!==t&&r.el_&&!r.hasClass("vjs-hidden")&&(r.hide(),this.audioOnlyCache_.hiddenChildren.push(r))}),this.audioOnlyCache_.playerHeight=this.currentHeight(),this.audioOnlyCache_.controlBarHeight=i,this.on("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.height(i),this.trigger("audioonlymodechange")}disableAudioOnlyUI_(){this.removeClass("vjs-audio-only-mode"),this.off("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.audioOnlyCache_.hiddenChildren.forEach(e=>e.show()),this.height(this.audioOnlyCache_.playerHeight),this.trigger("audioonlymodechange")}audioOnlyMode(e){if(typeof e!="boolean"||e===this.audioOnlyMode_)return this.audioOnlyMode_;if(this.audioOnlyMode_=e,e){const t=[];return this.isInPictureInPicture()&&t.push(this.exitPictureInPicture()),this.isFullscreen()&&t.push(this.exitFullscreen()),this.audioPosterMode()&&t.push(this.audioPosterMode(!1)),Promise.all(t).then(()=>this.enableAudioOnlyUI_())}return Promise.resolve().then(()=>this.disableAudioOnlyUI_())}enablePosterModeUI_(){(this.tech_&&this.tech_).hide(),this.addClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}disablePosterModeUI_(){(this.tech_&&this.tech_).show(),this.removeClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}audioPosterMode(e){return typeof e!="boolean"||e===this.audioPosterMode_?this.audioPosterMode_:(this.audioPosterMode_=e,e?this.audioOnlyMode()?this.audioOnlyMode(!1).then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.disablePosterModeUI_()}))}addTextTrack(e,t,i){if(this.tech_)return this.tech_.addTextTrack(e,t,i)}addRemoteTextTrack(e,t){if(this.tech_)return this.tech_.addRemoteTextTrack(e,t)}removeRemoteTextTrack(e={}){let{track:t}=e;if(t||(t=e),this.tech_)return this.tech_.removeRemoteTextTrack(t)}getVideoPlaybackQuality(){return this.techGet_("getVideoPlaybackQuality")}videoWidth(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0}videoHeight(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0}language(e){if(e===void 0)return this.language_;this.language_!==String(e).toLowerCase()&&(this.language_=String(e).toLowerCase(),ii(this)&&this.trigger("languagechange"))}languages(){return ce(ms.prototype.options_.languages,this.languages_)}toJSON(){const e=ce(this.options_),t=e.tracks;e.tracks=[];for(let i=0;i{this.removeChild(i)}),i.open(),i}updateCurrentBreakpoint_(){if(!this.responsive())return;const e=this.currentBreakpoint(),t=this.currentWidth();for(let i=0;ithis.addRemoteTextTrack(y,!1)),this.titleBar&&this.titleBar.update({title:p,description:a||r||""}),this.ready(t)}getMedia(){if(!this.cache_.media){const e=this.poster(),t=this.currentSources(),i=Array.prototype.map.call(this.remoteTextTracks(),n=>({kind:n.kind,label:n.label,language:n.language,src:n.src})),r={src:t,textTracks:i};return e&&(r.poster=e,r.artwork=[{src:r.poster,type:Ca(r.poster)}]),r}return ce(this.cache_.media)}static getTagSettings(e){const t={sources:[],tracks:[]},i=pi(e),r=i["data-setup"];if(Mr(e,"vjs-fill")&&(i.fill=!0),Mr(e,"vjs-fluid")&&(i.fluid=!0),r!==null)try{Object.assign(i,JSON.parse(r||"{}"))}catch(n){Z.error("data-setup",n)}if(Object.assign(t,i),e.hasChildNodes()){const n=e.childNodes;for(let a=0,o=n.length;atypeof t=="number")&&(this.cache_.playbackRates=e,this.trigger("playbackrateschange"))}};Ze.names.forEach(function(s){const e=Ze[s];Be.prototype[e.getterName]=function(){return this.tech_?this.tech_[e.getterName]():(this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName])}});Be.prototype.crossorigin=Be.prototype.crossOrigin;Be.players={};const Tr=E.navigator;Be.prototype.options_={techOrder:Q.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","titleBar","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:Tr&&(Tr.languages&&Tr.languages[0]||Tr.userLanguage||Tr.language)||"en",languages:{},notSupportedMessage:"No compatible source was found for this media.",normalizeAutoplay:!1,fullscreen:{options:{navigationUI:"hide"}},breakpoints:{},responsive:!1,audioOnlyMode:!1,audioPosterMode:!1,spatialNavigation:{enabled:!1,horizontalSeek:!1},enableSmoothSeeking:!1};eg.forEach(function(s){Be.prototype[`handleTech${Se(s)}_`]=function(){return this.trigger(s)}});B.registerComponent("Player",Be);const Aa="plugin",As="activePlugins_",_s={},wa=s=>_s.hasOwnProperty(s),ra=s=>wa(s)?_s[s]:void 0,tg=(s,e)=>{s[As]=s[As]||{},s[As][e]=!0},Da=(s,e,t)=>{const i=(t?"before":"")+"pluginsetup";s.trigger(i,e),s.trigger(i+":"+e.name,e)},PA=function(s,e){const t=function(){Da(this,{name:s,plugin:e,instance:null},!0);const i=e.apply(this,arguments);return tg(this,s),Da(this,{name:s,plugin:e,instance:i}),i};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t},Dh=(s,e)=>(e.prototype.name=s,function(...t){Da(this,{name:s,plugin:e,instance:null},!0);const i=new e(this,...t);return this[s]=()=>i,Da(this,i.getEventHash()),i});class ct{constructor(e){if(this.constructor===ct)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=e,this.log||(this.log=this.player.log.createLogger(this.name)),Iu(this),delete this.trigger,pm(this,this.constructor.defaultState),tg(e,this.name),this.dispose=this.dispose.bind(this),e.on("dispose",this.dispose)}version(){return this.constructor.VERSION}getEventHash(e={}){return e.name=this.name,e.plugin=this.constructor,e.instance=this,e}trigger(e,t={}){return Ys(this.eventBusEl_,e,this.getEventHash(t))}handleStateChanged(e){}dispose(){const{name:e,player:t}=this;this.trigger("dispose"),this.off(),t.off("dispose",this.dispose),t[As][e]=!1,this.player=this.state=null,t[e]=Dh(e,_s[e])}static isBasic(e){const t=typeof e=="string"?ra(e):e;return typeof t=="function"&&!ct.prototype.isPrototypeOf(t.prototype)}static registerPlugin(e,t){if(typeof e!="string")throw new Error(`Illegal plugin name, "${e}", must be a string, was ${typeof e}.`);if(wa(e))Z.warn(`A plugin named "${e}" already exists. You may want to avoid re-registering plugins!`);else if(Be.prototype.hasOwnProperty(e))throw new Error(`Illegal plugin name, "${e}", cannot share a name with an existing player method!`);if(typeof t!="function")throw new Error(`Illegal plugin for "${e}", must be a function, was ${typeof t}.`);return _s[e]=t,e!==Aa&&(ct.isBasic(t)?Be.prototype[e]=PA(e,t):Be.prototype[e]=Dh(e,t)),t}static deregisterPlugin(e){if(e===Aa)throw new Error("Cannot de-register base plugin.");wa(e)&&(delete _s[e],delete Be.prototype[e])}static getPlugins(e=Object.keys(_s)){let t;return e.forEach(i=>{const r=ra(i);r&&(t=t||{},t[i]=r)}),t}static getPluginVersion(e){const t=ra(e);return t&&t.VERSION||""}}ct.getPlugin=ra;ct.BASE_PLUGIN_NAME=Aa;ct.registerPlugin(Aa,ct);Be.prototype.usingPlugin=function(s){return!!this[As]&&this[As][s]===!0};Be.prototype.hasPlugin=function(s){return!!wa(s)};function LA(s,e){let t=!1;return function(...i){return t||Z.warn(s),t=!0,e.apply(this,i)}}function It(s,e,t,i){return LA(`${e} is deprecated and will be removed in ${s}.0; please use ${t} instead.`,i)}var OA={NetworkBadStatus:"networkbadstatus",NetworkRequestFailed:"networkrequestfailed",NetworkRequestAborted:"networkrequestaborted",NetworkRequestTimeout:"networkrequesttimeout",NetworkBodyParserFailed:"networkbodyparserfailed",StreamingHlsPlaylistParserError:"streaminghlsplaylistparsererror",StreamingDashManifestParserError:"streamingdashmanifestparsererror",StreamingContentSteeringParserError:"streamingcontentsteeringparsererror",StreamingVttParserError:"streamingvttparsererror",StreamingFailedToSelectNextSegment:"streamingfailedtoselectnextsegment",StreamingFailedToDecryptSegment:"streamingfailedtodecryptsegment",StreamingFailedToTransmuxSegment:"streamingfailedtotransmuxsegment",StreamingFailedToAppendSegment:"streamingfailedtoappendsegment",StreamingCodecsChangeError:"streamingcodecschangeerror"};const ig=s=>s.indexOf("#")===0?s.slice(1):s;function O(s,e,t){let i=O.getPlayer(s);if(i)return e&&Z.warn(`Player "${s}" is already initialised. Options will not be applied.`),t&&i.ready(t),i;const r=typeof s=="string"?Si("#"+ig(s)):s;if(!Xs(r))throw new TypeError("The element or ID supplied is not valid. (videojs)");const a=("getRootNode"in r?r.getRootNode()instanceof E.ShadowRoot:!1)?r.getRootNode():r.ownerDocument.body;(!r.ownerDocument.defaultView||!a.contains(r))&&Z.warn("The element supplied is not included in the DOM"),e=e||{},e.restoreEl===!0&&(e.restoreEl=(r.parentNode&&r.parentNode.hasAttribute&&r.parentNode.hasAttribute("data-vjs-player")?r.parentNode:r).cloneNode(!0)),bi("beforesetup").forEach(u=>{const c=u(r,ce(e));if(!qt(c)||Array.isArray(c)){Z.error("please return an object in beforesetup hooks");return}e=ce(e,c)});const o=B.getComponent("Player");return i=new o(r,e,t),bi("setup").forEach(u=>u(i)),i}O.hooks_=Zt;O.hooks=bi;O.hook=dC;O.hookOnce=hC;O.removeHook=Up;if(E.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&Ks()){let s=Si(".vjs-styles-defaults");if(!s){s=um("vjs-styles-defaults");const e=Si("head");e&&e.insertBefore(s,e.firstChild),cm(s,`
+ .video-js {
+ width: 300px;
+ height: 150px;
+ }
+
+ .vjs-fluid:not(.vjs-audio-only-mode) {
+ padding-top: 56.25%
+ }
+ `)}}Dl(1,O);O.VERSION=El;O.options=Be.prototype.options_;O.getPlayers=()=>Be.players;O.getPlayer=s=>{const e=Be.players;let t;if(typeof s=="string"){const i=ig(s),r=e[i];if(r)return r;t=Si("#"+i)}else t=s;if(Xs(t)){const{player:i,playerId:r}=t;if(i||e[r])return i||e[r]}};O.getAllPlayers=()=>Object.keys(Be.players).map(s=>Be.players[s]).filter(Boolean);O.players=Be.players;O.getComponent=B.getComponent;O.registerComponent=(s,e)=>(Q.isTech(e)&&Z.warn(`The ${s} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),B.registerComponent.call(B,s,e));O.getTech=Q.getTech;O.registerTech=Q.registerTech;O.use=jC;Object.defineProperty(O,"middleware",{value:{},writeable:!1,enumerable:!0});Object.defineProperty(O.middleware,"TERMINATOR",{value:Ea,writeable:!1,enumerable:!0});O.browser=Kp;O.obj=mC;O.mergeOptions=It(9,"videojs.mergeOptions","videojs.obj.merge",ce);O.defineLazyProperty=It(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",Xa);O.bind=It(9,"videojs.bind","native Function.prototype.bind",de);O.registerPlugin=ct.registerPlugin;O.deregisterPlugin=ct.deregisterPlugin;O.plugin=(s,e)=>(Z.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),ct.registerPlugin(s,e));O.getPlugins=ct.getPlugins;O.getPlugin=ct.getPlugin;O.getPluginVersion=ct.getPluginVersion;O.addLanguage=function(s,e){return s=(""+s).toLowerCase(),O.options.languages=ce(O.options.languages,{[s]:e}),O.options.languages[s]};O.log=Z;O.createLogger=$p;O.time=IC;O.createTimeRange=It(9,"videojs.createTimeRange","videojs.time.createTimeRanges",kt);O.createTimeRanges=It(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",kt);O.formatTime=It(9,"videojs.formatTime","videojs.time.formatTime",Zi);O.setFormatTime=It(9,"videojs.setFormatTime","videojs.time.setFormatTime",ym);O.resetFormatTime=It(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",_m);O.parseUrl=It(9,"videojs.parseUrl","videojs.url.parseUrl",Ou);O.isCrossOrigin=It(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",oo);O.EventTarget=yt;O.any=ku;O.on=gt;O.one=no;O.off=ze;O.trigger=Ys;O.xhr=Hf;O.TextTrack=dn;O.AudioTrack=Sm;O.VideoTrack=xm;["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(s=>{O[s]=function(){return Z.warn(`videojs.${s}() is deprecated; use videojs.dom.${s}() instead`),om[s].apply(null,arguments)}});O.computedStyle=It(9,"videojs.computedStyle","videojs.dom.computedStyle",qs);O.dom=om;O.fn=EC;O.num=lA;O.str=DC;O.url=UC;O.Error=OA;/*! @name videojs-contrib-quality-levels @version 4.1.0 @license Apache-2.0 */class RA{constructor(e){let t=this;return t.id=e.id,t.label=t.id,t.width=e.width,t.height=e.height,t.bitrate=e.bandwidth,t.frameRate=e.frameRate,t.enabled_=e.enabled,Object.defineProperty(t,"enabled",{get(){return t.enabled_()},set(i){t.enabled_(i)}}),t}}class ka extends O.EventTarget{constructor(){super();let e=this;return e.levels_=[],e.selectedIndex_=-1,Object.defineProperty(e,"selectedIndex",{get(){return e.selectedIndex_}}),Object.defineProperty(e,"length",{get(){return e.levels_.length}}),e[Symbol.iterator]=()=>e.levels_.values(),e}addQualityLevel(e){let t=this.getQualityLevelById(e.id);if(t)return t;const i=this.levels_.length;return t=new RA(e),""+i in this||Object.defineProperty(this,i,{get(){return this.levels_[i]}}),this.levels_.push(t),this.trigger({qualityLevel:t,type:"addqualitylevel"}),t}removeQualityLevel(e){let t=null;for(let i=0,r=this.length;ii&&this.selectedIndex_--;break}return t&&this.trigger({qualityLevel:e,type:"removequalitylevel"}),t}getQualityLevelById(e){for(let t=0,i=this.length;ti,s.qualityLevels.VERSION=sg,i},rg=function(s){return NA(this,O.obj.merge({},s))};O.registerPlugin("qualityLevels",rg);rg.VERSION=sg;/*! @name @videojs/http-streaming @version 3.14.2 @license Apache-2.0 */const lt=qa,Ia=(s,e)=>e&&e.responseURL&&s!==e.responseURL?e.responseURL:s,Ct=s=>O.log.debug?O.log.debug.bind(O,"VHS:",`${s} >`):function(){};function se(...s){const e=O.obj||O;return(e.merge||e.mergeOptions).apply(e,s)}function Ve(...s){const e=O.time||O;return(e.createTimeRanges||e.createTimeRanges).apply(e,s)}function MA(s){if(s.length===0)return"Buffered Ranges are empty";let e=`Buffered Ranges:
+`;for(let t=0;t ${r}. Duration (${r-i})
+`}return e}const Bt=1/30,Ft=Bt*3,ng=function(s,e){const t=[];let i;if(s&&s.length)for(i=0;i=e})},Kn=function(s,e){return ng(s,function(t){return t-Bt>=e})},BA=function(s){if(s.length<2)return Ve();const e=[];for(let t=1;t{const e=[];if(!s||!s.length)return"";for(let t=0;t "+s.end(t));return e.join(", ")},UA=function(s,e,t=1){return((s.length?s.end(s.length-1):0)-e)/t},ji=s=>{const e=[];for(let t=0;tn)){if(e>r&&e<=n){t+=n-e;continue}t+=n-r}}return t},Ju=(s,e)=>{if(!e.preload)return e.duration;let t=0;return(e.parts||[]).forEach(function(i){t+=i.duration}),(e.preloadHints||[]).forEach(function(i){i.type==="PART"&&(t+=s.partTargetDuration)}),t},Nl=s=>(s.segments||[]).reduce((e,t,i)=>(t.parts?t.parts.forEach(function(r,n){e.push({duration:r.duration,segmentIndex:i,partIndex:n,part:r,segment:t})}):e.push({duration:t.duration,segmentIndex:i,partIndex:null,segment:t,part:null}),e),[]),og=s=>{const e=s.segments&&s.segments.length&&s.segments[s.segments.length-1];return e&&e.parts||[]},lg=({preloadSegment:s})=>{if(!s)return;const{parts:e,preloadHints:t}=s;let i=(t||[]).reduce((r,n)=>r+(n.type==="PART"?1:0),0);return i+=e&&e.length?e.length:0,i},ug=(s,e)=>{if(e.endList)return 0;if(s&&s.suggestedPresentationDelay)return s.suggestedPresentationDelay;const t=og(e).length>0;return t&&e.serverControl&&e.serverControl.partHoldBack?e.serverControl.partHoldBack:t&&e.partTargetDuration?e.partTargetDuration*3:e.serverControl&&e.serverControl.holdBack?e.serverControl.holdBack:e.targetDuration?e.targetDuration*3:0},jA=function(s,e){let t=0,i=e-s.mediaSequence,r=s.segments[i];if(r){if(typeof r.start<"u")return{result:r.start,precise:!0};if(typeof r.end<"u")return{result:r.end-r.duration,precise:!0}}for(;i--;){if(r=s.segments[i],typeof r.end<"u")return{result:t+r.end,precise:!0};if(t+=Ju(s,r),typeof r.start<"u")return{result:t+r.start,precise:!0}}return{result:t,precise:!1}},qA=function(s,e){let t=0,i,r=e-s.mediaSequence;for(;r"u"&&(e=s.mediaSequence+s.segments.length),e"u"){if(s.totalDuration)return s.totalDuration;if(!s.endList)return E.Infinity}return cg(s,e,t)},Ur=function({defaultDuration:s,durationList:e,startIndex:t,endIndex:i}){let r=0;if(t>i&&([t,i]=[i,t]),t<0){for(let n=t;n0)for(let c=u-1;c>=0;c--){const p=o[c];if(a+=p.duration,n){if(a<0)continue}else if(a+Bt<=0)continue;return{partIndex:p.partIndex,segmentIndex:p.segmentIndex,startTime:r-Ur({defaultDuration:s.targetDuration,durationList:o,startIndex:u,endIndex:c})}}return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:e}}if(u<0){for(let c=u;c<0;c++)if(a-=s.targetDuration,a<0)return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:e};u=0}for(let c=u;cBt,v=a===0,b=y&&a+Bt>=0;if(!((v||b)&&c!==o.length-1)){if(n){if(a>0)continue}else if(a-Bt>=0)continue;return{partIndex:p.partIndex,segmentIndex:p.segmentIndex,startTime:r+Ur({defaultDuration:s.targetDuration,durationList:o,startIndex:u,endIndex:c})}}}return{segmentIndex:o[o.length-1].segmentIndex,partIndex:o[o.length-1].partIndex,startTime:e}},fg=function(s){return s.excludeUntil&&s.excludeUntil>Date.now()},Zu=function(s){return s.excludeUntil&&s.excludeUntil===1/0},co=function(s){const e=fg(s);return!s.disabled&&!e},zA=function(s){return s.disabled},GA=function(s){for(let e=0;e{if(s.playlists.length===1)return!0;const t=e.attributes.BANDWIDTH||Number.MAX_VALUE;return s.playlists.filter(i=>co(i)?(i.attributes.BANDWIDTH||0)!s&&!e||!s&&e||s&&!e?!1:!!(s===e||s.id&&e.id&&s.id===e.id||s.resolvedUri&&e.resolvedUri&&s.resolvedUri===e.resolvedUri||s.uri&&e.uri&&s.uri===e.uri),kh=function(s,e){const t=s&&s.mediaGroups&&s.mediaGroups.AUDIO||{};let i=!1;for(const r in t){for(const n in t[r])if(i=e(t[r][n]),i)break;if(i)break}return!!i},mn=s=>{if(!s||!s.playlists||!s.playlists.length)return kh(s,t=>t.playlists&&t.playlists.length||t.uri);for(let e=0;eXf(n))||kh(s,n=>ec(t,n))))return!1}return!0};var ut={liveEdgeDelay:ug,duration:dg,seekable:HA,getMediaInfoForTime:VA,isEnabled:co,isDisabled:zA,isExcluded:fg,isIncompatible:Zu,playlistEnd:hg,isAes:GA,hasAttribute:pg,estimateSegmentRequestTime:WA,isLowestEnabledRendition:Ml,isAudioOnly:mn,playlistMatch:ec,segmentDurationWithParts:Ju};const{log:mg}=O,ws=(s,e)=>`${s}-${e}`,gg=(s,e,t)=>`placeholder-uri-${s}-${e}-${t}`,KA=({onwarn:s,oninfo:e,manifestString:t,customTagParsers:i=[],customTagMappers:r=[],llhls:n})=>{const a=new cx;s&&a.on("warn",s),e&&a.on("info",e),i.forEach(c=>a.addParser(c)),r.forEach(c=>a.addTagMapper(c)),a.push(t),a.end();const o=a.manifest;if(n||(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach(function(c){o.hasOwnProperty(c)&&delete o[c]}),o.segments&&o.segments.forEach(function(c){["parts","preloadHints"].forEach(function(p){c.hasOwnProperty(p)&&delete c[p]})})),!o.targetDuration){let c=10;o.segments&&o.segments.length&&(c=o.segments.reduce((p,y)=>Math.max(p,y.duration),0)),s&&s({message:`manifest has no targetDuration defaulting to ${c}`}),o.targetDuration=c}const u=og(o);if(u.length&&!o.partTargetDuration){const c=u.reduce((p,y)=>Math.max(p,y.duration),0);s&&(s({message:`manifest has no partTargetDuration defaulting to ${c}`}),mg.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),o.partTargetDuration=c}return o},er=(s,e)=>{s.mediaGroups&&["AUDIO","SUBTITLES"].forEach(t=>{if(s.mediaGroups[t])for(const i in s.mediaGroups[t])for(const r in s.mediaGroups[t][i]){const n=s.mediaGroups[t][i][r];e(n,t,i,r)}})},yg=({playlist:s,uri:e,id:t})=>{s.id=t,s.playlistErrors_=0,e&&(s.uri=e),s.attributes=s.attributes||{}},XA=s=>{let e=s.playlists.length;for(;e--;){const t=s.playlists[e];yg({playlist:t,id:ws(e,t.uri)}),t.resolvedUri=lt(s.uri,t.uri),s.playlists[t.id]=t,s.playlists[t.uri]=t,t.attributes.BANDWIDTH||mg.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},YA=s=>{er(s,e=>{e.uri&&(e.resolvedUri=lt(s.uri,e.uri))})},QA=(s,e)=>{const t=ws(0,e),i={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:E.location.href,resolvedUri:E.location.href,playlists:[{uri:e,id:t,resolvedUri:e,attributes:{}}]};return i.playlists[t]=i.playlists[0],i.playlists[e]=i.playlists[0],i},_g=(s,e,t=gg)=>{s.uri=e;for(let r=0;r{if(!r.playlists||!r.playlists.length){if(i&&n==="AUDIO"&&!r.uri)for(let u=0;u(r.set(n.id,n),r),new Map)}processDateRange(e){this.pendingDateRanges_.delete(e.id),this.processedDateRanges_.set(e.id,e)}getDateRangesToProcess(){if(this.offset_===null)return[];const e={},t=[];this.pendingDateRanges_.forEach((i,r)=>{if(!this.processedDateRanges_.has(r)&&(i.startTime=i.startDate.getTime()/1e3-this.offset_,i.processDateRange=()=>this.processDateRange(i),t.push(i),!!i.class))if(e[i.class]){const n=e[i.class].push(i);i.classListIndex=n-1}else e[i.class]=[i],i.classListIndex=0});for(const i of t){const r=e[i.class]||[];i.endDate?i.endTime=i.endDate.getTime()/1e3-this.offset_:i.endOnNext&&r[i.classListIndex+1]?i.endTime=r[i.classListIndex+1].startTime:i.duration?i.endTime=i.startTime+i.duration:i.plannedDuration?i.endTime=i.startTime+i.plannedDuration:i.endTime=i.startTime}return t}trimProcessedDateRanges_(e){new Map(this.processedDateRanges_).forEach((i,r)=>{i.startDate.getTime(){const r=e.status<200||e.status>299,n=e.status>=400&&e.status<=499,a={uri:e.uri,requestType:s},o=r&&!n||i;if(t&&n)a.error=xe({},t),a.errorType=O.Error.NetworkRequestFailed;else if(e.aborted)a.errorType=O.Error.NetworkRequestAborted;else if(e.timedout)a.erroType=O.Error.NetworkRequestTimeout;else if(o){const u=i?O.Error.NetworkBodyParserFailed:O.Error.NetworkBadStatus;a.errorType=u,a.status=e.status,a.headers=e.headers}return a},{EventTarget:JA}=O,ZA=(s,e)=>{if(e.endList||!e.serverControl)return s;const t={};if(e.serverControl.canBlockReload){const{preloadSegment:i}=e;let r=e.mediaSequence+e.segments.length;if(i){const n=i.parts||[],a=lg(e)-1;a>-1&&a!==n.length-1&&(t._HLS_part=a),(a>-1||n.length)&&r--}t._HLS_msn=r}if(e.serverControl&&e.serverControl.canSkipUntil&&(t._HLS_skip=e.serverControl.canSkipDateranges?"v2":"YES"),Object.keys(t).length){const i=new E.URL(s);["_HLS_skip","_HLS_msn","_HLS_part"].forEach(function(r){t.hasOwnProperty(r)&&i.searchParams.set(r,t[r])}),s=i.toString()}return s},ew=(s,e)=>{if(!s)return e;const t=se(s,e);if(s.preloadHints&&!e.preloadHints&&delete t.preloadHints,s.parts&&!e.parts)delete t.parts;else if(s.parts&&e.parts)for(let i=0;i{const i=s.slice(),r=e.slice();t=t||0;const n=[];let a;for(let o=0;o{!s.resolvedUri&&s.uri&&(s.resolvedUri=lt(e,s.uri)),s.key&&!s.key.resolvedUri&&(s.key.resolvedUri=lt(e,s.key.uri)),s.map&&!s.map.resolvedUri&&(s.map.resolvedUri=lt(e,s.map.uri)),s.map&&s.map.key&&!s.map.key.resolvedUri&&(s.map.key.resolvedUri=lt(e,s.map.key.uri)),s.parts&&s.parts.length&&s.parts.forEach(t=>{t.resolvedUri||(t.resolvedUri=lt(e,t.uri))}),s.preloadHints&&s.preloadHints.length&&s.preloadHints.forEach(t=>{t.resolvedUri||(t.resolvedUri=lt(e,t.uri))})},bg=function(s){const e=s.segments||[],t=s.preloadSegment;if(t&&t.parts&&t.parts.length){if(t.preloadHints){for(let i=0;is===e||s.segments&&e.segments&&s.segments.length===e.segments.length&&s.endList===e.endList&&s.mediaSequence===e.mediaSequence&&s.preloadSegment===e.preloadSegment,Bl=(s,e,t=Sg)=>{const i=se(s,{}),r=i.playlists[e.id];if(!r||t(r,e))return null;e.segments=bg(e);const n=se(r,e);if(n.preloadSegment&&!e.preloadSegment&&delete n.preloadSegment,r.segments){if(e.skip){e.segments=e.segments||[];for(let a=0;a{Tg(a,n.resolvedUri)});for(let a=0;a{if(a.playlists)for(let p=0;p{const t=s.segments||[],i=t[t.length-1],r=i&&i.parts&&i.parts[i.parts.length-1],n=r&&r.duration||i&&i.duration;return e&&n?n*1e3:(s.partTargetDuration||s.targetDuration||10)*500},Ph=(s,e,t)=>{if(!s)return;const i=[];return s.forEach(r=>{if(!r.attributes)return;const{BANDWIDTH:n,RESOLUTION:a,CODECS:o}=r.attributes;i.push({id:r.id,bandwidth:n,resolution:a,codecs:o})}),{type:e,isLive:t,renditions:i}};class Ts extends JA{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=Ct("PlaylistLoader");const{withCredentials:r=!1}=i;this.src=e,this.vhs_=t,this.withCredentials=r,this.addDateRangesToTextTrack_=i.addDateRangesToTextTrack;const n=t.options_;this.customTagParsers=n&&n.customTagParsers||[],this.customTagMappers=n&&n.customTagMappers||[],this.llhls=n&&n.llhls,this.dateRangesStorage_=new Ih,this.state="HAVE_NOTHING",this.handleMediaupdatetimeout_=this.handleMediaupdatetimeout_.bind(this),this.on("mediaupdatetimeout",this.handleMediaupdatetimeout_),this.on("loadedplaylist",this.handleLoadedPlaylist_.bind(this))}handleLoadedPlaylist_(){const e=this.media();if(!e)return;this.dateRangesStorage_.setOffset(e.segments),this.dateRangesStorage_.setPendingDateRanges(e.dateRanges);const t=this.dateRangesStorage_.getDateRangesToProcess();!t.length||!this.addDateRangesToTextTrack_||this.addDateRangesToTextTrack_(t)}handleMediaupdatetimeout_(){if(this.state!=="HAVE_METADATA")return;const e=this.media();let t=lt(this.main.uri,e.uri);this.llhls&&(t=ZA(t,e)),this.state="HAVE_CURRENT_METADATA",this.request=this.vhs_.xhr({uri:t,withCredentials:this.withCredentials,requestType:"hls-playlist"},(i,r)=>{if(this.request){if(i)return this.playlistRequestError(this.request,this.media(),"HAVE_METADATA");this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})}})}playlistRequestError(e,t,i){const{uri:r,id:n}=t;this.request=null,i&&(this.state=i),this.error={playlist:this.main.playlists[n],status:e.status,message:`HLS playlist request error at URL: ${r}.`,responseText:e.responseText,code:e.status>=500?4:2,metadata:Ki({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{return KA({onwarn:({message:i})=>this.logger_(`m3u8-parser warn for ${e}: ${i}`),oninfo:({message:i})=>this.logger_(`m3u8-parser info for ${e}: ${i}`),manifestString:t,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,llhls:this.llhls})}catch(i){this.error=i,this.error.metadata={errorType:O.Error.StreamingHlsPlaylistParserError,error:i}}}haveMetadata({playlistString:e,playlistObject:t,url:i,id:r}){this.request=null,this.state="HAVE_METADATA";const n={playlistInfo:{type:"media",uri:i}};this.trigger({type:"playlistparsestart",metadata:n});const a=t||this.parseManifest_({url:i,manifestString:e});a.lastRequest=Date.now(),yg({playlist:a,uri:i,id:r});const o=Bl(this.main,a);this.targetDuration=a.partTargetDuration||a.targetDuration,this.pendingMedia_=null,o?(this.main=o,this.media_=this.main.playlists[r]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(Fl(this.media(),!!o)),n.parsedPlaylist=Ph(this.main.playlists,n.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:n}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),E.clearTimeout(this.mediaUpdateTimeout),E.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new Ih,this.off()}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e,t){if(!e)return this.media_;if(this.state==="HAVE_NOTHING")throw new Error("Cannot switch media playlist from "+this.state);if(typeof e=="string"){if(!this.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.main.playlists[e]}if(E.clearTimeout(this.finalRenditionTimeout),t){const o=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=E.setTimeout(this.media.bind(this,e,!1),o);return}const i=this.state,r=!this.media_||e.id!==this.media_.id,n=this.main.playlists[e.id];if(n&&n.endList||e.endList&&e.segments.length){this.request&&(this.request.onreadystatechange=null,this.request.abort(),this.request=null),this.state="HAVE_METADATA",this.media_=e,r&&(this.trigger("mediachanging"),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange"));return}if(this.updateMediaUpdateTimeout_(Fl(e,!0)),!r)return;if(this.state="SWITCHING_MEDIA",this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.pendingMedia_=e;const a={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:a}),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},(o,u)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=Ia(e.resolvedUri,u),o)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:a}),this.haveMetadata({playlistString:u.responseText,url:e.uri,id:e.id}),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}pause(){this.mediaUpdateTimeout&&(E.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.stopRequest(),this.state==="HAVE_NOTHING"&&(this.started=!1),this.state==="SWITCHING_MEDIA"?this.media_?this.state="HAVE_METADATA":this.state="HAVE_MAIN_MANIFEST":this.state==="HAVE_CURRENT_METADATA"&&(this.state="HAVE_METADATA")}load(e){this.mediaUpdateTimeout&&(E.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const i=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=E.setTimeout(()=>{this.mediaUpdateTimeout=null,this.load()},i);return}if(!this.started){this.start();return}t&&!t.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist")}updateMediaUpdateTimeout_(e){this.mediaUpdateTimeout&&(E.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),!(!this.media()||this.media().endList)&&(this.mediaUpdateTimeout=E.setTimeout(()=>{this.mediaUpdateTimeout=null,this.trigger("mediaupdatetimeout"),this.updateMediaUpdateTimeout_(e)},e))}start(){if(this.started=!0,typeof this.src=="object"){this.src.uri||(this.src.uri=E.location.href),this.src.resolvedUri=this.src.uri,setTimeout(()=>{this.setupInitialPlaylist(this.src)},0);return}const e={playlistInfo:{type:"multivariant",uri:this.src}};this.trigger({type:"playlistrequeststart",metadata:e}),this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials,requestType:"hls-playlist"},(t,i)=>{if(!this.request)return;if(this.request=null,t)return this.error={status:i.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:i.responseText,code:2,metadata:Ki({requestType:i.requestType,request:i,error:t})},this.state==="HAVE_NOTHING"&&(this.started=!1),this.trigger("error");this.trigger({type:"playlistrequestcomplete",metadata:e}),this.src=Ia(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});const r=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=Ph(r.playlists,e.playlistInfo.type,!1),this.trigger({type:"playlistparsecomplete",metadata:e}),this.setupInitialPlaylist(r)})}srcUri(){return typeof this.src=="string"?this.src:this.src.uri}setupInitialPlaylist(e){if(this.state="HAVE_MAIN_MANIFEST",e.playlists){this.main=e,_g(this.main,this.srcUri()),e.playlists.forEach(i=>{i.segments=bg(i),i.segments.forEach(r=>{Tg(r,i.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);return}const t=this.srcUri()||E.location.href;this.main=QA(e,t),this.haveMetadata({playlistObject:e,url:t,id:this.main.playlists[0].id}),this.trigger("loadedmetadata")}updateOrDeleteClone(e,t){const i=this.main,r=e.ID;let n=i.playlists.length;for(;n--;){const a=i.playlists[n];if(a.attributes["PATHWAY-ID"]===r){const o=a.resolvedUri,u=a.id;if(t){const c=this.createCloneURI_(a.resolvedUri,e),p=ws(r,c),y=this.createCloneAttributes_(r,a.attributes),v=this.createClonePlaylist_(a,p,e,y);i.playlists[n]=v,i.playlists[p]=v,i.playlists[c]=v}else i.playlists.splice(n,1);delete i.playlists[u],delete i.playlists[o]}}this.updateOrDeleteCloneMedia(e,t)}updateOrDeleteCloneMedia(e,t){const i=this.main,r=e.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(n=>{if(!(!i.mediaGroups[n]||!i.mediaGroups[n][r])){for(const a in i.mediaGroups[n])if(a===r){for(const o in i.mediaGroups[n][a])i.mediaGroups[n][a][o].playlists.forEach((c,p)=>{const y=i.playlists[c.id],v=y.id,b=y.resolvedUri;delete i.playlists[v],delete i.playlists[b]});delete i.mediaGroups[n][a]}}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,r=i.playlists.length,n=this.createCloneURI_(t.resolvedUri,e),a=ws(e.ID,n),o=this.createCloneAttributes_(e.ID,t.attributes),u=this.createClonePlaylist_(t,a,e,o);i.playlists[r]=u,i.playlists[a]=u,i.playlists[n]=u,this.createClonedMediaGroups_(e)}createClonedMediaGroups_(e){const t=e.ID,i=e["BASE-ID"],r=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(n=>{if(!(!r.mediaGroups[n]||r.mediaGroups[n][t]))for(const a in r.mediaGroups[n]){if(a===i)r.mediaGroups[n][t]={};else continue;for(const o in r.mediaGroups[n][a]){const u=r.mediaGroups[n][a][o];r.mediaGroups[n][t][o]=xe({},u);const c=r.mediaGroups[n][t][o],p=this.createCloneURI_(u.resolvedUri,e);c.resolvedUri=p,c.uri=p,c.playlists=[],u.playlists.forEach((y,v)=>{const b=r.playlists[y.id],C=gg(n,t,o),_=ws(t,C);if(b&&!r.playlists[_]){const D=this.createClonePlaylist_(b,_,e),w=D.resolvedUri;r.playlists[_]=D,r.playlists[w]=D}c.playlists[v]=this.createClonePlaylist_(y,_,e)})}}})}createClonePlaylist_(e,t,i,r){const n=this.createCloneURI_(e.resolvedUri,i),a={resolvedUri:n,uri:n,id:t};return e.segments&&(a.segments=[]),r&&(a.attributes=r),se(e,a)}createCloneURI_(e,t){const i=new URL(e);i.hostname=t["URI-REPLACEMENT"].HOST;const r=t["URI-REPLACEMENT"].PARAMS;for(const n of Object.keys(r))i.searchParams.set(n,r[n]);return i.href}createCloneAttributes_(e,t){const i={"PATHWAY-ID":e};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{t[r]&&(i[r]=e)}),i}getKeyIdSet(e){if(e.contentProtection){const t=new Set;for(const i in e.contentProtection){const r=e.contentProtection[i].attributes.keyId;r&&t.add(r.toLowerCase())}return t}}}const Ul=function(s,e,t,i){const r=s.responseType==="arraybuffer"?s.response:s.responseText;!e&&r&&(s.responseTime=Date.now(),s.roundTripTime=s.responseTime-s.requestTime,s.bytesReceived=r.byteLength||r.length,s.bandwidth||(s.bandwidth=Math.floor(s.bytesReceived/s.roundTripTime*8*1e3))),t.headers&&(s.responseHeaders=t.headers),e&&e.code==="ETIMEDOUT"&&(s.timedout=!0),!e&&!s.aborted&&t.statusCode!==200&&t.statusCode!==206&&t.statusCode!==0&&(e=new Error("XHR Failed with a response of: "+(s&&(r||s.responseText)))),i(e,s)},iw=(s,e)=>{if(!s||!s.size)return;let t=e;return s.forEach(i=>{t=i(t)}),t},sw=(s,e,t,i)=>{!s||!s.size||s.forEach(r=>{r(e,t,i)})},xg=function(){const s=function e(t,i){t=se({timeout:45e3},t);const r=e.beforeRequest||O.Vhs.xhr.beforeRequest,n=e._requestCallbackSet||O.Vhs.xhr._requestCallbackSet||new Set,a=e._responseCallbackSet||O.Vhs.xhr._responseCallbackSet;r&&typeof r=="function"&&(O.log.warn("beforeRequest is deprecated, use onRequest instead."),n.add(r));const o=O.Vhs.xhr.original===!0?O.xhr:O.Vhs.xhr,u=iw(n,t);n.delete(r);const c=o(u||t,function(y,v){return sw(a,c,y,v),Ul(c,y,v,i)}),p=c.abort;return c.abort=function(){return c.aborted=!0,p.apply(c,arguments)},c.uri=t.uri,c.requestType=t.requestType,c.requestTime=Date.now(),c};return s.original=!0,s},rw=function(s){let e;const t=s.offset;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=E.BigInt(s.offset)+E.BigInt(s.length)-E.BigInt(1):e=s.offset+s.length-1,"bytes="+t+"-"+e},$l=function(s){const e={};return s.byterange&&(e.Range=rw(s.byterange)),e},nw=function(s,e){return s.start(e)+"-"+s.end(e)},aw=function(s,e){const t=s.toString(16);return"00".substring(0,2-t.length)+t+(e%2?" ":"")},ow=function(s){return s>=32&&s<126?String.fromCharCode(s):"."},Eg=function(s){const e={};return Object.keys(s).forEach(t=>{const i=s[t];Qf(i)?e[t]={bytes:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength}:e[t]=i}),e},Pa=function(s){const e=s.byterange||{length:1/0,offset:0};return[e.length,e.offset,s.resolvedUri].join(",")},Cg=function(s){return s.resolvedUri},Ag=s=>{const e=Array.prototype.slice.call(s),t=16;let i="",r,n;for(let a=0;aAg(s),uw=s=>{let e="",t;for(t=0;t{if(!e.dateTimeObject)return null;const t=e.videoTimingInfo.transmuxerPrependedSeconds,r=e.videoTimingInfo.transmuxedPresentationStart+t,n=s-r;return new Date(e.dateTimeObject.getTime()+n*1e3)},hw=s=>s.transmuxedPresentationEnd-s.transmuxedPresentationStart-s.transmuxerPrependedSeconds,fw=(s,e)=>{let t;try{t=new Date(s)}catch{return null}if(!e||!e.segments||e.segments.length===0)return null;let i=e.segments[0];if(to?null:(t>new Date(n)&&(i=r),{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:ut.duration(e,e.mediaSequence+e.segments.indexOf(i)),type:i.videoTimingInfo?"accurate":"estimate"})},pw=(s,e)=>{if(!e||!e.segments||e.segments.length===0)return null;let t=0,i;for(let n=0;nt){if(s>t+r.duration*wg)return null;i=r}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:t-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}},mw=(s,e)=>{let t,i;try{t=new Date(s),i=new Date(e)}catch{}const r=t.getTime();return(i.getTime()-r)/1e3},gw=s=>{if(!s.segments||s.segments.length===0)return!1;for(let e=0;e{if(!t)throw new Error("getProgramTime: callback must be provided");if(!s||e===void 0)return t({message:"getProgramTime: playlist and time must be provided"});const i=pw(e,s);if(!i)return t({message:"valid programTime was not found"});if(i.type==="estimate")return t({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:i.estimatedStart});const r={mediaSeconds:e},n=dw(e,i.segment);return n&&(r.programDateTime=n.toISOString()),t(null,r)},Dg=({programTime:s,playlist:e,retryCount:t=2,seekTo:i,pauseAfterSeek:r=!0,tech:n,callback:a})=>{if(!a)throw new Error("seekToProgramTime: callback must be provided");if(typeof s>"u"||!e||!i)return a({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!e.endList&&!n.hasStarted_)return a({message:"player must be playing a live stream to start buffering"});if(!gw(e))return a({message:"programDateTime tags must be provided in the manifest "+e.resolvedUri});const o=fw(s,e);if(!o)return a({message:`${s} was not found in the stream`});const u=o.segment,c=mw(u.dateTimeObject,s);if(o.type==="estimate"){if(t===0)return a({message:`${s} is not buffered yet. Try again`});i(o.estimatedStart+c),n.one("seeked",()=>{Dg({programTime:s,playlist:e,retryCount:t-1,seekTo:i,pauseAfterSeek:r,tech:n,callback:a})});return}const p=u.start+c,y=()=>a(null,n.currentTime());n.one("seeked",y),r&&n.pause(),i(p)},cl=(s,e)=>{if(s.readyState===4)return e()},_w=(s,e,t,i)=>{let r=[],n,a=!1;const o=function(y,v,b,C){return v.abort(),a=!0,t(y,v,b,C)},u=function(y,v){if(a)return;if(y)return y.metadata=Ki({requestType:i,request:v,error:y}),o(y,v,"",r);const b=v.responseText.substring(r&&r.byteLength||0,v.responseText.length);if(r=Sx(r,Jf(b,!0)),n=n||Dr(r),r.length<10||n&&r.lengtho(y,v,"",r));const C=Tu(r);return C==="ts"&&r.length<188?cl(v,()=>o(y,v,"",r)):!C&&r.length<376?cl(v,()=>o(y,v,"",r)):o(null,v,C,r)},p=e({uri:s,beforeSend(y){y.overrideMimeType("text/plain; charset=x-user-defined"),y.addEventListener("progress",function({total:v,loaded:b}){return Ul(y,null,{statusCode:y.status},u)})}},function(y,v){return Ul(p,y,v,u)});return p},{EventTarget:vw}=O,Lh=function(s,e){if(!Sg(s,e)||s.sidx&&e.sidx&&(s.sidx.offset!==e.sidx.offset||s.sidx.length!==e.sidx.length))return!1;if(!s.sidx&&e.sidx||s.sidx&&!e.sidx||s.segments&&!e.segments||!s.segments&&e.segments)return!1;if(!s.segments&&!e.segments)return!0;for(let t=0;t{const r=i.attributes.NAME||t;return`placeholder-uri-${s}-${e}-${r}`},bw=({mainXml:s,srcUrl:e,clientOffset:t,sidxMapping:i,previousManifest:r})=>{const n=HE(s,{manifestUri:e,clientOffset:t,sidxMapping:i,previousManifest:r});return _g(n,e,Tw),n},Sw=(s,e)=>{er(s,(t,i,r,n)=>{(!e.mediaGroups[i][r]||!(n in e.mediaGroups[i][r]))&&delete s.mediaGroups[i][r][n]})},xw=(s,e,t)=>{let i=!0,r=se(s,{duration:e.duration,minimumUpdatePeriod:e.minimumUpdatePeriod,timelineStarts:e.timelineStarts});for(let n=0;n{if(n.playlists&&n.playlists.length){const c=n.playlists[0].id,p=Bl(r,n.playlists[0],Lh);p&&(r=p,u in r.mediaGroups[a][o]||(r.mediaGroups[a][o][u]=n),r.mediaGroups[a][o][u].playlists[0]=r.playlists[c],i=!1)}}),Sw(r,e),e.minimumUpdatePeriod!==s.minimumUpdatePeriod&&(i=!1),i?null:r},Ew=(s,e)=>(!s.map&&!e.map||!!(s.map&&e.map&&s.map.byterange.offset===e.map.byterange.offset&&s.map.byterange.length===e.map.byterange.length))&&s.uri===e.uri&&s.byterange.offset===e.byterange.offset&&s.byterange.length===e.byterange.length,Oh=(s,e)=>{const t={};for(const i in s){const n=s[i].sidx;if(n){const a=Ga(n);if(!e[a])break;const o=e[a].sidxInfo;Ew(o,n)&&(t[a]=e[a])}}return t},Cw=(s,e)=>{let i=Oh(s.playlists,e);return er(s,(r,n,a,o)=>{if(r.playlists&&r.playlists.length){const u=r.playlists;i=se(i,Oh(u,e))}}),i};class jl extends vw{constructor(e,t,i={},r){super(),this.mainPlaylistLoader_=r||this,r||(this.isMain_=!0);const{withCredentials:n=!1}=i;if(this.vhs_=t,this.withCredentials=n,this.addMetadataToTextTrack=i.addMetadataToTextTrack,!e)throw new Error("A non-empty playlist URL or object is required");this.on("minimumUpdatePeriod",()=>{this.refreshXml_()}),this.on("mediaupdatetimeout",()=>{this.refreshMedia_(this.media().id)}),this.state="HAVE_NOTHING",this.loadedPlaylists_={},this.logger_=Ct("DashPlaylistLoader"),this.isMain_?(this.mainPlaylistLoader_.srcUrl=e,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=e}requestErrored_(e,t,i){if(!this.request)return!0;if(this.request=null,e)return this.error=typeof e=="object"&&!(e instanceof Error)?e:{status:t.status,message:"DASH request error at URL: "+t.uri,response:t.response,code:2,metadata:e.metadata},i&&(this.state=i),this.trigger("error"),!0}addSidxSegments_(e,t,i){const r=e.sidx&&Ga(e.sidx);if(!e.sidx||!r||this.mainPlaylistLoader_.sidxMapping_[r]){this.mediaRequest_=E.setTimeout(()=>i(!1),0);return}const n=Ia(e.sidx.resolvedUri),a=(u,c)=>{if(this.requestErrored_(u,c,t))return;const p=this.mainPlaylistLoader_.sidxMapping_,{requestType:y}=c;let v;try{v=XE(G(c.response).subarray(8))}catch(b){b.metadata=Ki({requestType:y,request:c,parseFailure:!0}),this.requestErrored_(b,c,t);return}return p[r]={sidxInfo:e.sidx,sidx:v},yu(e,v,e.sidx.resolvedUri),i(!0)},o="dash-sidx";this.request=_w(n,this.vhs_.xhr,(u,c,p,y)=>{if(u)return a(u,c);if(!p||p!=="mp4"){const C=p||"unknown";return a({status:c.status,message:`Unsupported ${C} container type for sidx segment at URL: ${n}`,response:"",playlist:e,internal:!0,playlistExclusionDuration:1/0,code:2},c)}const{offset:v,length:b}=e.sidx.byterange;if(y.length>=b+v)return a(u,{response:y.subarray(v,v+b),status:c.status,uri:c.uri});this.request=this.vhs_.xhr({uri:n,responseType:"arraybuffer",requestType:"dash-sidx",headers:$l({byterange:e.sidx.byterange})},a)},o)}dispose(){this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},E.clearTimeout(this.minimumUpdatePeriodTimeout_),E.clearTimeout(this.mediaRequest_),E.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e){if(!e)return this.media_;if(this.state==="HAVE_NOTHING")throw new Error("Cannot switch media playlist from "+this.state);const t=this.state;if(typeof e=="string"){if(!this.mainPlaylistLoader_.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.mainPlaylistLoader_.main.playlists[e]}const i=!this.media_||e.id!==this.media_.id;if(i&&this.loadedPlaylists_[e.id]&&this.loadedPlaylists_[e.id].endList){this.state="HAVE_METADATA",this.media_=e,i&&(this.trigger("mediachanging"),this.trigger("mediachange"));return}i&&(this.media_&&this.trigger("mediachanging"),this.addSidxSegments_(e,t,r=>{this.haveMetadata({startingState:t,playlist:e})}))}haveMetadata({startingState:e,playlist:t}){this.state="HAVE_METADATA",this.loadedPlaylists_[t.id]=t,this.mediaRequest_=null,this.refreshMedia_(t.id),e==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),E.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(E.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),this.state==="HAVE_NOTHING"&&(this.started=!1)}load(e){E.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const i=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=E.setTimeout(()=>this.load(),i);return}if(!this.started){this.start();return}t&&!t.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist")}start(){if(this.started=!0,!this.isMain_){this.mediaRequest_=E.setTimeout(()=>this.haveMain_(),0);return}this.requestMain_((e,t)=>{this.haveMain_(),!this.hasPendingRequest()&&!this.media_&&this.media(this.mainPlaylistLoader_.main.playlists[0])})}requestMain_(e){const t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestrequeststart",metadata:t}),this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,requestType:"dash-manifest"},(i,r)=>{if(i){const{requestType:a}=r;i.metadata=Ki({requestType:a,request:r,error:i})}if(this.requestErrored_(i,r)){this.state==="HAVE_NOTHING"&&(this.started=!1);return}this.trigger({type:"manifestrequestcomplete",metadata:t});const n=r.responseText!==this.mainPlaylistLoader_.mainXml_;if(this.mainPlaylistLoader_.mainXml_=r.responseText,r.responseHeaders&&r.responseHeaders.date?this.mainLoaded_=Date.parse(r.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=Ia(this.mainPlaylistLoader_.srcUrl,r),n){this.handleMain_(),this.syncClientServerClock_(()=>e(r,n));return}return e(r,n)})}syncClientServerClock_(e){const t=VE(this.mainPlaylistLoader_.mainXml_);if(t===null)return this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e();if(t.method==="DIRECT")return this.mainPlaylistLoader_.clientOffset_=t.value-Date.now(),e();this.request=this.vhs_.xhr({uri:lt(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials,requestType:"dash-clock-sync"},(i,r)=>{if(!this.request)return;if(i){const{requestType:a}=r;return this.error.metadata=Ki({requestType:a,request:r,error:i}),this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()}let n;t.method==="HEAD"?!r.responseHeaders||!r.responseHeaders.date?n=this.mainLoaded_:n=Date.parse(r.responseHeaders.date):n=Date.parse(r.responseText),this.mainPlaylistLoader_.clientOffset_=n-Date.now(),e()})}haveMain_(){this.state="HAVE_MAIN_MANIFEST",this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){this.mediaRequest_=null;const e=this.mainPlaylistLoader_.main,t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestparsestart",metadata:t});let i;try{i=bw({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:e})}catch(n){this.error=n,this.error.metadata={errorType:O.Error.StreamingDashManifestParserError,error:n},this.trigger("error")}e&&(i=xw(e,i,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=i||e;const r=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];if(r&&r!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=r),(!e||i&&i.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(i),i){const{duration:n,endList:a}=i,o=[];i.playlists.forEach(c=>{o.push({id:c.id,bandwidth:c.attributes.BANDWIDTH,resolution:c.attributes.RESOLUTION,codecs:c.attributes.CODECS})});const u={duration:n,isLive:!a,renditions:o};t.parsedManifest=u,this.trigger({type:"manifestparsecomplete",metadata:t})}return!!i}updateMinimumUpdatePeriodTimeout_(){const e=this.mainPlaylistLoader_;e.createMupOnMedia_&&(e.off("loadedmetadata",e.createMupOnMedia_),e.createMupOnMedia_=null),e.minimumUpdatePeriodTimeout_&&(E.clearTimeout(e.minimumUpdatePeriodTimeout_),e.minimumUpdatePeriodTimeout_=null);let t=e.main&&e.main.minimumUpdatePeriod;if(t===0&&(e.media()?t=e.media().targetDuration*1e3:(e.createMupOnMedia_=e.updateMinimumUpdatePeriodTimeout_,e.one("loadedmetadata",e.createMupOnMedia_))),typeof t!="number"||t<=0){t<0&&this.logger_(`found invalid minimumUpdatePeriod of ${t}, not setting a timeout`);return}this.createMUPTimeout_(t)}createMUPTimeout_(e){const t=this.mainPlaylistLoader_;t.minimumUpdatePeriodTimeout_=E.setTimeout(()=>{t.minimumUpdatePeriodTimeout_=null,t.trigger("minimumUpdatePeriod"),t.createMUPTimeout_(e)},e)}refreshXml_(){this.requestMain_((e,t)=>{t&&(this.media_&&(this.media_=this.mainPlaylistLoader_.main.playlists[this.media_.id]),this.mainPlaylistLoader_.sidxMapping_=Cw(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.sidxMapping_),this.addSidxSegments_(this.media(),this.state,i=>{this.refreshMedia_(this.media().id)}))})}refreshMedia_(e){if(!e)throw new Error("refreshMedia_ must take a media id");this.media_&&this.isMain_&&this.handleMain_();const t=this.mainPlaylistLoader_.main.playlists,i=!this.media_||this.media_!==t[e];if(i?this.media_=t[e]:this.trigger("playlistunchanged"),!this.mediaUpdateTimeout){const r=()=>{this.media().endList||(this.mediaUpdateTimeout=E.setTimeout(()=>{this.trigger("mediaupdatetimeout"),r()},Fl(this.media(),!!i)))};r()}this.trigger("loadedplaylist")}addEventStreamToMetadataTrack_(e){if(e&&this.mainPlaylistLoader_.main.eventStream){const t=this.mainPlaylistLoader_.main.eventStream.map(i=>({cueTime:i.start,frames:[{data:i.messageData}]}));this.addMetadataToTextTrack("EventStream",t,this.mainPlaylistLoader_.main.duration)}}getKeyIdSet(e){if(e.contentProtection){const t=new Set;for(const i in e.contentProtection){const r=e.contentProtection[i].attributes["cenc:default_KID"];r&&t.add(r.replace(/-/g,"").toLowerCase())}return t}}}var $e={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,BACK_BUFFER_LENGTH:30,GOAL_BUFFER_LENGTH_RATE:1,INITIAL_BANDWIDTH:4194304,BANDWIDTH_VARIANCE:1.2,BUFFER_LOW_WATER_LINE:0,MAX_BUFFER_LOW_WATER_LINE:30,EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:16,BUFFER_LOW_WATER_LINE_RATE:1,BUFFER_HIGH_WATER_LINE:30};const Aw=s=>{const e=new Uint8Array(new ArrayBuffer(s.length));for(let t=0;t-1):!1},this.trigger=function(d){var f,h,m,g;if(f=l[d],!!f)if(arguments.length===2)for(m=f.length,h=0;h"u")){for(l in z)z.hasOwnProperty(l)&&(z[l]=[l.charCodeAt(0),l.charCodeAt(1),l.charCodeAt(2),l.charCodeAt(3)]);te=new Uint8Array([105,115,111,109]),ie=new Uint8Array([97,118,99,49]),Ke=new Uint8Array([0,0,0,1]),Ee=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),Gt=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),Ci={video:Ee,audio:Gt},Di=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),wi=new Uint8Array([0,0,0,0,0,0,0,0]),gn=new Uint8Array([0,0,0,0,0,0,0,0]),nc=gn,ac=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),oc=gn,Ai=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}})(),o=function(l){var d=[],f=0,h,m,g;for(h=1;h>>1,l.samplingfrequencyindex<<7|l.channelcount<<3,6,1,2]))},p=function(){return o(z.ftyp,te,Ke,te,ie)},M=function(l){return o(z.hdlr,Ci[l])},y=function(l){return o(z.mdat,l)},k=function(l){var d=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,l.duration>>>24&255,l.duration>>>16&255,l.duration>>>8&255,l.duration&255,85,196,0,0]);return l.samplerate&&(d[12]=l.samplerate>>>24&255,d[13]=l.samplerate>>>16&255,d[14]=l.samplerate>>>8&255,d[15]=l.samplerate&255),o(z.mdhd,d)},R=function(l){return o(z.mdia,k(l),M(l.type),b(l))},v=function(l){return o(z.mfhd,new Uint8Array([0,0,0,0,(l&4278190080)>>24,(l&16711680)>>16,(l&65280)>>8,l&255]))},b=function(l){return o(z.minf,l.type==="video"?o(z.vmhd,Ai):o(z.smhd,wi),u(),q(l))},C=function(l,d){for(var f=[],h=d.length;h--;)f[h]=oe(d[h]);return o.apply(null,[z.moof,v(l)].concat(f))},_=function(l){for(var d=l.length,f=[];d--;)f[d]=L(l[d]);return o.apply(null,[z.moov,w(4294967295)].concat(f).concat(D(l)))},D=function(l){for(var d=l.length,f=[];d--;)f[d]=ee(l[d]);return o.apply(null,[z.mvex].concat(f))},w=function(l){var d=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(l&4278190080)>>24,(l&16711680)>>16,(l&65280)>>8,l&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 o(z.mvhd,d)},V=function(l){var d=l.samples||[],f=new Uint8Array(4+d.length),h,m;for(m=0;m>>8),g.push(h[S].byteLength&255),g=g.concat(Array.prototype.slice.call(h[S]));for(S=0;S>>8),T.push(m[S].byteLength&255),T=T.concat(Array.prototype.slice.call(m[S]));if(x=[z.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,(f.width&65280)>>8,f.width&255,(f.height&65280)>>8,f.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]),o(z.avcC,new Uint8Array([1,f.profileIdc,f.profileCompatibility,f.levelIdc,255].concat([h.length],g,[m.length],T))),o(z.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],f.sarRatio){var A=f.sarRatio[0],P=f.sarRatio[1];x.push(o(z.pasp,new Uint8Array([(A&4278190080)>>24,(A&16711680)>>16,(A&65280)>>8,A&255,(P&4278190080)>>24,(P&16711680)>>16,(P&65280)>>8,P&255])))}return o.apply(null,x)},d=function(f){return o(z.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(f.channelcount&65280)>>8,f.channelcount&255,(f.samplesize&65280)>>8,f.samplesize&255,0,0,0,0,(f.samplerate&65280)>>8,f.samplerate&255,0,0]),c(f))}}(),I=function(l){var d=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(l.id&4278190080)>>24,(l.id&16711680)>>16,(l.id&65280)>>8,l.id&255,0,0,0,0,(l.duration&4278190080)>>24,(l.duration&16711680)>>16,(l.duration&65280)>>8,l.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,(l.width&65280)>>8,l.width&255,0,0,(l.height&65280)>>8,l.height&255,0,0]);return o(z.tkhd,d)},oe=function(l){var d,f,h,m,g,T,S;return d=o(z.tfhd,new Uint8Array([0,0,0,58,(l.id&4278190080)>>24,(l.id&16711680)>>16,(l.id&65280)>>8,l.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),T=Math.floor(l.baseMediaDecodeTime/a),S=Math.floor(l.baseMediaDecodeTime%a),f=o(z.tfdt,new Uint8Array([1,0,0,0,T>>>24&255,T>>>16&255,T>>>8&255,T&255,S>>>24&255,S>>>16&255,S>>>8&255,S&255])),g=92,l.type==="audio"?(h=le(l,g),o(z.traf,d,f,h)):(m=V(l),h=le(l,m.length+g),o(z.traf,d,f,h,m))},L=function(l){return l.duration=l.duration||4294967295,o(z.trak,I(l),R(l))},ee=function(l){var d=new Uint8Array([0,0,0,0,(l.id&4278190080)>>24,(l.id&16711680)>>16,(l.id&65280)>>8,l.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return l.type!=="video"&&(d[d.length-1]=0),o(z.trex,d)},function(){var l,d,f;f=function(h,m){var g=0,T=0,S=0,x=0;return h.length&&(h[0].duration!==void 0&&(g=1),h[0].size!==void 0&&(T=2),h[0].flags!==void 0&&(S=4),h[0].compositionTimeOffset!==void 0&&(x=8)),[0,0,g|T|S|x,1,(h.length&4278190080)>>>24,(h.length&16711680)>>>16,(h.length&65280)>>>8,h.length&255,(m&4278190080)>>>24,(m&16711680)>>>16,(m&65280)>>>8,m&255]},d=function(h,m){var g,T,S,x,A,P;for(x=h.samples||[],m+=20+16*x.length,S=f(x,m),T=new Uint8Array(S.length+x.length*16),T.set(S),g=S.length,P=0;P>>24,T[g++]=(A.duration&16711680)>>>16,T[g++]=(A.duration&65280)>>>8,T[g++]=A.duration&255,T[g++]=(A.size&4278190080)>>>24,T[g++]=(A.size&16711680)>>>16,T[g++]=(A.size&65280)>>>8,T[g++]=A.size&255,T[g++]=A.flags.isLeading<<2|A.flags.dependsOn,T[g++]=A.flags.isDependedOn<<6|A.flags.hasRedundancy<<4|A.flags.paddingValue<<1|A.flags.isNonSyncSample,T[g++]=A.flags.degradationPriority&61440,T[g++]=A.flags.degradationPriority&15,T[g++]=(A.compositionTimeOffset&4278190080)>>>24,T[g++]=(A.compositionTimeOffset&16711680)>>>16,T[g++]=(A.compositionTimeOffset&65280)>>>8,T[g++]=A.compositionTimeOffset&255;return o(z.trun,T)},l=function(h,m){var g,T,S,x,A,P;for(x=h.samples||[],m+=20+8*x.length,S=f(x,m),g=new Uint8Array(S.length+x.length*8),g.set(S),T=S.length,P=0;P>>24,g[T++]=(A.duration&16711680)>>>16,g[T++]=(A.duration&65280)>>>8,g[T++]=A.duration&255,g[T++]=(A.size&4278190080)>>>24,g[T++]=(A.size&16711680)>>>16,g[T++]=(A.size&65280)>>>8,g[T++]=A.size&255;return o(z.trun,g)},le=function(h,m){return h.type==="audio"?l(h,m):d(h,m)}}();var AT={ftyp:p,mdat:y,moof:C,moov:_,initSegment:function(l){var d=p(),f=_(l),h;return h=new Uint8Array(d.byteLength+f.byteLength),h.set(d),h.set(f,d.byteLength),h}},wT=function(l){var d,f,h=[],m=[];for(m.byteLength=0,m.nalCount=0,m.duration=0,h.byteLength=0,d=0;d1&&(d=l.shift(),l.byteLength-=d.byteLength,l.nalCount-=d.nalCount,l[0][0].dts=d.dts,l[0][0].pts=d.pts,l[0][0].duration+=d.duration),l},IT=function(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}}},lc=function(l,d){var f=IT();return f.dataOffset=d,f.compositionTimeOffset=l.pts-l.dts,f.duration=l.duration,f.size=4*l.length,f.size+=l.byteLength,l.keyFrame&&(f.flags.dependsOn=2,f.flags.isNonSyncSample=0),f},PT=function(l,d){var f,h,m,g,T,S=d||0,x=[];for(f=0;f_n.ONE_SECOND_IN_TS/2))){for(A=FT()[l.samplerate],A||(A=d[0].data),P=0;P=f?l:(d.minSegmentDts=1/0,l.filter(function(h){return h.dts>=f?(d.minSegmentDts=Math.min(d.minSegmentDts,h.dts),d.minSegmentPts=d.minSegmentDts,!0):!1}))},qT=function(l){var d,f,h=[];for(d=0;d=this.virtualRowCount&&typeof this.beforeRowOverflow=="function"&&this.beforeRowOverflow(l),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},Wt.prototype.isEmpty=function(){return this.rows.length===0?!0:this.rows.length===1?this.rows[0]==="":!1},Wt.prototype.addText=function(l){this.rows[this.rowIdx]+=l},Wt.prototype.backspace=function(){if(!this.isEmpty()){var l=this.rows[this.rowIdx];this.rows[this.rowIdx]=l.substr(0,l.length-1)}};var bn=function(l,d,f){this.serviceNum=l,this.text="",this.currentWindow=new Wt(-1),this.windows=[],this.stream=f,typeof d=="string"&&this.createTextDecoder(d)};bn.prototype.init=function(l,d){this.startPts=l;for(var f=0;f<8;f++)this.windows[f]=new Wt(f),typeof d=="function"&&(this.windows[f].beforeRowOverflow=d)},bn.prototype.setCurrentWindow=function(l){this.currentWindow=this.windows[l]},bn.prototype.createTextDecoder=function(l){if(typeof TextDecoder>"u")this.stream.trigger("log",{level:"warn",message:"The `encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(l)}catch(d){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+l+" encoding. "+d})}};var ue=function(l){l=l||{},ue.prototype.init.call(this);var d=this,f=l.captionServices||{},h={},m;Object.keys(f).forEach(g=>{m=f[g],/^SERVICE/.test(g)&&(h[g]=m.encoding)}),this.serviceEncodings=h,this.current708Packet=null,this.services={},this.push=function(g){g.type===3?(d.new708Packet(),d.add708Bytes(g)):(d.current708Packet===null&&d.new708Packet(),d.add708Bytes(g))}};ue.prototype=new vo,ue.prototype.new708Packet=function(){this.current708Packet!==null&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},ue.prototype.add708Bytes=function(l){var d=l.ccData,f=d>>>8,h=d&255;this.current708Packet.ptsVals.push(l.pts),this.current708Packet.data.push(f),this.current708Packet.data.push(h)},ue.prototype.push708Packet=function(){var l=this.current708Packet,d=l.data,f=null,h=null,m=0,g=d[m++];for(l.seq=g>>6,l.sizeCode=g&63;m>5,h=g&31,f===7&&h>0&&(g=d[m++],f=g),this.pushServiceBlock(f,m,h),h>0&&(m+=h-1)},ue.prototype.pushServiceBlock=function(l,d,f){var h,m=d,g=this.current708Packet.data,T=this.services[l];for(T||(T=this.initService(l,m));m("0"+(W&255).toString(16)).slice(-2)).join("")}if(m?(N=[S,x],l++):N=[S],d.textDecoder_&&!h)P=d.textDecoder_.decode(new Uint8Array(N));else if(m){const F=j(N);P=String.fromCharCode(parseInt(F,16))}else P=ib(T|S);return A.pendingNewLine&&!A.isEmpty()&&A.newLine(this.getPts(l)),A.pendingNewLine=!1,A.addText(P),l},ue.prototype.multiByteCharacter=function(l,d){var f=this.current708Packet.data,h=f[l+1],m=f[l+2];return Tn(h)&&Tn(m)&&(l=this.handleText(++l,d,{isMultiByte:!0})),l},ue.prototype.setCurrentWindow=function(l,d){var f=this.current708Packet.data,h=f[l],m=h&7;return d.setCurrentWindow(m),l},ue.prototype.defineWindow=function(l,d){var f=this.current708Packet.data,h=f[l],m=h&7;d.setCurrentWindow(m);var g=d.currentWindow;return h=f[++l],g.visible=(h&32)>>5,g.rowLock=(h&16)>>4,g.columnLock=(h&8)>>3,g.priority=h&7,h=f[++l],g.relativePositioning=(h&128)>>7,g.anchorVertical=h&127,h=f[++l],g.anchorHorizontal=h,h=f[++l],g.anchorPoint=(h&240)>>4,g.rowCount=h&15,h=f[++l],g.columnCount=h&63,h=f[++l],g.windowStyle=(h&56)>>3,g.penStyle=h&7,g.virtualRowCount=g.rowCount+1,l},ue.prototype.setWindowAttributes=function(l,d){var f=this.current708Packet.data,h=f[l],m=d.currentWindow.winAttr;return h=f[++l],m.fillOpacity=(h&192)>>6,m.fillRed=(h&48)>>4,m.fillGreen=(h&12)>>2,m.fillBlue=h&3,h=f[++l],m.borderType=(h&192)>>6,m.borderRed=(h&48)>>4,m.borderGreen=(h&12)>>2,m.borderBlue=h&3,h=f[++l],m.borderType+=(h&128)>>5,m.wordWrap=(h&64)>>6,m.printDirection=(h&48)>>4,m.scrollDirection=(h&12)>>2,m.justify=h&3,h=f[++l],m.effectSpeed=(h&240)>>4,m.effectDirection=(h&12)>>2,m.displayEffect=h&3,l},ue.prototype.flushDisplayed=function(l,d){for(var f=[],h=0;h<8;h++)d.windows[h].visible&&!d.windows[h].isEmpty()&&f.push(d.windows[h].getText());d.endPts=l,d.text=f.join(`
+
+`),this.pushCaption(d),d.startPts=l},ue.prototype.pushCaption=function(l){l.text!==""&&(this.trigger("data",{startPts:l.startPts,endPts:l.endPts,text:l.text,stream:"cc708_"+l.serviceNum}),l.text="",l.startPts=l.endPts)},ue.prototype.displayWindows=function(l,d){var f=this.current708Packet.data,h=f[++l],m=this.getPts(l);this.flushDisplayed(m,d);for(var g=0;g<8;g++)h&1<>4,m.offset=(h&12)>>2,m.penSize=h&3,h=f[++l],m.italics=(h&128)>>7,m.underline=(h&64)>>6,m.edgeType=(h&56)>>3,m.fontStyle=h&7,l},ue.prototype.setPenColor=function(l,d){var f=this.current708Packet.data,h=f[l],m=d.currentWindow.penColor;return h=f[++l],m.fgOpacity=(h&192)>>6,m.fgRed=(h&48)>>4,m.fgGreen=(h&12)>>2,m.fgBlue=h&3,h=f[++l],m.bgOpacity=(h&192)>>6,m.bgRed=(h&48)>>4,m.bgGreen=(h&12)>>2,m.bgBlue=h&3,h=f[++l],m.edgeRed=(h&48)>>4,m.edgeGreen=(h&12)>>2,m.edgeBlue=h&3,l},ue.prototype.setPenLocation=function(l,d){var f=this.current708Packet.data,h=f[l],m=d.currentWindow.penLoc;return d.currentWindow.pendingNewLine=!0,h=f[++l],m.row=h&15,h=f[++l],m.column=h&63,l},ue.prototype.reset=function(l,d){var f=this.getPts(l);return this.flushDisplayed(f,d),this.initService(d.serviceNum,l)};var sb={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},Sn=function(l){return l===null?"":(l=sb[l]||l,String.fromCharCode(l))},xn=14,rb=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],ki=function(){for(var l=[],d=xn+1;d--;)l.push({text:"",indent:0,offset:0});return l},me=function(l,d){me.prototype.init.call(this),this.field_=l||0,this.dataChannel_=d||0,this.name_="CC"+((this.field_<<1|this.dataChannel_)+1),this.setConstants(),this.reset(),this.push=function(f){var h,m,g,T,S;if(h=f.ccData&32639,h===this.lastControlCode_){this.lastControlCode_=null;return}if((h&61440)===4096?this.lastControlCode_=h:h!==this.PADDING_&&(this.lastControlCode_=null),g=h>>>8,T=h&255,h!==this.PADDING_)if(h===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(h===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(f.pts),this.flushDisplayed(f.pts),m=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=m,this.startPts_=f.pts;else if(h===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(f.pts);else if(h===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(f.pts);else if(h===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(f.pts);else if(h===this.CARRIAGE_RETURN_)this.clearFormatting(f.pts),this.flushDisplayed(f.pts),this.shiftRowsUp_(),this.startPts_=f.pts;else if(h===this.BACKSPACE_)this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1);else if(h===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(f.pts),this.displayed_=ki();else if(h===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=ki();else if(h===this.RESUME_DIRECT_CAPTIONING_)this.mode_!=="paintOn"&&(this.flushDisplayed(f.pts),this.displayed_=ki()),this.mode_="paintOn",this.startPts_=f.pts;else if(this.isSpecialCharacter(g,T))g=(g&3)<<8,S=Sn(g|T),this[this.mode_](f.pts,S),this.column_++;else if(this.isExtCharacter(g,T))this.mode_==="popOn"?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),g=(g&3)<<8,S=Sn(g|T),this[this.mode_](f.pts,S),this.column_++;else if(this.isMidRowCode(g,T))this.clearFormatting(f.pts),this[this.mode_](f.pts," "),this.column_++,(T&14)===14&&this.addFormatting(f.pts,["i"]),(T&1)===1&&this.addFormatting(f.pts,["u"]);else if(this.isOffsetControlCode(g,T)){const A=T&3;this.nonDisplayed_[this.row_].offset=A,this.column_+=A}else if(this.isPAC(g,T)){var x=rb.indexOf(h&7968);if(this.mode_==="rollUp"&&(x-this.rollUpRows_+1<0&&(x=this.rollUpRows_-1),this.setRollUp(f.pts,x)),x!==this.row_&&x>=0&&x<=14&&(this.clearFormatting(f.pts),this.row_=x),T&1&&this.formatting_.indexOf("u")===-1&&this.addFormatting(f.pts,["u"]),(h&16)===16){const A=(h&14)>>1;this.column_=A*4,this.nonDisplayed_[this.row_].indent+=A}this.isColorPAC(T)&&(T&14)===14&&this.addFormatting(f.pts,["i"])}else this.isNormalChar(g)&&(T===0&&(T=null),S=Sn(g),S+=Sn(T),this[this.mode_](f.pts,S),this.column_+=S.length)}};me.prototype=new vo,me.prototype.flushDisplayed=function(l){const d=h=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+h+"."})},f=[];this.displayed_.forEach((h,m)=>{if(h&&h.text&&h.text.length){try{h.text=h.text.trim()}catch{d(m)}h.text.length&&f.push({text:h.text,line:m+1,position:10+Math.min(70,h.indent*10)+h.offset*2.5})}else h==null&&d(m)}),f.length&&this.trigger("data",{startPts:this.startPts_,endPts:l,content:f,stream:this.name_})},me.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=ki(),this.nonDisplayed_=ki(),this.lastControlCode_=null,this.column_=0,this.row_=xn,this.rollUpRows_=2,this.formatting_=[]},me.prototype.setConstants=function(){this.dataChannel_===0?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):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},me.prototype.isSpecialCharacter=function(l,d){return l===this.EXT_&&d>=48&&d<=63},me.prototype.isExtCharacter=function(l,d){return(l===this.EXT_+1||l===this.EXT_+2)&&d>=32&&d<=63},me.prototype.isMidRowCode=function(l,d){return l===this.EXT_&&d>=32&&d<=47},me.prototype.isOffsetControlCode=function(l,d){return l===this.OFFSET_&&d>=33&&d<=35},me.prototype.isPAC=function(l,d){return l>=this.BASE_&&l=64&&d<=127},me.prototype.isColorPAC=function(l){return l>=64&&l<=79||l>=96&&l<=127},me.prototype.isNormalChar=function(l){return l>=32&&l<=127},me.prototype.setRollUp=function(l,d){if(this.mode_!=="rollUp"&&(this.row_=xn,this.mode_="rollUp",this.flushDisplayed(l),this.nonDisplayed_=ki(),this.displayed_=ki()),d!==void 0&&d!==this.row_)for(var f=0;f"},"");this[this.mode_](l,f)},me.prototype.clearFormatting=function(l){if(this.formatting_.length){var d=this.formatting_.reverse().reduce(function(f,h){return f+""+h+">"},"");this.formatting_=[],this[this.mode_](l,d)}},me.prototype.popOn=function(l,d){var f=this.nonDisplayed_[this.row_].text;f+=d,this.nonDisplayed_[this.row_].text=f},me.prototype.rollUp=function(l,d){var f=this.displayed_[this.row_].text;f+=d,this.displayed_[this.row_].text=f},me.prototype.shiftRowsUp_=function(){var l;for(l=0;ld&&(f=-1);Math.abs(d-l)>ob;)l+=f*ab;return l},bo=function(l){var d,f;bo.prototype.init.call(this),this.type_=l||mc,this.push=function(h){if(h.type==="metadata"){this.trigger("data",h);return}this.type_!==mc&&h.type!==this.type_||(f===void 0&&(f=h.dts),h.dts=To(h.dts,f),h.pts=To(h.pts,f),d=h.dts,this.trigger("data",h))},this.flush=function(){f=d,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){f=void 0,d=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};bo.prototype=new nb;var gc={TimestampRolloverStream:bo,handleRollover:To},lb=(l,d,f)=>{if(!l)return-1;for(var h=f;h";l.data[0]===An.Utf8&&(f=Cn(l.data,0,d),!(f<0)&&(l.mimeType=ir(l.data,d,f),d=f+1,l.pictureType=l.data[d],d++,h=Cn(l.data,0,d),!(h<0)&&(l.description=tr(l.data,d,h),d=h+1,l.mimeType===m?l.url=ir(l.data,d,l.data.length):l.pictureData=l.data.subarray(d,l.data.length))))},"T*":function(l){l.data[0]===An.Utf8&&(l.value=tr(l.data,1,l.data.length).replace(/\0*$/,""),l.values=l.value.split("\0"))},TXXX:function(l){var d;l.data[0]===An.Utf8&&(d=Cn(l.data,0,1),d!==-1&&(l.description=tr(l.data,1,d),l.value=tr(l.data,d+1,l.data.length).replace(/\0*$/,""),l.data=l.value))},"W*":function(l){l.url=ir(l.data,0,l.data.length).replace(/\0.*$/,"")},WXXX:function(l){var d;l.data[0]===An.Utf8&&(d=Cn(l.data,0,1),d!==-1&&(l.description=tr(l.data,1,d),l.url=ir(l.data,d+1,l.data.length).replace(/\0.*$/,"")))},PRIV:function(l){var d;for(d=0;d>>2;W*=4,W+=F[7]&3,P.timeStamp=W,S.pts===void 0&&S.dts===void 0&&(S.pts=P.timeStamp,S.dts=P.timeStamp),this.trigger("timestamp",P)}S.frames.push(P),x+=10,x+=A}while(x>>4>1&&(T+=m[T]+1),g.pid===0)g.type="pat",l(m.subarray(T),g),this.trigger("data",g);else if(g.pid===this.pmtPid)for(g.type="pmt",l(m.subarray(T),g),this.trigger("data",g);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else this.programMapTable===void 0?this.packetsWaitingForPmt.push([m,T,g]):this.processPes_(m,T,g)},this.processPes_=function(m,g,T){T.pid===this.programMapTable.video?T.streamType=At.H264_STREAM_TYPE:T.pid===this.programMapTable.audio?T.streamType=At.ADTS_STREAM_TYPE:T.streamType=this.programMapTable["timed-metadata"][T.pid],T.type="pes",T.data=m.subarray(g),this.trigger("data",T)}},nr.prototype=new So,nr.STREAM_TYPES={h264:27,adts:15},kn=function(){var l=this,d=!1,f={data:[],size:0},h={data:[],size:0},m={data:[],size:0},g,T=function(x,A){var P;const N=x[0]<<16|x[1]<<8|x[2];A.data=new Uint8Array,N===1&&(A.packetLength=6+(x[4]<<8|x[5]),A.dataAlignmentIndicator=(x[6]&4)!==0,P=x[7],P&192&&(A.pts=(x[9]&14)<<27|(x[10]&255)<<20|(x[11]&254)<<12|(x[12]&255)<<5|(x[13]&254)>>>3,A.pts*=4,A.pts+=(x[13]&6)>>>1,A.dts=A.pts,P&64&&(A.dts=(x[14]&14)<<27|(x[15]&255)<<20|(x[16]&254)<<12|(x[17]&255)<<5|(x[18]&254)>>>3,A.dts*=4,A.dts+=(x[18]&6)>>>1)),A.data=x.subarray(9+x[8]))},S=function(x,A,P){var N=new Uint8Array(x.size),j={type:A},F=0,W=0,Y=!1,Re;if(!(!x.data.length||x.size<9)){for(j.trackId=x.data[0].pid,F=0;F>5,x=((d[m+6]&3)+1)*1024,A=x*yb/Tc[(d[m+2]&60)>>>2],d.byteLength-m>>6&3)+1,channelcount:(d[m+2]&1)<<2|(d[m+3]&192)>>>6,samplerate:Tc[(d[m+2]&60)>>>2],samplingfrequencyindex:(d[m+2]&60)>>>2,samplesize:16,data:d.subarray(m+7+T,m+g)}),f++,m+=g}typeof P=="number"&&(this.skipWarn_(P,m),P=null),d=d.subarray(m)}},this.flush=function(){f=0,this.trigger("done")},this.reset=function(){d=void 0,this.trigger("reset")},this.endTimeline=function(){d=void 0,this.trigger("endedtimeline")}},In.prototype=new gb;var _b=In,bc;bc=function(l){var d=l.byteLength,f=0,h=0;this.length=function(){return 8*d},this.bitsAvailable=function(){return 8*d+h},this.loadWord=function(){var m=l.byteLength-d,g=new Uint8Array(4),T=Math.min(4,d);if(T===0)throw new Error("no bytes available");g.set(l.subarray(m,m+T)),f=new DataView(g.buffer).getUint32(0),h=T*8,d-=T},this.skipBits=function(m){var g;h>m?(f<<=m,h-=m):(m-=h,g=Math.floor(m/8),m-=g*8,d-=g,this.loadWord(),f<<=m,h-=m)},this.readBits=function(m){var g=Math.min(h,m),T=f>>>32-g;return h-=g,h>0?f<<=g:d>0&&this.loadWord(),g=m-g,g>0?T<>>m)return f<<=m,h-=m,m;return this.loadWord(),m+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var m=this.skipLeadingZeros();return this.readBits(m+1)-1},this.readExpGolomb=function(){var m=this.readUnsignedExpGolomb();return 1&m?1+m>>>1:-1*(m>>>1)},this.readBoolean=function(){return this.readBits(1)===1},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};var vb=bc,Sc=t,Tb=vb,Pn,ar,xc;ar=function(){var l=0,d,f;ar.prototype.init.call(this),this.push=function(h){var m;f?(m=new Uint8Array(f.byteLength+h.data.byteLength),m.set(f),m.set(h.data,f.byteLength),f=m):f=h.data;for(var g=f.byteLength;l3&&this.trigger("data",f.subarray(l+3)),f=null,l=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}},ar.prototype=new Sc,xc={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},Pn=function(){var l=new ar,d,f,h,m,g,T,S;Pn.prototype.init.call(this),d=this,this.push=function(x){x.type==="video"&&(f=x.trackId,h=x.pts,m=x.dts,l.push(x))},l.on("data",function(x){var A={trackId:f,pts:h,dts:m,data:x,nalUnitTypeCode:x[0]&31};switch(A.nalUnitTypeCode){case 5:A.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:A.nalUnitType="sei_rbsp",A.escapedRBSP=g(x.subarray(1));break;case 7:A.nalUnitType="seq_parameter_set_rbsp",A.escapedRBSP=g(x.subarray(1)),A.config=T(A.escapedRBSP);break;case 8:A.nalUnitType="pic_parameter_set_rbsp";break;case 9:A.nalUnitType="access_unit_delimiter_rbsp";break}d.trigger("data",A)}),l.on("done",function(){d.trigger("done")}),l.on("partialdone",function(){d.trigger("partialdone")}),l.on("reset",function(){d.trigger("reset")}),l.on("endedtimeline",function(){d.trigger("endedtimeline")}),this.flush=function(){l.flush()},this.partialFlush=function(){l.partialFlush()},this.reset=function(){l.reset()},this.endTimeline=function(){l.endTimeline()},S=function(x,A){var P=8,N=8,j,F;for(j=0;j>4;return f=f>=0?f:0,m?f+20:f+10},Cc=function(l,d){return l.length-d<10||l[d]!==73||l[d+1]!==68||l[d+2]!==51?d:(d+=Ec(l,d),Cc(l,d))},xb=function(l){var d=Cc(l,0);return l.length>=d+2&&(l[d]&255)===255&&(l[d+1]&240)===240&&(l[d+1]&22)===16},Ac=function(l){return l[0]<<21|l[1]<<14|l[2]<<7|l[3]},Eb=function(l,d,f){var h,m="";for(h=d;h>5,h=l[d+4]<<3,m=l[d+3]&6144;return m|h|f},wb=function(l,d){return l[d]===73&&l[d+1]===68&&l[d+2]===51?"timed-metadata":l[d]&!0&&(l[d+1]&240)===240?"audio":null},Db=function(l){for(var d=0;d+5>>2]}return null},kb=function(l){var d,f,h,m;d=10,l[5]&64&&(d+=4,d+=Ac(l.subarray(10,14)));do{if(f=Ac(l.subarray(d+4,d+8)),f<1)return null;if(m=String.fromCharCode(l[d],l[d+1],l[d+2],l[d+3]),m==="PRIV"){h=l.subarray(d+10,d+f+10);for(var g=0;g>>2;return x*=4,x+=S[7]&3,x}break}}d+=10,d+=f}while(d=3;){if(l[m]===73&&l[m+1]===68&&l[m+2]===51){if(l.length-m<10||(h=wc.parseId3TagSize(l,m),m+h>l.length))break;T={type:"timed-metadata",data:l.subarray(m,m+h)},this.trigger("data",T),m+=h;continue}else if((l[m]&255)===255&&(l[m+1]&240)===240){if(l.length-m<7||(h=wc.parseAdtsSize(l,m),m+h>l.length))break;S={type:"audio",data:l.subarray(m,m+h),pts:d,dts:d},this.trigger("data",S),m+=h;continue}m++}g=l.length-m,g>0?l=l.subarray(m):l=new Uint8Array},this.reset=function(){l=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){l=new Uint8Array,this.trigger("endedtimeline")}},Ln.prototype=new Ib;var Pb=Ln,Lb=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],Ob=Lb,Rb=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],Nb=Rb,On=t,or=AT,lr=NT,Rn=VT,wt=XT,Kt=mb,Nn=fe,Dc=_b,Mb=bb.H264Stream,Bb=Pb,Fb=Ao.isLikelyAacData,Ub=fe.ONE_SECOND_IN_TS,wo=Ob,Do=Nb,ur,ss,Mn,Ii,$b=function(l,d){d.stream=l,this.trigger("log",d)},kc=function(l,d){for(var f=Object.keys(d),h=0;h=-A&&N<=x&&(!j||P>N)&&(j=W,P=N)));return j?j.gop:null},this.alignGopsAtStart_=function(S){var x,A,P,N,j,F,W,Y;for(j=S.byteLength,F=S.nalCount,W=S.duration,x=A=0;xP.pts){x++;continue}A++,j-=N.byteLength,F-=N.nalCount,W-=N.duration}return A===0?S:A===S.length?null:(Y=S.slice(A),Y.byteLength=j,Y.duration=W,Y.nalCount=F,Y.pts=Y[0].pts,Y.dts=Y[0].dts,Y)},this.alignGopsAtEnd_=function(S){var x,A,P,N,j,F;for(x=m.length-1,A=S.length-1,j=null,F=!1;x>=0&&A>=0;){if(P=m[x],N=S[A],P.pts===N.pts){F=!0;break}if(P.pts>N.pts){x--;continue}x===m.length-1&&(j=A),A--}if(!F&&j===null)return null;var W;if(F?W=A:W=j,W===0)return S;var Y=S.slice(W),Re=Y.reduce(function(_t,Li){return _t.byteLength+=Li.byteLength,_t.duration+=Li.duration,_t.nalCount+=Li.nalCount,_t},{byteLength:0,duration:0,nalCount:0});return Y.byteLength=Re.byteLength,Y.duration=Re.duration,Y.nalCount=Re.nalCount,Y.pts=Y[0].pts,Y.dts=Y[0].dts,Y},this.alignGopsWith=function(S){m=S}},ur.prototype=new On,Ii=function(l,d){this.numberOfTracks=0,this.metadataStream=d,l=l||{},typeof l.remux<"u"?this.remuxTracks=!!l.remux:this.remuxTracks=!0,typeof l.keepOriginalTimestamps=="boolean"?this.keepOriginalTimestamps=l.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,Ii.prototype.init.call(this),this.push=function(f){if(f.content||f.text)return this.pendingCaptions.push(f);if(f.frames)return this.pendingMetadata.push(f);this.pendingTracks.push(f.track),this.pendingBytes+=f.boxes.byteLength,f.track.type==="video"&&(this.videoTrack=f.track,this.pendingBoxes.push(f.boxes)),f.track.type==="audio"&&(this.audioTrack=f.track,this.pendingBoxes.unshift(f.boxes))}},Ii.prototype=new On,Ii.prototype.flush=function(l){var d=0,f={captions:[],captionStreams:{},metadata:[],info:{}},h,m,g,T=0,S;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0);return}}if(this.videoTrack?(T=this.videoTrack.timelineStartInfo.pts,Do.forEach(function(x){f.info[x]=this.videoTrack[x]},this)):this.audioTrack&&(T=this.audioTrack.timelineStartInfo.pts,wo.forEach(function(x){f.info[x]=this.audioTrack[x]},this)),this.videoTrack||this.audioTrack){for(this.pendingTracks.length===1?f.type=this.pendingTracks[0].type:f.type="combined",this.emittedTracks+=this.pendingTracks.length,g=or.initSegment(this.pendingTracks),f.initSegment=new Uint8Array(g.byteLength),f.initSegment.set(g),f.data=new Uint8Array(this.pendingBytes),S=0;S=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},Ii.prototype.setRemux=function(l){this.remuxTracks=l},Mn=function(l){var d=this,f=!0,h,m;Mn.prototype.init.call(this),l=l||{},this.baseMediaDecodeTime=l.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var g={};this.transmuxPipeline_=g,g.type="aac",g.metadataStream=new Kt.MetadataStream,g.aacStream=new Bb,g.audioTimestampRolloverStream=new Kt.TimestampRolloverStream("audio"),g.timedMetadataTimestampRolloverStream=new Kt.TimestampRolloverStream("timed-metadata"),g.adtsStream=new Dc,g.coalesceStream=new Ii(l,g.metadataStream),g.headOfPipeline=g.aacStream,g.aacStream.pipe(g.audioTimestampRolloverStream).pipe(g.adtsStream),g.aacStream.pipe(g.timedMetadataTimestampRolloverStream).pipe(g.metadataStream).pipe(g.coalesceStream),g.metadataStream.on("timestamp",function(T){g.aacStream.setTimestamp(T.timeStamp)}),g.aacStream.on("data",function(T){T.type!=="timed-metadata"&&T.type!=="audio"||g.audioSegmentStream||(m=m||{timelineStartInfo:{baseMediaDecodeTime:d.baseMediaDecodeTime},codec:"adts",type:"audio"},g.coalesceStream.numberOfTracks++,g.audioSegmentStream=new ss(m,l),g.audioSegmentStream.on("log",d.getLogTrigger_("audioSegmentStream")),g.audioSegmentStream.on("timingInfo",d.trigger.bind(d,"audioTimingInfo")),g.adtsStream.pipe(g.audioSegmentStream).pipe(g.coalesceStream),d.trigger("trackinfo",{hasAudio:!!m,hasVideo:!!h}))}),g.coalesceStream.on("data",this.trigger.bind(this,"data")),g.coalesceStream.on("done",this.trigger.bind(this,"done")),kc(this,g)},this.setupTsPipeline=function(){var g={};this.transmuxPipeline_=g,g.type="ts",g.metadataStream=new Kt.MetadataStream,g.packetStream=new Kt.TransportPacketStream,g.parseStream=new Kt.TransportParseStream,g.elementaryStream=new Kt.ElementaryStream,g.timestampRolloverStream=new Kt.TimestampRolloverStream,g.adtsStream=new Dc,g.h264Stream=new Mb,g.captionStream=new Kt.CaptionStream(l),g.coalesceStream=new Ii(l,g.metadataStream),g.headOfPipeline=g.packetStream,g.packetStream.pipe(g.parseStream).pipe(g.elementaryStream).pipe(g.timestampRolloverStream),g.timestampRolloverStream.pipe(g.h264Stream),g.timestampRolloverStream.pipe(g.adtsStream),g.timestampRolloverStream.pipe(g.metadataStream).pipe(g.coalesceStream),g.h264Stream.pipe(g.captionStream).pipe(g.coalesceStream),g.elementaryStream.on("data",function(T){var S;if(T.type==="metadata"){for(S=T.tracks.length;S--;)!h&&T.tracks[S].type==="video"?(h=T.tracks[S],h.timelineStartInfo.baseMediaDecodeTime=d.baseMediaDecodeTime):!m&&T.tracks[S].type==="audio"&&(m=T.tracks[S],m.timelineStartInfo.baseMediaDecodeTime=d.baseMediaDecodeTime);h&&!g.videoSegmentStream&&(g.coalesceStream.numberOfTracks++,g.videoSegmentStream=new ur(h,l),g.videoSegmentStream.on("log",d.getLogTrigger_("videoSegmentStream")),g.videoSegmentStream.on("timelineStartInfo",function(x){m&&!l.keepOriginalTimestamps&&(m.timelineStartInfo=x,g.audioSegmentStream.setEarliestDts(x.dts-d.baseMediaDecodeTime))}),g.videoSegmentStream.on("processedGopsInfo",d.trigger.bind(d,"gopInfo")),g.videoSegmentStream.on("segmentTimingInfo",d.trigger.bind(d,"videoSegmentTimingInfo")),g.videoSegmentStream.on("baseMediaDecodeTime",function(x){m&&g.audioSegmentStream.setVideoBaseMediaDecodeTime(x)}),g.videoSegmentStream.on("timingInfo",d.trigger.bind(d,"videoTimingInfo")),g.h264Stream.pipe(g.videoSegmentStream).pipe(g.coalesceStream)),m&&!g.audioSegmentStream&&(g.coalesceStream.numberOfTracks++,g.audioSegmentStream=new ss(m,l),g.audioSegmentStream.on("log",d.getLogTrigger_("audioSegmentStream")),g.audioSegmentStream.on("timingInfo",d.trigger.bind(d,"audioTimingInfo")),g.audioSegmentStream.on("segmentTimingInfo",d.trigger.bind(d,"audioSegmentTimingInfo")),g.adtsStream.pipe(g.audioSegmentStream).pipe(g.coalesceStream)),d.trigger("trackinfo",{hasAudio:!!m,hasVideo:!!h})}}),g.coalesceStream.on("data",this.trigger.bind(this,"data")),g.coalesceStream.on("id3Frame",function(T){T.dispatchType=g.metadataStream.dispatchType,d.trigger("id3Frame",T)}),g.coalesceStream.on("caption",this.trigger.bind(this,"caption")),g.coalesceStream.on("done",this.trigger.bind(this,"done")),kc(this,g)},this.setBaseMediaDecodeTime=function(g){var T=this.transmuxPipeline_;l.keepOriginalTimestamps||(this.baseMediaDecodeTime=g),m&&(m.timelineStartInfo.dts=void 0,m.timelineStartInfo.pts=void 0,wt.clearDtsInfo(m),T.audioTimestampRolloverStream&&T.audioTimestampRolloverStream.discontinuity()),h&&(T.videoSegmentStream&&(T.videoSegmentStream.gopCache_=[]),h.timelineStartInfo.dts=void 0,h.timelineStartInfo.pts=void 0,wt.clearDtsInfo(h),T.captionStream.reset()),T.timestampRolloverStream&&T.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(g){m&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(g)},this.setRemux=function(g){var T=this.transmuxPipeline_;l.remux=g,T&&T.coalesceStream&&T.coalesceStream.setRemux(g)},this.alignGopsWith=function(g){h&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(g)},this.getLogTrigger_=function(g){var T=this;return function(S){S.stream=g,T.trigger("log",S)}},this.push=function(g){if(f){var T=Fb(g);T&&this.transmuxPipeline_.type!=="aac"?this.setupAacPipeline():!T&&this.transmuxPipeline_.type!=="ts"&&this.setupTsPipeline(),f=!1}this.transmuxPipeline_.headOfPipeline.push(g)},this.flush=function(){f=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}},Mn.prototype=new On;var jb={Transmuxer:Mn,VideoSegmentStream:ur,AudioSegmentStream:ss,AUDIO_PROPERTIES:wo,VIDEO_PROPERTIES:Do,generateSegmentTimingInfo:ko},qb=function(l){return l>>>0},Hb=function(l){return("00"+l.toString(16)).slice(-2)},Bn={toUnsigned:qb,toHexString:Hb},Vb=function(l){var d="";return d+=String.fromCharCode(l[0]),d+=String.fromCharCode(l[1]),d+=String.fromCharCode(l[2]),d+=String.fromCharCode(l[3]),d},Pc=Vb,zb=Bn.toUnsigned,Gb=Pc,Lc=function(l,d){var f=[],h,m,g,T,S;if(!d.length)return null;for(h=0;h1?h+m:l.byteLength,g===d[0]&&(d.length===1?f.push(l.subarray(h+8,T)):(S=Lc(l.subarray(h+8,T),d.slice(1)),S.length&&(f=f.concat(S)))),h=T;return f},Oc=Lc,Wb=Bn.toUnsigned,Kb=n.getUint64,Xb=function(l){var d={version:l[0],flags:new Uint8Array(l.subarray(1,4))};return d.version===1?d.baseMediaDecodeTime=Kb(l.subarray(4)):d.baseMediaDecodeTime=Wb(l[4]<<24|l[5]<<16|l[6]<<8|l[7]),d},Rc=Xb,Yb=function(l){return{isLeading:(l[0]&12)>>>2,dependsOn:l[0]&3,isDependedOn:(l[1]&192)>>>6,hasRedundancy:(l[1]&48)>>>4,paddingValue:(l[1]&14)>>>1,isNonSyncSample:l[1]&1,degradationPriority:l[2]<<8|l[3]}},Qb=Yb,Nc=Qb,Jb=function(l){var d={version:l[0],flags:new Uint8Array(l.subarray(1,4)),samples:[]},f=new DataView(l.buffer,l.byteOffset,l.byteLength),h=d.flags[2]&1,m=d.flags[2]&4,g=d.flags[1]&1,T=d.flags[1]&2,S=d.flags[1]&4,x=d.flags[1]&8,A=f.getUint32(4),P=8,N;for(h&&(d.dataOffset=f.getInt32(P),P+=4),m&&A&&(N={flags:Nc(l.subarray(P,P+4))},P+=4,g&&(N.duration=f.getUint32(P),P+=4),T&&(N.size=f.getUint32(P),P+=4),x&&(d.version===1?N.compositionTimeOffset=f.getInt32(P):N.compositionTimeOffset=f.getUint32(P),P+=4),d.samples.push(N),A--);A--;)N={},g&&(N.duration=f.getUint32(P),P+=4),T&&(N.size=f.getUint32(P),P+=4),S&&(N.flags=Nc(l.subarray(P,P+4)),P+=4),x&&(d.version===1?N.compositionTimeOffset=f.getInt32(P):N.compositionTimeOffset=f.getUint32(P),P+=4),d.samples.push(N);return d},Mc=Jb,Zb=function(l){var d=new DataView(l.buffer,l.byteOffset,l.byteLength),f={version:l[0],flags:new Uint8Array(l.subarray(1,4)),trackId:d.getUint32(4)},h=f.flags[2]&1,m=f.flags[2]&2,g=f.flags[2]&8,T=f.flags[2]&16,S=f.flags[2]&32,x=f.flags[0]&65536,A=f.flags[0]&131072,P;return P=8,h&&(P+=4,f.baseDataOffset=d.getUint32(12),P+=4),m&&(f.sampleDescriptionIndex=d.getUint32(P),P+=4),g&&(f.defaultSampleDuration=d.getUint32(P),P+=4),T&&(f.defaultSampleSize=d.getUint32(P),P+=4),S&&(f.defaultSampleFlags=d.getUint32(P)),x&&(f.durationIsEmpty=!0),!h&&A&&(f.baseDataOffsetIsMoof=!0),f},Bc=Zb,cr;typeof window<"u"?cr=window:typeof s<"u"?cr=s:typeof self<"u"?cr=self:cr={};var Fc=cr,e2=fc.discardEmulationPreventionBytes,t2=pc.CaptionStream,dr=Oc,i2=Rc,s2=Mc,r2=Bc,Uc=Fc,n2=function(l,d){for(var f=l,h=0;h0?i2(j[0]).baseMediaDecodeTime:0,W=dr(x,["trun"]),Y,Re;d===N&&W.length>0&&(Y=o2(W,F,P),Re=a2(S,Y,N),m[N]||(m[N]={seiNals:[],logs:[]}),m[N].seiNals=m[N].seiNals.concat(Re.seiNals),m[N].logs=m[N].logs.concat(Re.logs))}),m},u2=function(l,d,f){var h;if(d===null)return null;h=l2(l,d);var m=h[d]||{};return{seiNals:m.seiNals,logs:m.logs,timescale:f}},c2=function(){var l=!1,d,f,h,m,g,T;this.isInitialized=function(){return l},this.init=function(S){d=new t2,l=!0,T=S?S.isPartial:!1,d.on("data",function(x){x.startTime=x.startPts/m,x.endTime=x.endPts/m,g.captions.push(x),g.captionStreams[x.stream]=!0}),d.on("log",function(x){g.logs.push(x)})},this.isNewInit=function(S,x){return S&&S.length===0||x&&typeof x=="object"&&Object.keys(x).length===0?!1:h!==S[0]||m!==x[h]},this.parse=function(S,x,A){var P;if(this.isInitialized()){if(!x||!A)return null;if(this.isNewInit(x,A))h=x[0],m=A[h];else if(h===null||!m)return f.push(S),null}else return null;for(;f.length>0;){var N=f.shift();this.parse(N,x,A)}return P=u2(S,h,m),P&&P.logs&&(g.logs=g.logs.concat(P.logs)),P===null||!P.seiNals?g.logs.length?{logs:g.logs,captions:[],captionStreams:[]}:null:(this.pushNals(P.seiNals),this.flushStream(),g)},this.pushNals=function(S){if(!this.isInitialized()||!S||S.length===0)return null;S.forEach(function(x){d.push(x)})},this.flushStream=function(){if(!this.isInitialized())return null;T?d.partialFlush():d.flush()},this.clearParsedCaptions=function(){g.captions=[],g.captionStreams={},g.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;d.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){f=[],h=null,m=null,g?this.clearParsedCaptions():g={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},d2=c2,h2=function(l){for(var d=0,f=String.fromCharCode(l[d]),h="";f!=="\0";)h+=f,d++,f=String.fromCharCode(l[d]);return h+=f,h},f2={uint8ToCString:h2},Fn=f2.uint8ToCString,p2=n.getUint64,m2=function(l){var d=4,f=l[0],h,m,g,T,S,x,A,P;if(f===0){h=Fn(l.subarray(d)),d+=h.length,m=Fn(l.subarray(d)),d+=m.length;var N=new DataView(l.buffer);g=N.getUint32(d),d+=4,S=N.getUint32(d),d+=4,x=N.getUint32(d),d+=4,A=N.getUint32(d),d+=4}else if(f===1){var N=new DataView(l.buffer);g=N.getUint32(d),d+=4,T=p2(l.subarray(d)),d+=8,x=N.getUint32(d),d+=4,A=N.getUint32(d),d+=4,h=Fn(l.subarray(d)),d+=h.length,m=Fn(l.subarray(d)),d+=m.length}P=new Uint8Array(l.subarray(d,l.byteLength));var j={scheme_id_uri:h,value:m,timescale:g||1,presentation_time:T,presentation_time_delta:S,event_duration:x,id:A,message_data:P};return y2(f,j)?j:void 0},g2=function(l,d,f,h){return l||l===0?l/d:h+f/d},y2=function(l,d){var f=d.scheme_id_uri!=="\0",h=l===0&&$c(d.presentation_time_delta)&&f,m=l===1&&$c(d.presentation_time)&&f;return!(l>1)&&h||m},$c=function(l){return l!==void 0||l!==null},_2={parseEmsgBox:m2,scaleTime:g2},Un=Bn.toUnsigned,hr=Bn.toHexString,Ce=Oc,rs=Pc,Io=_2,v2=Bc,T2=Mc,b2=Rc,S2=n.getUint64,jc,qc,Hc,Vc,zc,Po,Gc,Lo=Fc,x2=_c.parseId3Frames;jc=function(l){var d={},f=Ce(l,["moov","trak"]);return f.reduce(function(h,m){var g,T,S,x,A;return g=Ce(m,["tkhd"])[0],!g||(T=g[0],S=T===0?12:20,x=Un(g[S]<<24|g[S+1]<<16|g[S+2]<<8|g[S+3]),A=Ce(m,["mdia","mdhd"])[0],!A)?null:(T=A[0],S=T===0?12:20,h[x]=Un(A[S]<<24|A[S+1]<<16|A[S+2]<<8|A[S+3]),h)},d)},qc=function(l,d){var f;f=Ce(d,["moof","traf"]);var h=f.reduce(function(m,g){var T=Ce(g,["tfhd"])[0],S=Un(T[4]<<24|T[5]<<16|T[6]<<8|T[7]),x=l[S]||9e4,A=Ce(g,["tfdt"])[0],P=new DataView(A.buffer,A.byteOffset,A.byteLength),N;A[0]===1?N=S2(A.subarray(4,12)):N=P.getUint32(4);let j;return typeof N=="bigint"?j=N/Lo.BigInt(x):typeof N=="number"&&!isNaN(N)&&(j=N/x),j11?(m.codec+=".",m.codec+=hr(F[9]),m.codec+=hr(F[10]),m.codec+=hr(F[11])):m.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(m.codec)?(F=j.subarray(28),W=rs(F.subarray(4,8)),W==="esds"&&F.length>20&&F[19]!==0?(m.codec+="."+hr(F[19]),m.codec+="."+hr(F[20]>>>2&63).replace(/^0/,"")):m.codec="mp4a.40.2"):m.codec=m.codec.toLowerCase())}var Y=Ce(h,["mdia","mdhd"])[0];Y&&(m.timescale=Po(Y)),f.push(m)}),f},Gc=function(l,d=0){var f=Ce(l,["emsg"]);return f.map(h=>{var m=Io.parseEmsgBox(new Uint8Array(h)),g=x2(m.message_data);return{cueTime:Io.scaleTime(m.presentation_time,m.timescale,m.presentation_time_delta,d),duration:Io.scaleTime(m.event_duration,m.timescale),frames:g}})};var Oo={findBox:Ce,parseType:rs,timescale:jc,startTime:qc,compositionStartTime:Hc,videoTrackIds:Vc,tracks:zc,getTimescaleFromMediaHeader:Po,getEmsgID3:Gc},Ro=En,Wc=function(l){var d=l[1]&31;return d<<=8,d|=l[2],d},$n=function(l){return!!(l[1]&64)},jn=function(l){var d=0;return(l[3]&48)>>>4>1&&(d+=l[4]+1),d},E2=function(l,d){var f=Wc(l);return f===0?"pat":f===d?"pmt":d?"pes":null},C2=function(l){var d=$n(l),f=4+jn(l);return d&&(f+=l[f]+1),(l[f+10]&31)<<8|l[f+11]},A2=function(l){var d={},f=$n(l),h=4+jn(l);if(f&&(h+=l[h]+1),!!(l[h+5]&1)){var m,g,T;m=(l[h+1]&15)<<8|l[h+2],g=3+m-4,T=(l[h+10]&15)<<8|l[h+11];for(var S=12+T;S=l.byteLength)return null;var h=null,m;return m=l[f+7],m&192&&(h={},h.pts=(l[f+9]&14)<<27|(l[f+10]&255)<<20|(l[f+11]&254)<<12|(l[f+12]&255)<<5|(l[f+13]&254)>>>3,h.pts*=4,h.pts+=(l[f+13]&6)>>>1,h.dts=h.pts,m&64&&(h.dts=(l[f+14]&14)<<27|(l[f+15]&255)<<20|(l[f+16]&254)<<12|(l[f+17]&255)<<5|(l[f+18]&254)>>>3,h.dts*=4,h.dts+=(l[f+18]&6)>>>1)),h},No=function(l){switch(l){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}},k2=function(l){for(var d=4+jn(l),f=l.subarray(d),h=0,m=0,g=!1,T;m3&&(T=No(f[m+3]&31),T==="slice_layer_without_partitioning_rbsp_idr"&&(g=!0)),g},I2={parseType:E2,parsePat:C2,parsePmt:A2,parsePayloadUnitStartIndicator:$n,parsePesType:w2,parsePesTime:D2,videoPacketContainsKeyFrame:k2},Kc=En,ns=gc.handleRollover,ne={};ne.ts=I2,ne.aac=Ao;var Pi=fe.ONE_SECOND_IN_TS,Xe=188,Pt=71,P2=function(l,d){for(var f=0,h=Xe,m,g;h=0;){if(l[h]===Pt&&(l[m]===Pt||m===l.byteLength)){switch(g=l.subarray(h,m),T=ne.ts.parseType(g,d.pid),T){case"pes":S=ne.ts.parsePesType(g,d.table),x=ne.ts.parsePayloadUnitStartIndicator(g),S==="audio"&&x&&(A=ne.ts.parsePesTime(g),A&&(A.type="audio",f.audio.push(A),P=!0));break}if(P)break;h-=Xe,m-=Xe;continue}h--,m--}},L2=function(l,d,f){for(var h=0,m=Xe,g,T,S,x,A,P,N,j,F=!1,W={data:[],size:0};m=0;){if(l[h]===Pt&&l[m]===Pt){switch(g=l.subarray(h,m),T=ne.ts.parseType(g,d.pid),T){case"pes":S=ne.ts.parsePesType(g,d.table),x=ne.ts.parsePayloadUnitStartIndicator(g),S==="video"&&x&&(A=ne.ts.parsePesTime(g),A&&(A.type="video",f.video.push(A),F=!0));break}if(F)break;h-=Xe,m-=Xe;continue}h--,m--}},O2=function(l,d){if(l.audio&&l.audio.length){var f=d;(typeof f>"u"||isNaN(f))&&(f=l.audio[0].dts),l.audio.forEach(function(g){g.dts=ns(g.dts,f),g.pts=ns(g.pts,f),g.dtsTime=g.dts/Pi,g.ptsTime=g.pts/Pi})}if(l.video&&l.video.length){var h=d;if((typeof h>"u"||isNaN(h))&&(h=l.video[0].dts),l.video.forEach(function(g){g.dts=ns(g.dts,h),g.pts=ns(g.pts,h),g.dtsTime=g.dts/Pi,g.ptsTime=g.pts/Pi}),l.firstKeyFrame){var m=l.firstKeyFrame;m.dts=ns(m.dts,h),m.pts=ns(m.pts,h),m.dtsTime=m.dts/Pi,m.ptsTime=m.pts/Pi}}},R2=function(l){for(var d=!1,f=0,h=null,m=null,g=0,T=0,S;l.length-T>=3;){var x=ne.aac.parseType(l,T);switch(x){case"timed-metadata":if(l.length-T<10){d=!0;break}if(g=ne.aac.parseId3TagSize(l,T),g>l.length){d=!0;break}m===null&&(S=l.subarray(T,T+g),m=ne.aac.parseAacTimestamp(S)),T+=g;break;case"audio":if(l.length-T<7){d=!0;break}if(g=ne.aac.parseAdtsSize(l,T),g>l.length){d=!0;break}h===null&&(S=l.subarray(T,T+g),h=ne.aac.parseSampleRate(S)),f++,T+=g;break;default:T++;break}if(d)return null}if(h===null||m===null)return null;var A=Pi/h,P={audio:[{type:"audio",dts:m,pts:m},{type:"audio",dts:m+f*1024*A,pts:m+f*1024*A}]};return P},N2=function(l){var d={pid:null,table:null},f={};P2(l,d);for(var h in d.table)if(d.table.hasOwnProperty(h)){var m=d.table[h];switch(m){case Kc.H264_STREAM_TYPE:f.video=[],L2(l,d,f),f.video.length===0&&delete f.video;break;case Kc.ADTS_STREAM_TYPE:f.audio=[],Xc(l,d,f),f.audio.length===0&&delete f.audio;break}}return f},M2=function(l,d){var f=ne.aac.isLikelyAacData(l),h;return f?h=R2(l):h=N2(l),!h||!h.audio&&!h.video?null:(O2(h,d),h)},B2={inspect:M2,parseAudioPes_:Xc};const F2=function(l,d){d.on("data",function(f){const h=f.initSegment;f.initSegment={data:h.buffer,byteOffset:h.byteOffset,byteLength:h.byteLength};const m=f.data;f.data=m.buffer,l.postMessage({action:"data",segment:f,byteOffset:m.byteOffset,byteLength:m.byteLength},[f.data])}),d.on("done",function(f){l.postMessage({action:"done"})}),d.on("gopInfo",function(f){l.postMessage({action:"gopInfo",gopInfo:f})}),d.on("videoSegmentTimingInfo",function(f){const h={start:{decode:fe.videoTsToSeconds(f.start.dts),presentation:fe.videoTsToSeconds(f.start.pts)},end:{decode:fe.videoTsToSeconds(f.end.dts),presentation:fe.videoTsToSeconds(f.end.pts)},baseMediaDecodeTime:fe.videoTsToSeconds(f.baseMediaDecodeTime)};f.prependedContentDuration&&(h.prependedContentDuration=fe.videoTsToSeconds(f.prependedContentDuration)),l.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:h})}),d.on("audioSegmentTimingInfo",function(f){const h={start:{decode:fe.videoTsToSeconds(f.start.dts),presentation:fe.videoTsToSeconds(f.start.pts)},end:{decode:fe.videoTsToSeconds(f.end.dts),presentation:fe.videoTsToSeconds(f.end.pts)},baseMediaDecodeTime:fe.videoTsToSeconds(f.baseMediaDecodeTime)};f.prependedContentDuration&&(h.prependedContentDuration=fe.videoTsToSeconds(f.prependedContentDuration)),l.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:h})}),d.on("id3Frame",function(f){l.postMessage({action:"id3Frame",id3Frame:f})}),d.on("caption",function(f){l.postMessage({action:"caption",caption:f})}),d.on("trackinfo",function(f){l.postMessage({action:"trackinfo",trackInfo:f})}),d.on("audioTimingInfo",function(f){l.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:fe.videoTsToSeconds(f.start),end:fe.videoTsToSeconds(f.end)}})}),d.on("videoTimingInfo",function(f){l.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:fe.videoTsToSeconds(f.start),end:fe.videoTsToSeconds(f.end)}})}),d.on("log",function(f){l.postMessage({action:"log",log:f})})};class Yc{constructor(d,f){this.options=f||{},this.self=d,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new jb.Transmuxer(this.options),F2(this.self,this.transmuxer)}pushMp4Captions(d){this.captionParser||(this.captionParser=new d2,this.captionParser.init());const f=new Uint8Array(d.data,d.byteOffset,d.byteLength),h=this.captionParser.parse(f,d.trackIds,d.timescales);this.self.postMessage({action:"mp4Captions",captions:h&&h.captions||[],logs:h&&h.logs||[],data:f.buffer},[f.buffer])}probeMp4StartTime({timescales:d,data:f}){const h=Oo.startTime(d,f);this.self.postMessage({action:"probeMp4StartTime",startTime:h,data:f},[f.buffer])}probeMp4Tracks({data:d}){const f=Oo.tracks(d);this.self.postMessage({action:"probeMp4Tracks",tracks:f,data:d},[d.buffer])}probeEmsgID3({data:d,offset:f}){const h=Oo.getEmsgID3(d,f);this.self.postMessage({action:"probeEmsgID3",id3Frames:h,emsgData:d},[d.buffer])}probeTs({data:d,baseStartTime:f}){const h=typeof f=="number"&&!isNaN(f)?f*fe.ONE_SECOND_IN_TS:void 0,m=B2.inspect(d,h);let g=null;m&&(g={hasVideo:m.video&&m.video.length===2||!1,hasAudio:m.audio&&m.audio.length===2||!1},g.hasVideo&&(g.videoStart=m.video[0].ptsTime),g.hasAudio&&(g.audioStart=m.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:g,data:d},[d.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(d){const f=new Uint8Array(d.data,d.byteOffset,d.byteLength);this.transmuxer.push(f)}reset(){this.transmuxer.reset()}setTimestampOffset(d){const f=d.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(fe.secondsToVideoTs(f)))}setAudioAppendStart(d){this.transmuxer.setAudioAppendStart(Math.ceil(fe.secondsToVideoTs(d.appendStart)))}setRemux(d){this.transmuxer.setRemux(d.remux)}flush(d){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(d){this.transmuxer.alignGopsWith(d.gopsToAlignWith.slice())}}self.onmessage=function(l){if(l.data.action==="init"&&l.data.options){this.messageHandlers=new Yc(self,l.data.options);return}this.messageHandlers||(this.messageHandlers=new Yc(self)),l.data&&l.data.action&&l.data.action!=="init"&&this.messageHandlers[l.data.action]&&this.messageHandlers[l.data.action](l.data)}}));var kw=Ig(Dw);const Iw=(s,e,t)=>{const{type:i,initSegment:r,captions:n,captionStreams:a,metadata:o,videoFrameDtsTime:u,videoFramePtsTime:c}=s.data.segment;e.buffer.push({captions:n,captionStreams:a,metadata:o});const p=s.data.segment.boxes||{data:s.data.segment.data},y={type:i,data:new Uint8Array(p.data,p.data.byteOffset,p.data.byteLength),initSegment:new Uint8Array(r.data,r.byteOffset,r.byteLength)};typeof u<"u"&&(y.videoFrameDtsTime=u),typeof c<"u"&&(y.videoFramePtsTime=c),t(y)},Pw=({transmuxedData:s,callback:e})=>{s.buffer=[],e(s)},Lw=(s,e)=>{e.gopInfo=s.data.gopInfo},Og=s=>{const{transmuxer:e,bytes:t,audioAppendStart:i,gopsToAlignWith:r,remux:n,onData:a,onTrackInfo:o,onAudioTimingInfo:u,onVideoTimingInfo:c,onVideoSegmentTimingInfo:p,onAudioSegmentTimingInfo:y,onId3:v,onCaptions:b,onDone:C,onEndedTimeline:_,onTransmuxerLog:D,isEndOfTimeline:w,segment:L,triggerSegmentEventFn:I}=s,R={buffer:[]};let k=w;const M=q=>{e.currentTransmux===s&&(q.data.action==="data"&&Iw(q,R,a),q.data.action==="trackinfo"&&o(q.data.trackInfo),q.data.action==="gopInfo"&&Lw(q,R),q.data.action==="audioTimingInfo"&&u(q.data.audioTimingInfo),q.data.action==="videoTimingInfo"&&c(q.data.videoTimingInfo),q.data.action==="videoSegmentTimingInfo"&&p(q.data.videoSegmentTimingInfo),q.data.action==="audioSegmentTimingInfo"&&y(q.data.audioSegmentTimingInfo),q.data.action==="id3Frame"&&v([q.data.id3Frame],q.data.id3Frame.dispatchType),q.data.action==="caption"&&b(q.data.caption),q.data.action==="endedtimeline"&&(k=!1,_()),q.data.action==="log"&&D(q.data.log),q.data.type==="transmuxed"&&(k||(e.onmessage=null,Pw({transmuxedData:R,callback:C}),Rg(e))))},V=()=>{const q={message:"Received an error message from the transmuxer worker",metadata:{errorType:O.Error.StreamingFailedToTransmuxSegment,segmentInfo:Bi({segment:L})}};C(null,q)};if(e.onmessage=M,e.onerror=V,i&&e.postMessage({action:"setAudioAppendStart",appendStart:i}),Array.isArray(r)&&e.postMessage({action:"alignGopsWith",gopsToAlignWith:r}),typeof n<"u"&&e.postMessage({action:"setRemux",remux:n}),t.byteLength){const q=t instanceof ArrayBuffer?t:t.buffer,K=t instanceof ArrayBuffer?0:t.byteOffset;I({type:"segmenttransmuxingstart",segment:L}),e.postMessage({action:"push",data:q,byteOffset:K,byteLength:t.byteLength},[q])}w&&e.postMessage({action:"endTimeline"}),e.postMessage({action:"flush"})},Rg=s=>{s.currentTransmux=null,s.transmuxQueue.length&&(s.currentTransmux=s.transmuxQueue.shift(),typeof s.currentTransmux=="function"?s.currentTransmux():Og(s.currentTransmux))},Rh=(s,e)=>{s.postMessage({action:e}),Rg(s)},Ng=(s,e)=>{if(!e.currentTransmux){e.currentTransmux=s,Rh(e,s);return}e.transmuxQueue.push(Rh.bind(null,e,s))},Ow=s=>{Ng("reset",s)},Rw=s=>{Ng("endTimeline",s)},Mg=s=>{if(!s.transmuxer.currentTransmux){s.transmuxer.currentTransmux=s,Og(s);return}s.transmuxer.transmuxQueue.push(s)},Nw=s=>{const e=new kw;e.currentTransmux=null,e.transmuxQueue=[];const t=e.terminate;return e.terminate=()=>(e.currentTransmux=null,e.transmuxQueue.length=0,t.call(e)),e.postMessage({action:"init",options:s}),e};var dl={reset:Ow,endTimeline:Rw,transmux:Mg,createTransmuxer:Nw};const $r=function(s){const e=s.transmuxer,t=s.endAction||s.action,i=s.callback,r=xe({},s,{endAction:null,transmuxer:null,callback:null}),n=a=>{a.data.action===t&&(e.removeEventListener("message",n),a.data.data&&(a.data.data=new Uint8Array(a.data.data,s.byteOffset||0,s.byteLength||a.data.data.byteLength),s.data&&(s.data=a.data.data)),i(a.data))};if(e.addEventListener("message",n),s.data){const a=s.data instanceof ArrayBuffer;r.byteOffset=a?0:s.data.byteOffset,r.byteLength=s.data.byteLength;const o=[a?s.data:s.data.buffer];e.postMessage(r,o)}else e.postMessage(r)},Ut={FAILURE:2,TIMEOUT:-101,ABORTED:-102},ql=s=>{s.forEach(e=>{e.abort()})},Mw=s=>({bandwidth:s.bandwidth,bytesReceived:s.bytesReceived||0,roundTripTime:s.roundTripTime||0}),Bw=s=>{const e=s.target,i={bandwidth:1/0,bytesReceived:0,roundTripTime:Date.now()-e.requestTime||0};return i.bytesReceived=s.loaded,i.bandwidth=Math.floor(i.bytesReceived/i.roundTripTime*8*1e3),i},tc=(s,e)=>{const{requestType:t}=e,i=Ki({requestType:t,request:e,error:s});return e.timedout?{status:e.status,message:"HLS request timed-out at URL: "+e.uri,code:Ut.TIMEOUT,xhr:e,metadata:i}:e.aborted?{status:e.status,message:"HLS request aborted at URL: "+e.uri,code:Ut.ABORTED,xhr:e,metadata:i}:s?{status:e.status,message:"HLS request errored at URL: "+e.uri,code:Ut.FAILURE,xhr:e,metadata:i}:e.responseType==="arraybuffer"&&e.response.byteLength===0?{status:e.status,message:"Empty HLS response at URL: "+e.uri,code:Ut.FAILURE,xhr:e,metadata:i}:null},Nh=(s,e,t,i)=>(r,n)=>{const a=n.response,o=tc(r,n);if(o)return t(o,s);if(a.byteLength!==16)return t({status:n.status,message:"Invalid HLS key at URL: "+n.uri,code:Ut.FAILURE,xhr:n},s);const u=new DataView(a),c=new Uint32Array([u.getUint32(0),u.getUint32(4),u.getUint32(8),u.getUint32(12)]);for(let y=0;y{const t=Tu(s.map.bytes);if(t!=="mp4"){const i=s.map.resolvedUri||s.map.uri,r=t||"unknown";return e({internal:!0,message:`Found unsupported ${r} container for initialization segment at URL: ${i}`,code:Ut.FAILURE,metadata:{mediaType:r}})}$r({action:"probeMp4Tracks",data:s.map.bytes,transmuxer:s.transmuxer,callback:({tracks:i,data:r})=>(s.map.bytes=r,i.forEach(function(n){s.map.tracks=s.map.tracks||{},!s.map.tracks[n.type]&&(s.map.tracks[n.type]=n,typeof n.id=="number"&&n.timescale&&(s.map.timescales=s.map.timescales||{},s.map.timescales[n.id]=n.timescale))}),e(null))})},Fw=({segment:s,finishProcessingFn:e,triggerSegmentEventFn:t})=>(i,r)=>{const n=tc(i,r);if(n)return e(n,s);const a=new Uint8Array(r.response);if(t({type:"segmentloaded",segment:s}),s.map.key)return s.map.encryptedBytes=a,e(null,s);s.map.bytes=a,Bg(s,function(o){if(o)return o.xhr=r,o.status=r.status,e(o,s);e(null,s)})},Uw=({segment:s,finishProcessingFn:e,responseType:t,triggerSegmentEventFn:i})=>(r,n)=>{const a=tc(r,n);if(a)return e(a,s);i({type:"segmentloaded",segment:s});const o=t==="arraybuffer"||!n.responseText?n.response:Aw(n.responseText.substring(s.lastReachedChar||0));return s.stats=Mw(n),s.key?s.encryptedBytes=new Uint8Array(o):s.bytes=new Uint8Array(o),e(null,s)},$w=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:u,endedTimelineFn:c,dataFn:p,doneFn:y,onTransmuxerLog:v,triggerSegmentEventFn:b})=>{const C=s.map&&s.map.tracks||{},_=!!(C.audio&&C.video);let D=i.bind(null,s,"audio","start");const w=i.bind(null,s,"audio","end");let L=i.bind(null,s,"video","start");const I=i.bind(null,s,"video","end"),R=()=>Mg({bytes:e,transmuxer:s.transmuxer,audioAppendStart:s.audioAppendStart,gopsToAlignWith:s.gopsToAlignWith,remux:_,onData:k=>{k.type=k.type==="combined"?"video":k.type,p(s,k)},onTrackInfo:k=>{t&&(_&&(k.isMuxed=!0),t(s,k))},onAudioTimingInfo:k=>{D&&typeof k.start<"u"&&(D(k.start),D=null),w&&typeof k.end<"u"&&w(k.end)},onVideoTimingInfo:k=>{L&&typeof k.start<"u"&&(L(k.start),L=null),I&&typeof k.end<"u"&&I(k.end)},onVideoSegmentTimingInfo:k=>{const M={pts:{start:k.start.presentation,end:k.end.presentation},dts:{start:k.start.decode,end:k.end.decode}};b({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:M}),r(k)},onAudioSegmentTimingInfo:k=>{const M={pts:{start:k.start.pts,end:k.end.pts},dts:{start:k.start.dts,end:k.end.dts}};b({type:"segmenttransmuxingtiminginfoavailable",segment:s,timingInfo:M}),n(k)},onId3:(k,M)=>{a(s,k,M)},onCaptions:k=>{o(s,[k])},isEndOfTimeline:u,onEndedTimeline:()=>{c()},onTransmuxerLog:v,onDone:(k,M)=>{y&&(k.type=k.type==="combined"?"video":k.type,b({type:"segmenttransmuxingcomplete",segment:s}),y(M,s,k))},segment:s,triggerSegmentEventFn:b});$r({action:"probeTs",transmuxer:s.transmuxer,data:e,baseStartTime:s.baseStartTime,callback:k=>{s.bytes=e=k.data;const M=k.result;M&&(t(s,{hasAudio:M.hasAudio,hasVideo:M.hasVideo,isMuxed:_}),t=null),R()}})},Fg=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:u,endedTimelineFn:c,dataFn:p,doneFn:y,onTransmuxerLog:v,triggerSegmentEventFn:b})=>{let C=new Uint8Array(e);if(cC(C)){s.isFmp4=!0;const{tracks:_}=s.map,D={isFmp4:!0,hasVideo:!!_.video,hasAudio:!!_.audio};_.audio&&_.audio.codec&&_.audio.codec!=="enca"&&(D.audioCodec=_.audio.codec),_.video&&_.video.codec&&_.video.codec!=="encv"&&(D.videoCodec=_.video.codec),_.video&&_.audio&&(D.isMuxed=!0),t(s,D);const w=(L,I)=>{p(s,{data:C,type:D.hasAudio&&!D.isMuxed?"audio":"video"}),I&&I.length&&a(s,I),L&&L.length&&o(s,L),y(null,s,{})};$r({action:"probeMp4StartTime",timescales:s.map.timescales,data:C,transmuxer:s.transmuxer,callback:({data:L,startTime:I})=>{e=L.buffer,s.bytes=C=L,D.hasAudio&&!D.isMuxed&&i(s,"audio","start",I),D.hasVideo&&i(s,"video","start",I),$r({action:"probeEmsgID3",data:C,transmuxer:s.transmuxer,offset:I,callback:({emsgData:R,id3Frames:k})=>{if(e=R.buffer,s.bytes=C=R,!_.video||!R.byteLength||!s.transmuxer){w(void 0,k);return}$r({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:s.transmuxer,data:C,timescales:s.map.timescales,trackIds:[_.video.id],callback:M=>{e=M.data.buffer,s.bytes=C=M.data,M.logs.forEach(function(V){v(se(V,{stream:"mp4CaptionParser"}))}),w(M.captions,k)}})}})}});return}if(!s.transmuxer){y(null,s,{});return}if(typeof s.container>"u"&&(s.container=Tu(C)),s.container!=="ts"&&s.container!=="aac"){t(s,{hasAudio:!1,hasVideo:!1}),y(null,s,{});return}$w({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:u,endedTimelineFn:c,dataFn:p,doneFn:y,onTransmuxerLog:v,triggerSegmentEventFn:b})},Ug=function({id:s,key:e,encryptedBytes:t,decryptionWorker:i,segment:r,doneFn:n},a){const o=c=>{if(c.data.source===s){i.removeEventListener("message",o);const p=c.data.decrypted;a(new Uint8Array(p.bytes,p.byteOffset,p.byteLength))}};i.onerror=()=>{const c="An error occurred in the decryption worker",p=Bi({segment:r}),y={message:c,metadata:{error:new Error(c),errorType:O.Error.StreamingFailedToDecryptSegment,segmentInfo:p,keyInfo:{uri:r.key.resolvedUri||r.map.key.resolvedUri}}};n(y,r)},i.addEventListener("message",o);let u;e.bytes.slice?u=e.bytes.slice():u=new Uint32Array(Array.prototype.slice.call(e.bytes)),i.postMessage(Eg({source:s,encrypted:t,key:u,iv:e.iv}),[t.buffer,u.buffer])},jw=({decryptionWorker:s,segment:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:u,endedTimelineFn:c,dataFn:p,doneFn:y,onTransmuxerLog:v,triggerSegmentEventFn:b})=>{b({type:"segmentdecryptionstart"}),Ug({id:e.requestId,key:e.key,encryptedBytes:e.encryptedBytes,decryptionWorker:s,segment:e,doneFn:y},C=>{e.bytes=C,b({type:"segmentdecryptioncomplete",segment:e}),Fg({segment:e,bytes:e.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:u,endedTimelineFn:c,dataFn:p,doneFn:y,onTransmuxerLog:v,triggerSegmentEventFn:b})})},qw=({activeXhrs:s,decryptionWorker:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:u,endedTimelineFn:c,dataFn:p,doneFn:y,onTransmuxerLog:v,triggerSegmentEventFn:b})=>{let C=0,_=!1;return(D,w)=>{if(!_){if(D)return _=!0,ql(s),y(D,w);if(C+=1,C===s.length){const L=function(){if(w.encryptedBytes)return jw({decryptionWorker:e,segment:w,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:u,endedTimelineFn:c,dataFn:p,doneFn:y,onTransmuxerLog:v,triggerSegmentEventFn:b});Fg({segment:w,bytes:w.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:u,endedTimelineFn:c,dataFn:p,doneFn:y,onTransmuxerLog:v,triggerSegmentEventFn:b})};if(w.endOfAllRequests=Date.now(),w.map&&w.map.encryptedBytes&&!w.map.bytes)return b({type:"segmentdecryptionstart",segment:w}),Ug({decryptionWorker:e,id:w.requestId+"-init",encryptedBytes:w.map.encryptedBytes,key:w.map.key,segment:w,doneFn:y},I=>{w.map.bytes=I,b({type:"segmentdecryptioncomplete",segment:w}),Bg(w,R=>{if(R)return ql(s),y(R,w);L()})});L()}}}},Hw=({loadendState:s,abortFn:e})=>t=>{t.target.aborted&&e&&!s.calledAbortFn&&(e(),s.calledAbortFn=!0)},Vw=({segment:s,progressFn:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:u,endedTimelineFn:c,dataFn:p})=>y=>{if(!y.target.aborted)return s.stats=se(s.stats,Bw(y)),!s.stats.firstBytesReceivedAt&&s.stats.bytesReceived&&(s.stats.firstBytesReceivedAt=Date.now()),e(y,s)},zw=({xhr:s,xhrOptions:e,decryptionWorker:t,segment:i,abortFn:r,progressFn:n,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:u,audioSegmentTimingInfoFn:c,id3Fn:p,captionsFn:y,isEndOfTimeline:v,endedTimelineFn:b,dataFn:C,doneFn:_,onTransmuxerLog:D,triggerSegmentEventFn:w})=>{const L=[],I=qw({activeXhrs:L,decryptionWorker:t,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:u,audioSegmentTimingInfoFn:c,id3Fn:p,captionsFn:y,isEndOfTimeline:v,endedTimelineFn:b,dataFn:C,doneFn:_,onTransmuxerLog:D,triggerSegmentEventFn:w});if(i.key&&!i.key.bytes){const q=[i.key];i.map&&!i.map.bytes&&i.map.key&&i.map.key.resolvedUri===i.key.resolvedUri&&q.push(i.map.key);const K=se(e,{uri:i.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),oe=Nh(i,q,I,w),ee={uri:i.key.resolvedUri};w({type:"segmentkeyloadstart",segment:i,keyInfo:ee});const le=s(K,oe);L.push(le)}if(i.map&&!i.map.bytes){if(i.map.key&&(!i.key||i.key.resolvedUri!==i.map.key.resolvedUri)){const le=se(e,{uri:i.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),z=Nh(i,[i.map.key],I,w),te={uri:i.map.key.resolvedUri};w({type:"segmentkeyloadstart",segment:i,keyInfo:te});const Ke=s(le,z);L.push(Ke)}const K=se(e,{uri:i.map.resolvedUri,responseType:"arraybuffer",headers:$l(i.map),requestType:"segment-media-initialization"}),oe=Fw({segment:i,finishProcessingFn:I,triggerSegmentEventFn:w});w({type:"segmentloadstart",segment:i});const ee=s(K,oe);L.push(ee)}const R=se(e,{uri:i.part&&i.part.resolvedUri||i.resolvedUri,responseType:"arraybuffer",headers:$l(i),requestType:"segment"}),k=Uw({segment:i,finishProcessingFn:I,responseType:R.responseType,triggerSegmentEventFn:w});w({type:"segmentloadstart",segment:i});const M=s(R,k);M.addEventListener("progress",Vw({segment:i,progressFn:n,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:u,audioSegmentTimingInfoFn:c,id3Fn:p,captionsFn:y,isEndOfTimeline:v,endedTimelineFn:b,dataFn:C})),L.push(M);const V={};return L.forEach(q=>{q.addEventListener("loadend",Hw({loadendState:V,abortFn:r}))}),()=>ql(L)},Gw=Ct("CodecUtils"),Ww=function(s){const e=s.attributes||{};if(e.CODECS)return Ot(e.CODECS)},$g=(s,e)=>{const t=e.attributes||{};return s&&s.mediaGroups&&s.mediaGroups.AUDIO&&t.AUDIO&&s.mediaGroups.AUDIO[t.AUDIO]},Kw=(s,e)=>{if(!$g(s,e))return!0;const t=e.attributes||{},i=s.mediaGroups.AUDIO[t.AUDIO];for(const r in i)if(!i[r].uri&&!i[r].playlists)return!0;return!1},La=function(s){const e={};return s.forEach(({mediaType:t,type:i,details:r})=>{e[t]=e[t]||[],e[t].push(Kf(`${i}${r}`))}),Object.keys(e).forEach(function(t){if(e[t].length>1){Gw(`multiple ${t} codecs found as attributes: ${e[t].join(", ")}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`),e[t]=null;return}e[t]=e[t][0]}),e},Mh=function(s){let e=0;return s.audio&&e++,s.video&&e++,e},jr=function(s,e){const t=e.attributes||{},i=La(Ww(e)||[]);if($g(s,e)&&!i.audio&&!Kw(s,e)){const r=La(hx(s,t.AUDIO)||[]);r.audio&&(i.audio=r.audio)}return i},Xn=Ct("PlaylistSelector"),Bh=function(s){if(!s||!s.playlist)return;const e=s.playlist;return JSON.stringify({id:e.id,bandwidth:s.bandwidth,width:s.width,height:s.height,codecs:e.attributes&&e.attributes.CODECS||""})},Oa=function(s,e){if(!s)return"";const t=E.getComputedStyle(s);return t?t[e]:""},Ds=function(s,e){const t=s.slice();s.sort(function(i,r){const n=e(i,r);return n===0?t.indexOf(i)-t.indexOf(r):n})},ic=function(s,e){let t,i;return s.attributes.BANDWIDTH&&(t=s.attributes.BANDWIDTH),t=t||E.Number.MAX_VALUE,e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||E.Number.MAX_VALUE,t-i},Xw=function(s,e){let t,i;return s.attributes.RESOLUTION&&s.attributes.RESOLUTION.width&&(t=s.attributes.RESOLUTION.width),t=t||E.Number.MAX_VALUE,e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||E.Number.MAX_VALUE,t===i&&s.attributes.BANDWIDTH&&e.attributes.BANDWIDTH?s.attributes.BANDWIDTH-e.attributes.BANDWIDTH:t-i};let jg=function(s,e,t,i,r,n){if(!s)return;const a={bandwidth:e,width:t,height:i,limitRenditionByPlayerDimensions:r};let o=s.playlists;ut.isAudioOnly(s)&&(o=n.getAudioTrackPlaylists_(),a.audioOnly=!0);let u=o.map(k=>{let M;const V=k.attributes&&k.attributes.RESOLUTION&&k.attributes.RESOLUTION.width,q=k.attributes&&k.attributes.RESOLUTION&&k.attributes.RESOLUTION.height;return M=k.attributes&&k.attributes.BANDWIDTH,M=M||E.Number.MAX_VALUE,{bandwidth:M,width:V,height:q,playlist:k}});Ds(u,(k,M)=>k.bandwidth-M.bandwidth),u=u.filter(k=>!ut.isIncompatible(k.playlist));let c=u.filter(k=>ut.isEnabled(k.playlist));c.length||(c=u.filter(k=>!ut.isDisabled(k.playlist)));const p=c.filter(k=>k.bandwidth*$e.BANDWIDTH_VARIANCEk.bandwidth===y.bandwidth)[0];if(r===!1){const k=v||c[0]||u[0];if(k&&k.playlist){let M="sortedPlaylistReps";return v&&(M="bandwidthBestRep"),c[0]&&(M="enabledPlaylistReps"),Xn(`choosing ${Bh(k)} using ${M} with options`,a),k.playlist}return Xn("could not choose a playlist with options",a),null}const b=p.filter(k=>k.width&&k.height);Ds(b,(k,M)=>k.width-M.width);const C=b.filter(k=>k.width===t&&k.height===i);y=C[C.length-1];const _=C.filter(k=>k.bandwidth===y.bandwidth)[0];let D,w,L;_||(D=b.filter(k=>k.width>t||k.height>i),w=D.filter(k=>k.width===D[0].width&&k.height===D[0].height),y=w[w.length-1],L=w.filter(k=>k.bandwidth===y.bandwidth)[0]);let I;if(n.leastPixelDiffSelector){const k=b.map(M=>(M.pixelDiff=Math.abs(M.width-t)+Math.abs(M.height-i),M));Ds(k,(M,V)=>M.pixelDiff===V.pixelDiff?V.bandwidth-M.bandwidth:M.pixelDiff-V.pixelDiff),I=k[0]}const R=I||L||_||v||c[0]||u[0];if(R&&R.playlist){let k="sortedPlaylistReps";return I?k="leastPixelDiffRep":L?k="resolutionPlusOneRep":_?k="resolutionBestRep":v?k="bandwidthBestRep":c[0]&&(k="enabledPlaylistReps"),Xn(`choosing ${Bh(R)} using ${k} with options`,a),R.playlist}return Xn("could not choose a playlist with options",a),null};const Fh=function(){let s=this.useDevicePixelRatio&&E.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(s=this.customPixelRatio),jg(this.playlists.main,this.systemBandwidth,parseInt(Oa(this.tech_.el(),"width"),10)*s,parseInt(Oa(this.tech_.el(),"height"),10)*s,this.limitRenditionByPlayerDimensions,this.playlistController_)},Yw=function(s){let e=-1,t=-1;if(s<0||s>1)throw new Error("Moving average bandwidth decay must be between 0 and 1.");return function(){let i=this.useDevicePixelRatio&&E.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(i=this.customPixelRatio),e<0&&(e=this.systemBandwidth,t=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==t&&(e=s*this.systemBandwidth+(1-s)*e,t=this.systemBandwidth),jg(this.playlists.main,e,parseInt(Oa(this.tech_.el(),"width"),10)*i,parseInt(Oa(this.tech_.el(),"height"),10)*i,this.limitRenditionByPlayerDimensions,this.playlistController_)}},Qw=function(s){const{main:e,currentTime:t,bandwidth:i,duration:r,segmentDuration:n,timeUntilRebuffer:a,currentTimeline:o,syncController:u}=s,c=e.playlists.filter(C=>!ut.isIncompatible(C));let p=c.filter(ut.isEnabled);p.length||(p=c.filter(C=>!ut.isDisabled(C)));const v=p.filter(ut.hasAttribute.bind(null,"BANDWIDTH")).map(C=>{const D=u.getSyncPoint(C,r,o,t)?1:2,L=ut.estimateSegmentRequestTime(n,i,C)*D-a;return{playlist:C,rebufferingImpact:L}}),b=v.filter(C=>C.rebufferingImpact<=0);return Ds(b,(C,_)=>ic(_.playlist,C.playlist)),b.length?b[0]:(Ds(v,(C,_)=>C.rebufferingImpact-_.rebufferingImpact),v[0]||null)},Jw=function(){const s=this.playlists.main.playlists.filter(ut.isEnabled);return Ds(s,(t,i)=>ic(t,i)),s.filter(t=>!!jr(this.playlists.main,t).video)[0]||null},Zw=s=>{let e=0,t;return s.bytes&&(t=new Uint8Array(s.bytes),s.segments.forEach(i=>{t.set(i,e),e+=i.byteLength})),t};function qg(s){try{return new URL(s).pathname.split("/").slice(-2).join("/")}catch{return""}}const eD=function(s,e,t){if(!s[t]){e.trigger({type:"usage",name:"vhs-608"});let i=t;/^cc708_/.test(t)&&(i="SERVICE"+t.split("_")[1]);const r=e.textTracks().getTrackById(i);if(r)s[t]=r;else{const n=e.options_.vhs&&e.options_.vhs.captionServices||{};let a=t,o=t,u=!1;const c=n[i];c&&(a=c.label,o=c.language,u=c.default),s[t]=e.addRemoteTextTrack({kind:"captions",id:i,default:u,label:a,language:o},!1).track}}},tD=function({inbandTextTracks:s,captionArray:e,timestampOffset:t}){if(!e)return;const i=E.WebKitDataCue||E.VTTCue;e.forEach(r=>{const n=r.stream;r.content?r.content.forEach(a=>{const o=new i(r.startTime+t,r.endTime+t,a.text);o.line=a.line,o.align="left",o.position=a.position,o.positionAlign="line-left",s[n].addCue(o)}):s[n].addCue(new i(r.startTime+t,r.endTime+t,r.text))})},iD=function(s){Object.defineProperties(s.frame,{id:{get(){return O.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),s.value.key}},value:{get(){return O.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),s.value.data}},privateData:{get(){return O.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),s.value.data}}})},sD=({inbandTextTracks:s,metadataArray:e,timestampOffset:t,videoDuration:i})=>{if(!e)return;const r=E.WebKitDataCue||E.VTTCue,n=s.metadataTrack_;if(!n||(e.forEach(p=>{const y=p.cueTime+t;typeof y!="number"||E.isNaN(y)||y<0||!(y<1/0)||!p.frames||!p.frames.length||p.frames.forEach(v=>{const b=new r(y,y,v.value||v.url||v.data||"");b.frame=v,b.value=v,iD(b),n.addCue(b)})}),!n.cues||!n.cues.length))return;const a=n.cues,o=[];for(let p=0;p{const v=p[y.startTime]||[];return v.push(y),p[y.startTime]=v,p},{}),c=Object.keys(u).sort((p,y)=>Number(p)-Number(y));c.forEach((p,y)=>{const v=u[p],b=isFinite(i)?i:p,C=Number(c[y+1])||b;v.forEach(_=>{_.endTime=C})})},rD={id:"ID",class:"CLASS",startDate:"START-DATE",duration:"DURATION",endDate:"END-DATE",endOnNext:"END-ON-NEXT",plannedDuration:"PLANNED-DURATION",scte35Out:"SCTE35-OUT",scte35In:"SCTE35-IN"},nD=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),aD=({inbandTextTracks:s,dateRanges:e})=>{const t=s.metadataTrack_;if(!t)return;const i=E.WebKitDataCue||E.VTTCue;e.forEach(r=>{for(const n of Object.keys(r)){if(nD.has(n))continue;const a=new i(r.startTime,r.endTime,"");a.id=r.id,a.type="com.apple.quicktime.HLS",a.value={key:rD[n],data:r[n]},(n==="scte35Out"||n==="scte35In")&&(a.value.data=new Uint8Array(a.value.data.match(/[\da-f]{2}/gi)).buffer),t.addCue(a)}r.processDateRange()})},Uh=(s,e,t)=>{s.metadataTrack_||(s.metadataTrack_=t.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,O.browser.IS_ANY_SAFARI||(s.metadataTrack_.inBandMetadataTrackDispatchType=e))},Ir=function(s,e,t){let i,r;if(t&&t.cues)for(i=t.cues.length;i--;)r=t.cues[i],r.startTime>=s&&r.endTime<=e&&t.removeCue(r)},oD=function(s){const e=s.cues;if(!e)return;const t={};for(let i=e.length-1;i>=0;i--){const r=e[i],n=`${r.startTime}-${r.endTime}-${r.text}`;t[n]?s.removeCue(r):t[n]=r}},lD=(s,e,t)=>{if(typeof e>"u"||e===null||!s.length)return[];const i=Math.ceil((e-t+3)*$i.ONE_SECOND_IN_TS);let r;for(r=0;ri);r++);return s.slice(r)},uD=(s,e,t)=>{if(!e.length)return s;if(t)return e.slice();const i=e[0].pts;let r=0;for(r;r=i);r++);return s.slice(0,r).concat(e)},cD=(s,e,t,i)=>{const r=Math.ceil((e-i)*$i.ONE_SECOND_IN_TS),n=Math.ceil((t-i)*$i.ONE_SECOND_IN_TS),a=s.slice();let o=s.length;for(;o--&&!(s[o].pts<=n););if(o===-1)return a;let u=o+1;for(;u--&&!(s[u].pts<=r););return u=Math.max(u,0),a.splice(u,o-u+1),a},dD=function(s,e){if(!s&&!e||!s&&e||s&&!e)return!1;if(s===e)return!0;const t=Object.keys(s).sort(),i=Object.keys(e).sort();if(t.length!==i.length)return!1;for(let r=0;rt))return n}return i.length===0?0:i[i.length-1]},br=1,fD=500,$h=s=>typeof s=="number"&&isFinite(s),Yn=1/60,pD=(s,e,t)=>s!=="main"||!e||!t?null:!t.hasAudio&&!t.hasVideo?"Neither audio nor video found in segment.":e.hasVideo&&!t.hasVideo?"Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.":!e.hasVideo&&t.hasVideo?"Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.":null,mD=(s,e,t)=>{let i=e-$e.BACK_BUFFER_LENGTH;s.length&&(i=Math.max(i,s.start(0)));const r=e-t;return Math.min(r,i)},hs=s=>{const{startOfSegment:e,duration:t,segment:i,part:r,playlist:{mediaSequence:n,id:a,segments:o=[]},mediaIndex:u,partIndex:c,timeline:p}=s,y=o.length-1;let v="mediaIndex/partIndex increment";s.getMediaInfoForTime?v=`getMediaInfoForTime (${s.getMediaInfoForTime})`:s.isSyncRequest&&(v="getSyncSegmentCandidate (isSyncRequest)"),s.independent&&(v+=` with independent ${s.independent}`);const b=typeof c=="number",C=s.segment.uri?"segment":"pre-segment",_=b?lg({preloadSegment:i})-1:0;return`${C} [${n+u}/${n+y}]`+(b?` part [${c}/${_}]`:"")+` segment start/end [${i.start} => ${i.end}]`+(b?` part start/end [${r.start} => ${r.end}]`:"")+` startOfSegment [${e}] duration [${t}] timeline [${p}] selected by [${v}] playlist [${a}]`},jh=s=>`${s}TimingInfo`,gD=({segmentTimeline:s,currentTimeline:e,startOfSegment:t,buffered:i,overrideCheck:r})=>!r&&s===e?null:s{if(e===t)return!1;if(i==="audio"){const n=s.lastTimelineChange({type:"main"});return!n||n.to!==t}if(i==="main"&&r){const n=s.pendingTimelineChange({type:"audio"});return!(n&&n.to===t)}return!1},yD=s=>{if(!s)return!1;const e=s.pendingTimelineChange({type:"audio"}),t=s.pendingTimelineChange({type:"main"}),i=e&&t,r=i&&e.to!==t.to;return!!(i&&e.from!==-1&&t.from!==-1&&r)},_D=s=>{s&&(s.pause(),s.resetEverything(),s.load())},vD=s=>{const e=s.timelineChangeController_.pendingTimelineChange({type:"audio"}),t=s.timelineChangeController_.pendingTimelineChange({type:"main"});return e&&t&&e.to{const e=s.pendingSegment_;if(!e)return;if(Hl({timelineChangeController:s.timelineChangeController_,currentTimeline:s.currentTimeline_,segmentTimeline:e.timeline,loaderType:s.loaderType_,audioDisabled:s.audioDisabled_})&&yD(s.timelineChangeController_)){if(vD(s)){s.timelineChangeController_.trigger("audioTimelineBehind");return}_D(s)}},TD=s=>{let e=0;return["video","audio"].forEach(function(t){const i=s[`${t}TimingInfo`];if(!i)return;const{start:r,end:n}=i;let a;typeof r=="bigint"||typeof n=="bigint"?a=E.BigInt(n)-E.BigInt(r):typeof r=="number"&&typeof n=="number"&&(a=n-r),typeof a<"u"&&a>e&&(e=a)}),typeof e=="bigint"&&es?Math.round(s)>e+Bt:!1,bD=(s,e)=>{if(e!=="hls")return null;const t=TD({audioTimingInfo:s.audioTimingInfo,videoTimingInfo:s.videoTimingInfo});if(!t)return null;const i=s.playlist.targetDuration,r=qh({segmentDuration:t,maxDuration:i*2}),n=qh({segmentDuration:t,maxDuration:i}),a=`Segment with index ${s.mediaIndex} from playlist ${s.playlist.id} has a duration of ${t} when the reported duration is ${s.duration} and the target duration is ${i}. For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1`;return r||n?{severity:r?"warn":"info",message:a}:null},Bi=({type:s,segment:e})=>{if(!e)return;const t=!!(e.key||e.map&&e.map.ke),i=!!(e.map&&!e.map.bytes),r=e.startOfSegment===void 0?e.start:e.startOfSegment;return{type:s||e.type,uri:e.resolvedUri||e.uri,start:r,duration:e.duration,isEncrypted:t,isMediaInitialization:i}};class Vl extends O.EventTarget{constructor(e,t={}){if(super(),!e)throw new TypeError("Initialization settings are required");if(typeof e.currentTime!="function")throw new TypeError("No currentTime getter specified");if(!e.mediaSource)throw new TypeError("No MediaSource specified");this.bandwidth=e.bandwidth,this.throughput={rate:0,count:0},this.roundTrip=NaN,this.resetStats_(),this.mediaIndex=null,this.partIndex=null,this.hasPlayed_=e.hasPlayed,this.currentTime_=e.currentTime,this.seekable_=e.seekable,this.seeking_=e.seeking,this.duration_=e.duration,this.mediaSource_=e.mediaSource,this.vhs_=e.vhs,this.loaderType_=e.loaderType,this.currentMediaInfo_=void 0,this.startingMediaInfo_=void 0,this.segmentMetadataTrack_=e.segmentMetadataTrack,this.goalBufferLength_=e.goalBufferLength,this.sourceType_=e.sourceType,this.sourceUpdater_=e.sourceUpdater,this.inbandTextTracks_=e.inbandTextTracks,this.state_="INIT",this.timelineChangeController_=e.timelineChangeController,this.shouldSaveSegmentTimingInfo_=!0,this.parse708captions_=e.parse708captions,this.useDtsForTimestampOffset_=e.useDtsForTimestampOffset,this.captionServices_=e.captionServices,this.exactManifestTimings=e.exactManifestTimings,this.addMetadataToTextTrack=e.addMetadataToTextTrack,this.checkBufferTimeout_=null,this.error_=void 0,this.currentTimeline_=-1,this.shouldForceTimestampOffsetAfterResync_=!1,this.pendingSegment_=null,this.xhrOptions_=null,this.pendingSegments_=[],this.audioDisabled_=!1,this.isPendingTimestampOffset_=!1,this.gopBuffer_=[],this.timeMapping_=0,this.safeAppend_=!1,this.appendInitSegment_={audio:!0,video:!0},this.playlistOfLastInitSegment_={audio:null,video:null},this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_={id3:[],caption:[]},this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=null,this.activeInitSegmentId_=null,this.initSegments_={},this.cacheEncryptionKeys_=e.cacheEncryptionKeys,this.keyCache_={},this.decrypter_=e.decrypter,this.syncController_=e.syncController,this.syncPoint_={segmentIndex:0,time:0},this.transmuxer_=this.createTransmuxer_(),this.triggerSyncInfoUpdate_=()=>this.trigger("syncinfoupdate"),this.syncController_.on("syncinfoupdate",this.triggerSyncInfoUpdate_),this.mediaSource_.addEventListener("sourceopen",()=>{this.isEndOfStream_()||(this.ended_=!1)}),this.fetchAtBuffer_=!1,this.logger_=Ct(`SegmentLoader[${this.loaderType_}]`),Object.defineProperty(this,"state",{get(){return this.state_},set(i){i!==this.state_&&(this.logger_(`${this.state_} -> ${i}`),this.state_=i,this.trigger("statechange"))}}),this.sourceUpdater_.on("ready",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():fi(this)}),this.sourceUpdater_.on("codecschange",i=>{this.trigger(xe({type:"codecschange"},i))}),this.loaderType_==="main"&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():fi(this)}),this.loaderType_==="audio"&&this.timelineChangeController_.on("timelinechange",i=>{this.trigger(xe({type:"timelinechange"},i)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():fi(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():fi(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return dl.createTransmuxer({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,captionServices:this.captionServices_})}resetStats_(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0}dispose(){this.trigger("dispose"),this.state="DISPOSED",this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&E.clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_),this.off()}setAudio(e){this.audioDisabled_=!e,e?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){if(this.state!=="WAITING"){this.pendingSegment_&&(this.pendingSegment_=null);return}this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_()}abort_(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests(),this.pendingSegment_=null,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_),this.waitingOnRemove_=!1,E.clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(e){return this.state==="APPENDING"&&!this.pendingSegment_?(this.state="READY",!0):!this.pendingSegment_||this.pendingSegment_.requestId!==e}error(e){return typeof e<"u"&&(this.logger_("error occurred:",e),this.error_=e),this.pendingSegment_=null,this.error_}endOfStream(){this.ended_=!0,this.transmuxer_&&dl.reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return Ve();if(this.loaderType_==="main"){const{hasAudio:t,hasVideo:i,isMuxed:r}=e;if(i&&t&&!this.audioDisabled_&&!r)return this.sourceUpdater_.buffered();if(i)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(e,t=!1){if(!e)return null;const i=Pa(e);let r=this.initSegments_[i];return t&&!r&&e.bytes&&(this.initSegments_[i]=r={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),r||e}segmentKey(e,t=!1){if(!e)return null;const i=Cg(e);let r=this.keyCache_[i];this.cacheEncryptionKeys_&&t&&!r&&e.bytes&&(this.keyCache_[i]=r={resolvedUri:e.resolvedUri,bytes:e.bytes});const n={resolvedUri:(r||e).resolvedUri};return r&&(n.bytes=r.bytes),n}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),!!this.playlist_){if(this.state==="INIT"&&this.couldBeginLoading_())return this.init_();!this.couldBeginLoading_()||this.state!=="READY"&&this.state!=="INIT"||(this.state="READY")}}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}playlist(e,t={}){if(!e)return;const i=this.playlist_,r=this.pendingSegment_;this.playlist_=e,this.xhrOptions_=t,this.state==="INIT"&&(e.syncInfo={mediaSequence:e.mediaSequence,time:0},this.loaderType_==="main"&&this.syncController_.setDateTimeMappingForStart(e));let n=null;if(i&&(i.id?n=i.id:i.uri&&(n=i.uri)),this.logger_(`playlist update [${n} => ${e.id||e.uri}]`),this.mediaSequenceSync_&&(this.mediaSequenceSync_.update(e,this.currentTime_()),this.logger_(`Playlist update:
+currentTime: ${this.currentTime_()}
+bufferedEnd: ${ul(this.buffered_())}
+`,this.mediaSequenceSync_.diagnostics)),this.trigger("syncinfoupdate"),this.state==="INIT"&&this.couldBeginLoading_())return this.init_();if(!i||i.uri!==e.uri){this.mediaIndex!==null&&(!e.endList&&typeof e.partTargetDuration=="number"?this.resetLoader():this.resyncLoader()),this.currentMediaInfo_=void 0,this.trigger("playlistupdate");return}const a=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${a}]`),this.mediaIndex!==null)if(this.mediaIndex-=a,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{const o=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!o.parts||!o.parts.length||!o.parts[this.partIndex])){const u=this.mediaIndex;this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=u}}r&&(r.mediaIndex-=a,r.mediaIndex<0?(r.mediaIndex=null,r.partIndex=null):(r.mediaIndex>=0&&(r.segment=e.segments[r.mediaIndex]),r.partIndex>=0&&r.segment.parts&&(r.part=r.segment.parts[r.partIndex]))),this.syncController_.saveExpiredSegmentInfo(i,e)}pause(){this.checkBufferTimeout_&&(E.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=null)}paused(){return this.checkBufferTimeout_===null}resetEverything(e){this.ended_=!1,this.activeInitSegmentId_=null,this.appendInitSegment_={audio:!0,video:!0},this.resetLoader(),this.remove(0,1/0,e),this.transmuxer_&&(this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.transmuxer_.postMessage({action:"reset"}))}resetLoader(){this.fetchAtBuffer_=!1,this.mediaSequenceSync_&&this.mediaSequenceSync_.resetAppendedStatus(),this.resyncLoader()}resyncLoader(){this.transmuxer_&&dl.reset(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1;const e=this.currentMediaInfo_&&this.currentMediaInfo_.isFmp4;this.sourceType_==="hls"&&!e&&(this.shouldForceTimestampOffsetAfterResync_=!0),this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}remove(e,t,i=()=>{},r=!1){if(t===1/0&&(t=this.duration_()),t<=e){this.logger_("skipping remove because end ${end} is <= start ${start}");return}if(!this.sourceUpdater_||!this.getMediaInfo_()){this.logger_("skipping remove because no source updater or starting media info");return}let n=1;const a=()=>{n--,n===0&&i()};(r||!this.audioDisabled_)&&(n++,this.sourceUpdater_.removeAudio(e,t,a)),(r||this.loaderType_==="main")&&(this.gopBuffer_=cD(this.gopBuffer_,e,t,this.timeMapping_),n++,this.sourceUpdater_.removeVideo(e,t,a));for(const o in this.inbandTextTracks_)Ir(e,t,this.inbandTextTracks_[o]);Ir(e,t,this.segmentMetadataTrack_),a()}monitorBuffer_(){this.checkBufferTimeout_&&E.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=E.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){this.state==="READY"&&this.fillBuffer_(),this.checkBufferTimeout_&&E.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=E.setTimeout(this.monitorBufferTick_.bind(this),fD)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();if(!e)return;const t={segmentInfo:Bi({type:this.loaderType_,segment:e})};this.trigger({type:"segmentselected",metadata:t}),typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e)}isEndOfStream_(e=this.mediaIndex,t=this.playlist_,i=this.partIndex){if(!t||!this.mediaSource_)return!1;const r=typeof e=="number"&&t.segments[e],n=e+1===t.segments.length,a=!r||!r.parts||i+1===r.parts.length;return t.endList&&this.mediaSource_.readyState==="open"&&n&&a}chooseNextRequest_(){const e=this.buffered_(),t=ul(e)||0,i=Qu(e,this.currentTime_()),r=!this.hasPlayed_()&&i>=1,n=i>=this.goalBufferLength_(),a=this.playlist_.segments;if(!a.length||r||n)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);const o={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:!this.syncPoint_};if(o.isSyncRequest)o.mediaIndex=hD(this.currentTimeline_,a,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${o.mediaIndex}`);else if(this.mediaIndex!==null){const v=a[this.mediaIndex],b=typeof this.partIndex=="number"?this.partIndex:-1;o.startOfSegment=v.end?v.end:t,v.parts&&v.parts[b+1]?(o.mediaIndex=this.mediaIndex,o.partIndex=b+1):o.mediaIndex=this.mediaIndex+1}else{let v,b,C;const _=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch:
+For TargetTime: ${_}.
+CurrentTime: ${this.currentTime_()}
+BufferedEnd: ${t}
+Fetch At Buffer: ${this.fetchAtBuffer_}
+`,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){const D=this.getSyncInfoFromMediaSequenceSync_(_);if(!D){const w="No sync info found while using media sequence sync";return this.error({message:w,metadata:{errorType:O.Error.StreamingFailedToSelectNextSegment,error:new Error(w)}}),this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${D.start} --> ${D.end})`),v=D.segmentIndex,b=D.partIndex,C=D.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");const D=ut.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:_,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});v=D.segmentIndex,b=D.partIndex,C=D.startTime}o.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${_}`:`currentTime ${_}`,o.mediaIndex=v,o.startOfSegment=C,o.partIndex=b,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${o.mediaIndex} `)}const u=a[o.mediaIndex];let c=u&&typeof o.partIndex=="number"&&u.parts&&u.parts[o.partIndex];if(!u||typeof o.partIndex=="number"&&!c)return null;typeof o.partIndex!="number"&&u.parts&&(o.partIndex=0,c=u.parts[0]);const p=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!i&&c&&!p&&!c.independent)if(o.partIndex===0){const v=a[o.mediaIndex-1],b=v.parts&&v.parts.length&&v.parts[v.parts.length-1];b&&b.independent&&(o.mediaIndex-=1,o.partIndex=v.parts.length-1,o.independent="previous segment")}else u.parts[o.partIndex-1].independent&&(o.partIndex-=1,o.independent="previous part");const y=this.mediaSource_&&this.mediaSource_.readyState==="ended";return o.mediaIndex>=a.length-1&&y&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,o.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync")),this.generateSegmentInfo_(o))}getSyncInfoFromMediaSequenceSync_(e){if(!this.mediaSequenceSync_)return null;const t=Math.max(e,this.mediaSequenceSync_.start);e!==t&&this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${e} to ${t}`);const i=this.mediaSequenceSync_.getSyncInfoForTime(t);if(!i)return null;if(!i.isAppended)return i;const r=this.mediaSequenceSync_.getSyncInfoForTime(i.end);return r?(r.isAppended&&this.logger_("getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!"),r):null}generateSegmentInfo_(e){const{independent:t,playlist:i,mediaIndex:r,startOfSegment:n,isSyncRequest:a,partIndex:o,forceTimestampOffset:u,getMediaInfoForTime:c}=e,p=i.segments[r],y=typeof o=="number"&&p.parts[o],v={requestId:"segment-loader-"+Math.random(),uri:y&&y.resolvedUri||p.resolvedUri,mediaIndex:r,partIndex:y?o:null,isSyncRequest:a,startOfSegment:n,playlist:i,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:p.timeline,duration:y&&y.duration||p.duration,segment:p,part:y,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:c,independent:t},b=typeof u<"u"?u:this.isPendingTimestampOffset_;v.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:p.timeline,currentTimeline:this.currentTimeline_,startOfSegment:n,buffered:this.buffered_(),overrideCheck:b});const C=ul(this.sourceUpdater_.audioBuffered());return typeof C=="number"&&(v.audioAppendStart=C-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(v.gopsToAlignWith=lD(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),v}timestampOffsetForSegment_(e){return gD(e)}earlyAbortWhenNeeded_(e){if(this.vhs_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH||Date.now()-(e.firstBytesReceivedAt||Date.now())<1e3)return;const t=this.currentTime_(),i=e.bandwidth,r=this.pendingSegment_.duration,n=ut.estimateSegmentRequestTime(r,i,this.playlist_,e.bytesReceived),a=UA(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(n<=a)return;const o=Qw({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:r,timeUntilRebuffer:a,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!o)return;const c=n-a-o.rebufferingImpact;let p=.5;a<=Bt&&(p=1),!(!o.playlist||o.playlist.uri===this.playlist_.uri||c{n[a.stream]=n[a.stream]||{startTime:1/0,captions:[],endTime:0};const o=n[a.stream];o.startTime=Math.min(o.startTime,a.startTime+r),o.endTime=Math.max(o.endTime,a.endTime+r),o.captions.push(a)}),Object.keys(n).forEach(a=>{const{startTime:o,endTime:u,captions:c}=n[a],p=this.inbandTextTracks_;this.logger_(`adding cues from ${o} -> ${u} for ${a}`),eD(p,this.vhs_.tech_,a),Ir(o,u,p[a]),tD({captionArray:c,inbandTextTracks:p,timestampOffset:r})}),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}handleId3_(e,t,i){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(!this.pendingSegment_.hasAppendedData_){this.metadataQueue_.id3.push(this.handleId3_.bind(this,e,t,i));return}this.addMetadataToTextTrack(i,t,this.duration_())}processMetadataQueue_(){this.metadataQueue_.id3.forEach(e=>e()),this.metadataQueue_.caption.forEach(e=>e()),this.metadataQueue_.id3=[],this.metadataQueue_.caption=[]}processCallQueue_(){const e=this.callQueue_;this.callQueue_=[],e.forEach(t=>t())}processLoadQueue_(){const e=this.loadQueue_;this.loadQueue_=[],e.forEach(t=>t())}hasEnoughInfoToLoad_(){if(this.loaderType_!=="audio")return!0;const e=this.pendingSegment_;return e?this.getCurrentMediaInfo_()?!Hl({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}):!0:!1}getCurrentMediaInfo_(e=this.pendingSegment_){return e&&e.trackInfo||this.currentMediaInfo_}getMediaInfo_(e=this.pendingSegment_){return this.getCurrentMediaInfo_(e)||this.startingMediaInfo_}getPendingSegmentPlaylist(){return this.pendingSegment_?this.pendingSegment_.playlist:null}hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready()||this.waitingOnRemove_||this.quotaExceededErrorRetryTimeout_)return!1;const e=this.pendingSegment_,t=this.getCurrentMediaInfo_();if(!e||!t)return!1;const{hasAudio:i,hasVideo:r,isMuxed:n}=t;return!(r&&!e.videoTimingInfo||i&&!this.audioDisabled_&&!n&&!e.audioTimingInfo||Hl({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}handleData_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(this.callQueue_.length||!this.hasEnoughInfoToAppend_()){fi(this),this.callQueue_.push(this.handleData_.bind(this,e,t));return}const i=this.pendingSegment_;if(this.setTimeMapping_(i.timeline),this.updateMediaSecondsLoaded_(i.part||i.segment),this.mediaSource_.readyState!=="closed"){if(e.map&&(e.map=this.initSegmentForMap(e.map,!0),i.segment.map=e.map),e.key&&this.segmentKey(e.key,!0),i.isFmp4=e.isFmp4,i.timingInfo=i.timingInfo||{},i.isFmp4)this.trigger("fmp4"),i.timingInfo.start=i[jh(t.type)].start;else{const r=this.getCurrentMediaInfo_(),n=this.loaderType_==="main"&&r&&r.hasVideo;let a;n&&(a=i.videoTimingInfo.start),i.timingInfo.start=this.trueSegmentStart_({currentStart:i.timingInfo.start,playlist:i.playlist,mediaIndex:i.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:n,firstVideoFrameTimeForData:a,videoTimingInfo:i.videoTimingInfo,audioTimingInfo:i.audioTimingInfo})}if(this.updateAppendInitSegmentStatus(i,t.type),this.updateSourceBufferTimestampOffset_(i),i.isSyncRequest){this.updateTimingInfoEnd_(i),this.syncController_.saveSegmentTimingInfo({segmentInfo:i,shouldSaveTimelineMapping:this.loaderType_==="main"});const r=this.chooseNextRequest_();if(r.mediaIndex!==i.mediaIndex||r.partIndex!==i.partIndex){this.logger_("sync segment was incorrect, not appending");return}this.logger_("sync segment was correct, appending")}i.hasAppendedData_=!0,this.processMetadataQueue_(),this.appendData_(i,t)}}updateAppendInitSegmentStatus(e,t){this.loaderType_==="main"&&typeof e.timestampOffset=="number"&&!e.changedTimestampOffset&&(this.appendInitSegment_={audio:!0,video:!0}),this.playlistOfLastInitSegment_[t]!==e.playlist&&(this.appendInitSegment_[t]=!0)}getInitSegmentAndUpdateState_({type:e,initSegment:t,map:i,playlist:r}){if(i){const n=Pa(i);if(this.activeInitSegmentId_===n)return null;t=this.initSegmentForMap(i,!0).bytes,this.activeInitSegmentId_=n}return t&&this.appendInitSegment_[e]?(this.playlistOfLastInitSegment_[e]=r,this.appendInitSegment_[e]=!1,this.activeInitSegmentId_=null,t):null}handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i},r){const n=this.sourceUpdater_.audioBuffered(),a=this.sourceUpdater_.videoBuffered();n.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+ji(n).join(", ")),a.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+ji(a).join(", "));const o=n.length?n.start(0):0,u=n.length?n.end(n.length-1):0,c=a.length?a.start(0):0,p=a.length?a.end(a.length-1):0;if(u-o<=br&&p-c<=br){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${ji(n).join(", ")}, video buffer: ${ji(a).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),this.trigger("error");return}this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:i}));const v=this.currentTime_()-br;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${v}`),this.remove(0,v,()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${br}s`),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=E.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},br*1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},r){if(r){if(r.code===vg){this.handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i});return}this.logger_("Received non QUOTA_EXCEEDED_ERR on append",r),this.error({message:`${t} append of ${i.length}b failed for segment #${e.mediaIndex} in playlist ${e.playlist.id}`,metadata:{errorType:O.Error.StreamingFailedToAppendSegment}}),this.trigger("appenderror")}}appendToSourceBuffer_({segmentInfo:e,type:t,initSegment:i,data:r,bytes:n}){if(!n){const o=[r];let u=r.byteLength;i&&(o.unshift(i),u+=i.byteLength),n=Zw({bytes:u,segments:o})}const a={segmentInfo:Bi({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:a}),this.sourceUpdater_.appendBuffer({segmentInfo:e,type:t,bytes:n},this.handleAppendError_.bind(this,{segmentInfo:e,type:t,bytes:n}))}handleSegmentTimingInfo_(e,t,i){if(!this.pendingSegment_||t!==this.pendingSegment_.requestId)return;const r=this.pendingSegment_.segment,n=`${e}TimingInfo`;r[n]||(r[n]={}),r[n].transmuxerPrependedSeconds=i.prependedContentDuration||0,r[n].transmuxedPresentationStart=i.start.presentation,r[n].transmuxedDecodeStart=i.start.decode,r[n].transmuxedPresentationEnd=i.end.presentation,r[n].transmuxedDecodeEnd=i.end.decode,r[n].baseMediaDecodeTime=i.baseMediaDecodeTime}appendData_(e,t){const{type:i,data:r}=t;if(!r||!r.byteLength||i==="audio"&&this.audioDisabled_)return;const n=this.getInitSegmentAndUpdateState_({type:i,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:i,initSegment:n,data:r})}loadSegment_(e){if(this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),typeof e.timestampOffset=="number"&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),!this.hasEnoughInfoToLoad_()){fi(this),this.loadQueue_.push(()=>{const t=xe({},e,{forceTimestampOffset:!0});xe(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)});return}this.updateTransmuxerAndRequestSegment_(e)}updateTransmuxerAndRequestSegment_(e){this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:e.timestampOffset}));const t=this.createSimplifiedSegmentObj_(e),i=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),r=this.mediaIndex!==null,n=e.timeline!==this.currentTimeline_&&e.timeline>0,a=i||r&&n;this.logger_(`Requesting
+${qg(e.uri)}
+${hs(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=zw({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:t,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"audio",e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:a,endedTimelineFn:()=>{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:o,level:u,stream:c})=>{this.logger_(`${hs(e)} logged from transmuxer stream ${c} as a ${u}: ${o}`)},triggerSegmentEventFn:({type:o,segment:u,keyInfo:c,trackInfo:p,timingInfo:y})=>{const b={segmentInfo:Bi({segment:u})};c&&(b.keyInfo=c),p&&(b.trackInfo=p),y&&(b.timingInfo=y),this.trigger({type:o,metadata:b})}})}trimBackBuffer_(e){const t=mD(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){const t=e.segment,i=e.part,r=e.segment.key||e.segment.map&&e.segment.map.key,n=e.segment.map&&!e.segment.map.bytes,a={resolvedUri:i?i.resolvedUri:t.resolvedUri,byterange:i?i.byterange:t.byterange,requestId:e.requestId,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,part:e.part,type:this.loaderType_,start:e.startOfSegment,duration:e.duration,isEncrypted:r,isMediaInitialization:n},o=e.playlist.segments[e.mediaIndex-1];if(o&&o.timeline===t.timeline&&(o.videoTimingInfo?a.baseStartTime=o.videoTimingInfo.transmuxedDecodeEnd:o.audioTimingInfo&&(a.baseStartTime=o.audioTimingInfo.transmuxedDecodeEnd)),t.key){const u=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);a.key=this.segmentKey(t.key),a.key.iv=u}return t.map&&(a.map=this.initSegmentForMap(t.map)),a}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){if(this.pendingSegment_.byteLength=t.bytesReceived,e"u"||c.end!==r+n?r:o.start}waitForAppendsToComplete_(e){const t=this.getCurrentMediaInfo_(e);if(!t){this.error({message:"No starting media returned, likely due to an unsupported media format.",playlistExclusionDuration:1/0}),this.trigger("error");return}const{hasAudio:i,hasVideo:r,isMuxed:n}=t,a=this.loaderType_==="main"&&r,o=!this.audioDisabled_&&i&&!n;if(e.waitingOnAppends=0,!e.hasAppendedData_){!e.timingInfo&&typeof e.timestampOffset=="number"&&(this.isPendingTimestampOffset_=!0),e.timingInfo={start:0},e.waitingOnAppends++,this.isPendingTimestampOffset_||(this.updateSourceBufferTimestampOffset_(e),this.processMetadataQueue_()),this.checkAppendsDone_(e);return}a&&e.waitingOnAppends++,o&&e.waitingOnAppends++,a&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,e)),o&&this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this,e))}checkAppendsDone_(e){this.checkForAbort_(e.requestId)||(e.waitingOnAppends--,e.waitingOnAppends===0&&this.handleAppendsDone_())}checkForIllegalMediaSwitch(e){const t=pD(this.loaderType_,this.getCurrentMediaInfo_(),e);return t?(this.error({message:t,playlistExclusionDuration:1/0}),this.trigger("error"),!0):!1}updateSourceBufferTimestampOffset_(e){if(e.timestampOffset===null||typeof e.timingInfo.start!="number"||e.changedTimestampOffset||this.loaderType_!=="main")return;let t=!1;e.timestampOffset-=this.getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e.segment.videoTimingInfo,audioTimingInfo:e.segment.audioTimingInfo,timingInfo:e.timingInfo}),e.changedTimestampOffset=!0,e.timestampOffset!==this.sourceUpdater_.videoTimestampOffset()&&(this.sourceUpdater_.videoTimestampOffset(e.timestampOffset),t=!0),e.timestampOffset!==this.sourceUpdater_.audioTimestampOffset()&&(this.sourceUpdater_.audioTimestampOffset(e.timestampOffset),t=!0),t&&this.trigger("timestampoffset")}getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e,audioTimingInfo:t,timingInfo:i}){return this.useDtsForTimestampOffset_?e&&typeof e.transmuxedDecodeStart=="number"?e.transmuxedDecodeStart:t&&typeof t.transmuxedDecodeStart=="number"?t.transmuxedDecodeStart:i.start:i.start}updateTimingInfoEnd_(e){e.timingInfo=e.timingInfo||{};const t=this.getMediaInfo_(),r=this.loaderType_==="main"&&t&&t.hasVideo&&e.videoTimingInfo?e.videoTimingInfo:e.audioTimingInfo;r&&(e.timingInfo.end=typeof r.end=="number"?r.end:r.start+e.duration)}handleAppendsDone_(){if(this.pendingSegment_){const u={segmentInfo:Bi({type:this.loaderType_,segment:this.pendingSegment_})};this.trigger({type:"appendsdone",metadata:u})}if(!this.pendingSegment_){this.state="READY",this.paused()||this.monitorBuffer_();return}const e=this.pendingSegment_;e.part&&e.part.syncInfo?e.part.syncInfo.markAppended():e.segment.syncInfo&&e.segment.syncInfo.markAppended(),this.updateTimingInfoEnd_(e),this.shouldSaveSegmentTimingInfo_&&this.syncController_.saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:this.loaderType_==="main"});const t=bD(e,this.sourceType_);if(t&&(t.severity==="warn"?O.log.warn(t.message):this.logger_(t.message)),this.recordThroughput_(e),this.pendingSegment_=null,this.state="READY",e.isSyncRequest&&(this.trigger("syncinfoupdate"),!e.hasAppendedData_)){this.logger_(`Throwing away un-appended sync request ${hs(e)}`);return}this.logger_(`Appended ${hs(e)}`),this.addSegmentMetadataCue_(e),this.fetchAtBuffer_=!0,this.currentTimeline_!==e.timeline&&(this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline}),this.loaderType_==="main"&&!this.audioDisabled_&&this.timelineChangeController_.lastTimelineChange({type:"audio",from:this.currentTimeline_,to:e.timeline})),this.currentTimeline_=e.timeline,this.trigger("syncinfoupdate");const i=e.segment,r=e.part,n=i.end&&this.currentTime_()-i.end>e.playlist.targetDuration*3,a=r&&r.end&&this.currentTime_()-r.end>e.playlist.partTargetDuration*3;if(n||a){this.logger_(`bad ${n?"segment":"part"} ${hs(e)}`),this.resetEverything();return}this.mediaIndex!==null&&this.trigger("bandwidthupdate"),this.trigger("progress"),this.mediaIndex=e.mediaIndex,this.partIndex=e.partIndex,this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex)&&this.endOfStream(),this.trigger("appended"),e.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitorBuffer_()}recordThroughput_(e){if(e.duratione.toUpperCase())},SD=["video","audio"],zl=(s,e)=>{const t=e[`${s}Buffer`];return t&&t.updating||e.queuePending[s]},xD=(s,e)=>{for(let t=0;t{if(e.queue.length===0)return;let t=0,i=e.queue[t];if(i.type==="mediaSource"){!e.updating()&&e.mediaSource.readyState!=="closed"&&(e.queue.shift(),i.action(e),i.doneFn&&i.doneFn(),ks("audio",e),ks("video",e));return}if(s!=="mediaSource"&&!(!e.ready()||e.mediaSource.readyState==="closed"||zl(s,e))){if(i.type!==s){if(t=xD(s,e.queue),t===null)return;i=e.queue[t]}if(e.queue.splice(t,1),e.queuePending[s]=i,i.action(s,e),!i.doneFn){e.queuePending[s]=null,ks(s,e);return}}},Vg=(s,e)=>{const t=e[`${s}Buffer`],i=Hg(s);t&&(t.removeEventListener("updateend",e[`on${i}UpdateEnd_`]),t.removeEventListener("error",e[`on${i}Error_`]),e.codecs[s]=null,e[`${s}Buffer`]=null)},Nt=(s,e)=>s&&e&&Array.prototype.indexOf.call(s.sourceBuffers,e)!==-1,ft={appendBuffer:(s,e,t)=>(i,r)=>{const n=r[`${i}Buffer`];if(Nt(r.mediaSource,n)){r.logger_(`Appending segment ${e.mediaIndex}'s ${s.length} bytes to ${i}Buffer`);try{n.appendBuffer(s)}catch(a){r.logger_(`Error with code ${a.code} `+(a.code===vg?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${e.mediaIndex} to ${i}Buffer`),r.queuePending[i]=null,t(a)}}},remove:(s,e)=>(t,i)=>{const r=i[`${t}Buffer`];if(Nt(i.mediaSource,r)){i.logger_(`Removing ${s} to ${e} from ${t}Buffer`);try{r.remove(s,e)}catch{i.logger_(`Remove ${s} to ${e} from ${t}Buffer failed`)}}},timestampOffset:s=>(e,t)=>{const i=t[`${e}Buffer`];Nt(t.mediaSource,i)&&(t.logger_(`Setting ${e}timestampOffset to ${s}`),i.timestampOffset=s)},callback:s=>(e,t)=>{s()},endOfStream:s=>e=>{if(e.mediaSource.readyState==="open"){e.logger_(`Calling mediaSource endOfStream(${s||""})`);try{e.mediaSource.endOfStream(s)}catch(t){O.log.warn("Failed to call media source endOfStream",t)}}},duration:s=>e=>{e.logger_(`Setting mediaSource duration to ${s}`);try{e.mediaSource.duration=s}catch(t){O.log.warn("Failed to set media source duration",t)}},abort:()=>(s,e)=>{if(e.mediaSource.readyState!=="open")return;const t=e[`${s}Buffer`];if(Nt(e.mediaSource,t)){e.logger_(`calling abort on ${s}Buffer`);try{t.abort()}catch(i){O.log.warn(`Failed to abort on ${s}Buffer`,i)}}},addSourceBuffer:(s,e)=>t=>{const i=Hg(s),r=Ls(e);t.logger_(`Adding ${s}Buffer with codec ${e} to mediaSource`);const n=t.mediaSource.addSourceBuffer(r);n.addEventListener("updateend",t[`on${i}UpdateEnd_`]),n.addEventListener("error",t[`on${i}Error_`]),t.codecs[s]=e,t[`${s}Buffer`]=n},removeSourceBuffer:s=>e=>{const t=e[`${s}Buffer`];if(Vg(s,e),!!Nt(e.mediaSource,t)){e.logger_(`Removing ${s}Buffer with codec ${e.codecs[s]} from mediaSource`);try{e.mediaSource.removeSourceBuffer(t)}catch(i){O.log.warn(`Failed to removeSourceBuffer ${s}Buffer`,i)}}},changeType:s=>(e,t)=>{const i=t[`${e}Buffer`],r=Ls(s);if(!Nt(t.mediaSource,i))return;const n=s.substring(0,s.indexOf(".")),a=t.codecs[e];if(a.substring(0,a.indexOf("."))===n)return;const u={codecsChangeInfo:{from:a,to:s}};t.trigger({type:"codecschange",metadata:u}),t.logger_(`changing ${e}Buffer codec from ${a} to ${s}`);try{i.changeType(r),t.codecs[e]=s}catch(c){u.errorType=O.Error.StreamingCodecsChangeError,u.error=c,c.metadata=u,t.error_=c,t.trigger("error"),O.log.warn(`Failed to changeType on ${e}Buffer`,c)}}},pt=({type:s,sourceUpdater:e,action:t,doneFn:i,name:r})=>{e.queue.push({type:s,action:t,doneFn:i,name:r}),ks(s,e)},Hh=(s,e)=>t=>{const i=e[`${s}Buffered`](),r=MA(i);if(e.logger_(`received "updateend" event for ${s} Source Buffer: `,r),e.queuePending[s]){const n=e.queuePending[s].doneFn;e.queuePending[s]=null,n&&n(e[`${s}Error_`])}ks(s,e)};class zg extends O.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>ks("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=Ct("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=Hh("video",this),this.onAudioUpdateEnd_=Hh("audio",this),this.onVideoError_=t=>{this.videoError_=t},this.onAudioError_=t=>{this.audioError_=t},this.createdSourceBuffers_=!1,this.initializedEme_=!1,this.triggeredReady_=!1}initializedEme(){this.initializedEme_=!0,this.triggerReady()}hasCreatedSourceBuffers(){return this.createdSourceBuffers_}hasInitializedAnyEme(){return this.initializedEme_}ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme()}createSourceBuffers(e){this.hasCreatedSourceBuffers()||(this.addOrChangeSourceBuffers(e),this.createdSourceBuffers_=!0,this.trigger("createdsourcebuffers"),this.triggerReady())}triggerReady(){this.ready()&&!this.triggeredReady_&&(this.triggeredReady_=!0,this.trigger("ready"))}addSourceBuffer(e,t){pt({type:"mediaSource",sourceUpdater:this,action:ft.addSourceBuffer(e,t),name:"addSourceBuffer"})}abort(e){pt({type:e,sourceUpdater:this,action:ft.abort(e),name:"abort"})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){O.log.error("removeSourceBuffer is not supported!");return}pt({type:"mediaSource",sourceUpdater:this,action:ft.removeSourceBuffer(e),name:"removeSourceBuffer"})}canRemoveSourceBuffer(){return!O.browser.IS_FIREFOX&&E.MediaSource&&E.MediaSource.prototype&&typeof E.MediaSource.prototype.removeSourceBuffer=="function"}static canChangeType(){return E.SourceBuffer&&E.SourceBuffer.prototype&&typeof E.SourceBuffer.prototype.changeType=="function"}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){if(!this.canChangeType()){O.log.error("changeType is not supported!");return}pt({type:e,sourceUpdater:this,action:ft.changeType(t),name:"changeType"})}addOrChangeSourceBuffers(e){if(!e||typeof e!="object"||Object.keys(e).length===0)throw new Error("Cannot addOrChangeSourceBuffers to undefined codecs");Object.keys(e).forEach(t=>{const i=e[t];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(t,i);this.canChangeType()&&this.changeType(t,i)})}appendBuffer(e,t){const{segmentInfo:i,type:r,bytes:n}=e;if(this.processedAppend_=!0,r==="audio"&&this.videoBuffer&&!this.videoAppendQueued_){this.delayedAudioAppendQueue_.push([e,t]),this.logger_(`delayed audio append of ${n.length} until video append`);return}const a=t;if(pt({type:r,sourceUpdater:this,action:ft.appendBuffer(n,i||{mediaIndex:-1},a),doneFn:t,name:"appendBuffer"}),r==="video"){if(this.videoAppendQueued_=!0,!this.delayedAudioAppendQueue_.length)return;const o=this.delayedAudioAppendQueue_.slice();this.logger_(`queuing delayed audio ${o.length} appendBuffers`),this.delayedAudioAppendQueue_.length=0,o.forEach(u=>{this.appendBuffer.apply(this,u)})}}audioBuffered(){return Nt(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:Ve()}videoBuffered(){return Nt(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:Ve()}buffered(){const e=Nt(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=Nt(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():FA(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=ei){pt({type:"mediaSource",sourceUpdater:this,action:ft.duration(e),name:"duration",doneFn:t})}endOfStream(e=null,t=ei){typeof e!="string"&&(e=void 0),pt({type:"mediaSource",sourceUpdater:this,action:ft.endOfStream(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=ei){if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){i();return}pt({type:"audio",sourceUpdater:this,action:ft.remove(e,t),doneFn:i,name:"remove"})}removeVideo(e,t,i=ei){if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){i();return}pt({type:"video",sourceUpdater:this,action:ft.remove(e,t),doneFn:i,name:"remove"})}updating(){return!!(zl("audio",this)||zl("video",this))}audioTimestampOffset(e){return typeof e<"u"&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(pt({type:"audio",sourceUpdater:this,action:ft.timestampOffset(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return typeof e<"u"&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(pt({type:"video",sourceUpdater:this,action:ft.timestampOffset(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&pt({type:"audio",sourceUpdater:this,action:ft.callback(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&pt({type:"video",sourceUpdater:this,action:ft.callback(e),name:"callback"})}dispose(){this.trigger("dispose"),SD.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>Vg(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const Vh=s=>decodeURIComponent(escape(String.fromCharCode.apply(null,s))),ED=s=>{const e=new Uint8Array(s);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},zh=new Uint8Array(`
+
+`.split("").map(s=>s.charCodeAt(0)));class CD extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class AD extends Vl{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.loadVttJs=e.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}createTransmuxer_(){return null}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return Ve();const e=this.subtitlesTrack_.cues,t=e[0].startTime,i=e[e.length-1].startTime;return Ve([[t,i]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=Pa(e);let r=this.initSegments_[i];if(t&&!r&&e.bytes){const n=zh.byteLength+e.bytes.byteLength,a=new Uint8Array(n);a.set(e.bytes),a.set(zh,e.bytes.byteLength),this.initSegments_[i]=r={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:a}}return r||e}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}track(e){return typeof e>"u"?this.subtitlesTrack_:(this.subtitlesTrack_=e,this.state==="INIT"&&this.couldBeginLoading_()&&this.init_(),this.subtitlesTrack_)}remove(e,t){Ir(e,t,this.subtitlesTrack_)}fillBuffer_(){const e=this.chooseNextRequest_();if(e){if(this.syncController_.timestampOffsetForTimeline(e.timeline)===null){const t=()=>{this.state="READY",this.paused()||this.monitorBuffer_()};this.syncController_.one("timestampoffset",t),this.state="WAITING_ON_TIMELINE";return}this.loadSegment_(e)}}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(e){for(;e&&e.segment.empty;){if(e.mediaIndex+1>=e.playlist.segments.length){e=null;break}e=this.generateSegmentInfo_({playlist:e.playlist,mediaIndex:e.mediaIndex+1,startOfSegment:e.startOfSegment+e.duration,isSyncRequest:e.isSyncRequest})}return e}stopForError(e){this.error(e),this.state="READY",this.pause(),this.trigger("error")}segmentRequestFinished_(e,t,i){if(!this.subtitlesTrack_){this.state="READY";return}if(this.saveTransferStats_(t.stats),!this.pendingSegment_){this.state="READY",this.mediaRequestsAborted+=1;return}if(e){e.code===Ut.TIMEOUT&&this.handleTimeout_(),e.code===Ut.ABORTED?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,this.stopForError(e);return}const r=this.pendingSegment_;this.saveBandwidthRelatedStats_(r.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");const n=r.segment;if(n.map&&(n.map.bytes=t.map.bytes),r.bytes=t.bytes,typeof E.WebVTT!="function"&&typeof this.loadVttJs=="function"){this.state="WAITING_ON_VTTJS",this.loadVttJs().then(()=>this.segmentRequestFinished_(e,t,i),()=>this.stopForError({message:"Error loading vtt.js"}));return}n.requested=!0;try{this.parseVTTCues_(r)}catch(a){this.stopForError({message:a.message,metadata:{errorType:O.Error.StreamingVttParserError,error:a}});return}if(this.updateTimeMapping_(r,this.syncController_.timelines[r.timeline],this.playlist_),r.cues.length?r.timingInfo={start:r.cues[0].startTime,end:r.cues[r.cues.length-1].endTime}:r.timingInfo={start:r.startOfSegment,end:r.startOfSegment+r.duration},r.isSyncRequest){this.trigger("syncinfoupdate"),this.pendingSegment_=null,this.state="READY";return}r.byteLength=r.bytes.byteLength,this.mediaSecondsLoaded+=n.duration,r.cues.forEach(a=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new E.VTTCue(a.startTime,a.endTime,a.text):a)}),oD(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(){}updateTimingInfoEnd_(){}parseVTTCues_(e){let t,i=!1;if(typeof E.WebVTT!="function")throw new CD;typeof E.TextDecoder=="function"?t=new E.TextDecoder("utf8"):(t=E.WebVTT.StringDecoder(),i=!0);const r=new E.WebVTT.Parser(E,E.vttjs,t);if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},r.oncue=e.cues.push.bind(e.cues),r.ontimestampmap=a=>{e.timestampmap=a},r.onparsingerror=a=>{O.log.warn("Error encountered when parsing cues: "+a.message)},e.segment.map){let a=e.segment.map.bytes;i&&(a=Vh(a)),r.parse(a)}let n=e.bytes;i&&(n=Vh(n)),r.parse(n),r.flush()}updateTimeMapping_(e,t,i){const r=e.segment;if(!t)return;if(!e.cues.length){r.empty=!0;return}const{MPEGTS:n,LOCAL:a}=e.timestampmap,u=n/$i.ONE_SECOND_IN_TS-a+t.mapping;if(e.cues.forEach(c=>{const p=c.endTime-c.startTime,y=this.handleRollover_(c.startTime+u,t.time);c.startTime=Math.max(y,0),c.endTime=Math.max(y+p,0)}),!i.syncInfo){const c=e.cues[0].startTime,p=e.cues[e.cues.length-1].startTime;i.syncInfo={mediaSequence:i.mediaSequence+e.mediaIndex,time:Math.min(c,p-r.duration)}}}handleRollover_(e,t){if(t===null)return e;let i=e*$i.ONE_SECOND_IN_TS;const r=t*$i.ONE_SECOND_IN_TS;let n;for(r4294967296;)i+=n;return i/$i.ONE_SECOND_IN_TS}}const wD=function(s,e){const t=s.cues;for(let i=0;i=r.adStartTime&&e<=r.adEndTime)return r}return null},DD=function(s,e,t=0){if(!s.segments)return;let i=t,r;for(let n=0;n=this.start&&e0}resetAppendStatus(){this.segmentSyncInfo_.resetAppendedStatus(),this.partsSyncInfo_.forEach(e=>e.resetAppendedStatus())}}class Gg{constructor(){this.storage_=new Map,this.diagnostics_="",this.isReliable_=!1,this.start_=-1/0,this.end_=1/0}get start(){return this.start_}get end(){return this.end_}get diagnostics(){return this.diagnostics_}get isReliable(){return this.isReliable_}resetAppendedStatus(){this.storage_.forEach(e=>e.resetAppendStatus())}update(e,t){const{mediaSequence:i,segments:r}=e;if(this.isReliable_=this.isReliablePlaylist_(i,r),!!this.isReliable_)return this.updateStorage_(r,i,this.calculateBaseTime_(i,t))}getSyncInfoForTime(e){for(const{segmentSyncInfo:t,partsSyncInfo:i}of this.storage_.values())if(i.length){for(const r of i)if(r.isInRange(e))return r}else if(t.isInRange(e))return t;return null}getSyncInfoForMediaSequence(e){return this.storage_.get(e)}updateStorage_(e,t,i){const r=new Map;let n=`
+`,a=i,o=t;this.start_=a,e.forEach((u,c)=>{const p=this.storage_.get(o),y=a,v=y+u.duration,b=!!(p&&p.segmentSyncInfo&&p.segmentSyncInfo.isAppended),C=new Gh({start:y,end:v,appended:b,segmentIndex:c});u.syncInfo=C;let _=a;const D=(u.parts||[]).map((w,L)=>{const I=_,R=_+w.duration,k=!!(p&&p.partsSyncInfo&&p.partsSyncInfo[L]&&p.partsSyncInfo[L].isAppended),M=new Gh({start:I,end:R,appended:k,segmentIndex:c,partIndex:L});return _=R,n+=`Media Sequence: ${o}.${L} | Range: ${I} --> ${R} | Appended: ${k}
+`,w.syncInfo=M,M});r.set(o,new kD(C,D)),n+=`${qg(u.resolvedUri)} | Media Sequence: ${o} | Range: ${y} --> ${v} | Appended: ${b}
+`,o++,a=v}),this.end_=a,this.storage_=r,this.diagnostics_=n}calculateBaseTime_(e,t){return this.storage_.size?this.storage_.has(e)?this.storage_.get(e).segmentSyncInfo.start:t:0}isReliablePlaylist_(e,t){return e!=null&&Array.isArray(t)&&t.length}}class Wh extends Gg{constructor(e){super(),this.parent_=e}calculateBaseTime_(e,t){if(!this.storage_.size){const i=this.parent_.getSyncInfoForMediaSequence(e);return i?i.segmentSyncInfo.start:0}return super.calculateBaseTime_(e,t)}}const ID=86400,hl=[{name:"VOD",run:(s,e,t,i,r)=>t!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(s,e,t,i,r,n)=>{const a=s.getMediaSequenceSync(n);if(!a||!a.isReliable)return null;const o=a.getSyncInfoForTime(r);return o?{time:o.start,partIndex:o.partIndex,segmentIndex:o.segmentIndex}:null}},{name:"ProgramDateTime",run:(s,e,t,i,r)=>{if(!Object.keys(s.timelineToDatetimeMappings).length)return null;let n=null,a=null;const o=Nl(e);r=r||0;for(let u=0;u{let n=null,a=null;r=r||0;const o=Nl(e);for(let u=0;u=b)&&(a=b,n={time:v,segmentIndex:p.segmentIndex,partIndex:p.partIndex})}}return n}},{name:"Discontinuity",run:(s,e,t,i,r)=>{let n=null;if(r=r||0,e.discontinuityStarts&&e.discontinuityStarts.length){let a=null;for(let o=0;o=y)&&(a=y,n={time:p.time,segmentIndex:u,partIndex:null})}}}return n}},{name:"Playlist",run:(s,e,t,i,r)=>e.syncInfo?{time:e.syncInfo.time,segmentIndex:e.syncInfo.mediaSequence-e.mediaSequence,partIndex:null}:null}];class PD extends O.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new Gg,i=new Wh(t),r=new Wh(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:r},this.logger_=Ct("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,r,n){if(t!==1/0)return hl.find(({name:u})=>u==="VOD").run(this,e,t);const a=this.runStrategies_(e,t,i,r,n);if(!a.length)return null;for(const o of a){const{syncPoint:u,strategy:c}=o,{segmentIndex:p,time:y}=u;if(p<0)continue;const v=e.segments[p],b=y,C=b+v.duration;if(this.logger_(`Strategy: ${c}. Current time: ${r}. selected segment: ${p}. Time: [${b} -> ${C}]}`),r>=b&&r0&&(r.time*=-1),Math.abs(r.time+Ur({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:r.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,r,n){const a=[];for(let o=0;oID){O.log.warn(`Not saving expired segment info. Media sequence gap ${i} is too large.`);return}for(let r=i-1;r>=0;r--){const n=e.segments[r];if(n&&typeof n.start<"u"){t.syncInfo={mediaSequence:e.mediaSequence+r,time:n.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){const t=e.segments[0],i=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-i}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){const i=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),r=e.segment;i&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:r.start}));const n=r.dateTimeObject;r.discontinuity&&t&&n&&(this.timelineToDatetimeMappings[r.timeline]=-(n.getTime()/1e3))}timestampOffsetForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].time}mappingForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,i){const r=e.segment,n=e.part;let a=this.timelines[e.timeline],o,u;if(typeof e.timestampOffset=="number")a={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=a,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${a.time}] [mapping: ${a.mapping}]`)),o=e.startOfSegment,u=t.end+a.mapping;else if(a)o=t.start+a.mapping,u=t.end+a.mapping;else return!1;return n&&(n.start=o,n.end=u),(!r.start||ou){let c;o<0?c=i.start-Ur({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:n}):c=i.end+Ur({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:n}),this.discontinuities[a]={time:c,accuracy:u}}}}dispose(){this.trigger("dispose"),this.off()}}class LD extends O.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange({type:e,from:t,to:i}){return typeof t=="number"&&typeof i=="number"&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:i},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:i}){if(typeof t=="number"&&typeof i=="number"){this.lastTimelineChanges_[e]={type:e,from:t,to:i},delete this.pendingTimelineChanges_[e];const r={timelineChangeInfo:{from:t,to:i}};this.trigger({type:"timelinechange",metadata:r})}return this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const OD=Pg(Lg(function(){var s=function(){function _(){this.listeners={}}var D=_.prototype;return D.on=function(L,I){this.listeners[L]||(this.listeners[L]=[]),this.listeners[L].push(I)},D.off=function(L,I){if(!this.listeners[L])return!1;var R=this.listeners[L].indexOf(I);return this.listeners[L]=this.listeners[L].slice(0),this.listeners[L].splice(R,1),R>-1},D.trigger=function(L){var I=this.listeners[L];if(I)if(arguments.length===2)for(var R=I.length,k=0;k>7)*283)^R]=R;for(k=M=0;!L[k];k^=K||1,M=q[M]||1)for(le=M^M<<1^M<<2^M<<3^M<<4,le=le>>8^le&255^99,L[k]=le,I[le]=k,ee=V[oe=V[K=V[k]]],te=ee*16843009^oe*65537^K*257^k*16843008,z=V[le]*257^le*16843008,R=0;R<4;R++)D[R][k]=z=z<<24^z>>>8,w[R][le]=te=te<<24^te>>>8;for(R=0;R<5;R++)D[R]=D[R].slice(0),w[R]=w[R].slice(0);return _};let i=null;class r{constructor(D){i||(i=t()),this._tables=[[i[0][0].slice(),i[0][1].slice(),i[0][2].slice(),i[0][3].slice(),i[0][4].slice()],[i[1][0].slice(),i[1][1].slice(),i[1][2].slice(),i[1][3].slice(),i[1][4].slice()]];let w,L,I;const R=this._tables[0][4],k=this._tables[1],M=D.length;let V=1;if(M!==4&&M!==6&&M!==8)throw new Error("Invalid aes key size");const q=D.slice(0),K=[];for(this._key=[q,K],w=M;w<4*M+28;w++)I=q[w-1],(w%M===0||M===8&&w%M===4)&&(I=R[I>>>24]<<24^R[I>>16&255]<<16^R[I>>8&255]<<8^R[I&255],w%M===0&&(I=I<<8^I>>>24^V<<24,V=V<<1^(V>>7)*283)),q[w]=q[w-M]^I;for(L=0;w;L++,w--)I=q[L&3?w:w-4],w<=4||L<4?K[L]=I:K[L]=k[0][R[I>>>24]]^k[1][R[I>>16&255]]^k[2][R[I>>8&255]]^k[3][R[I&255]]}decrypt(D,w,L,I,R,k){const M=this._key[1];let V=D^M[0],q=I^M[1],K=L^M[2],oe=w^M[3],ee,le,z;const te=M.length/4-2;let Ke,ie=4;const Ee=this._tables[1],Gt=Ee[0],Ci=Ee[1],Ai=Ee[2],wi=Ee[3],Di=Ee[4];for(Ke=0;Ke>>24]^Ci[q>>16&255]^Ai[K>>8&255]^wi[oe&255]^M[ie],le=Gt[q>>>24]^Ci[K>>16&255]^Ai[oe>>8&255]^wi[V&255]^M[ie+1],z=Gt[K>>>24]^Ci[oe>>16&255]^Ai[V>>8&255]^wi[q&255]^M[ie+2],oe=Gt[oe>>>24]^Ci[V>>16&255]^Ai[q>>8&255]^wi[K&255]^M[ie+3],ie+=4,V=ee,q=le,K=z;for(Ke=0;Ke<4;Ke++)R[(3&-Ke)+k]=Di[V>>>24]<<24^Di[q>>16&255]<<16^Di[K>>8&255]<<8^Di[oe&255]^M[ie++],ee=V,V=q,q=K,K=oe,oe=ee}}class n extends s{constructor(){super(s),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(D){this.jobs.push(D),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const a=function(_){return _<<24|(_&65280)<<8|(_&16711680)>>8|_>>>24},o=function(_,D,w){const L=new Int32Array(_.buffer,_.byteOffset,_.byteLength>>2),I=new r(Array.prototype.slice.call(D)),R=new Uint8Array(_.byteLength),k=new Int32Array(R.buffer);let M,V,q,K,oe,ee,le,z,te;for(M=w[0],V=w[1],q=w[2],K=w[3],te=0;te{const L=_[w];v(L)?D[w]={bytes:L.buffer,byteOffset:L.byteOffset,byteLength:L.byteLength}:D[w]=L}),D};self.onmessage=function(_){const D=_.data,w=new Uint8Array(D.encrypted.bytes,D.encrypted.byteOffset,D.encrypted.byteLength),L=new Uint32Array(D.key.bytes,D.key.byteOffset,D.key.byteLength/4),I=new Uint32Array(D.iv.bytes,D.iv.byteOffset,D.iv.byteLength/4);new u(w,L,I,function(R,k){self.postMessage(C({source:D.source,decrypted:k}),[k.buffer])})}}));var RD=Ig(OD);const ND=s=>{let e=s.default?"main":"alternative";return s.characteristics&&s.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},Wg=(s,e)=>{s.abort(),s.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},Gl=(s,e)=>{e.activePlaylistLoader=s,s.load()},MD=(s,e)=>()=>{const{segmentLoaders:{[s]:t,main:i},mediaTypes:{[s]:r}}=e,n=r.activeTrack(),a=r.getActiveGroup(),o=r.activePlaylistLoader,u=r.lastGroup_;if(!(a&&u&&a.id===u.id)&&(r.lastGroup_=a,r.lastTrack_=n,Wg(t,r),!(!a||a.isMainPlaylist))){if(!a.playlistLoader){o&&i.resetEverything();return}t.resyncLoader(),Gl(a.playlistLoader,r)}},BD=(s,e)=>()=>{const{segmentLoaders:{[s]:t},mediaTypes:{[s]:i}}=e;i.lastGroup_=null,t.abort(),t.pause()},FD=(s,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[s]:i,main:r},mediaTypes:{[s]:n}}=e,a=n.activeTrack(),o=n.getActiveGroup(),u=n.activePlaylistLoader,c=n.lastTrack_;if(!(c&&a&&c.id===a.id)&&(n.lastGroup_=o,n.lastTrack_=a,Wg(i,n),!!o)){if(o.isMainPlaylist){if(!a||!c||a.id===c.id)return;const p=e.vhs.playlistController_,y=p.selectPlaylist();if(p.media()===y)return;n.logger_(`track change. Switching main audio from ${c.id} to ${a.id}`),t.pause(),r.resetEverything(),p.fastQualityChange_(y);return}if(s==="AUDIO"){if(!o.playlistLoader){r.setAudio(!0),r.resetEverything();return}i.setAudio(!0),r.setAudio(!1)}if(u===o.playlistLoader){Gl(o.playlistLoader,n);return}i.track&&i.track(a),i.resetEverything(),Gl(o.playlistLoader,n)}},Ra={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:t},excludePlaylist:i}=e,r=t.activeTrack(),n=t.activeGroup(),a=(n.filter(u=>u.default)[0]||n[0]).id,o=t.tracks[a];if(r===o){i({error:{message:"Problem encountered loading the default audio track."}});return}O.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const u in t.tracks)t.tracks[u].enabled=t.tracks[u]===o;t.onTrackChanged()},SUBTITLES:(s,e)=>()=>{const{mediaTypes:{[s]:t}}=e;O.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const i=t.activeTrack();i&&(i.mode="disabled"),t.onTrackChanged()}},Kh={AUDIO:(s,e,t)=>{if(!e)return;const{tech:i,requestOptions:r,segmentLoaders:{[s]:n}}=t;e.on("loadedmetadata",()=>{const a=e.media();n.playlist(a,r),(!i.paused()||a.endList&&i.preload()!=="none")&&n.load()}),e.on("loadedplaylist",()=>{n.playlist(e.media(),r),i.paused()||n.load()}),e.on("error",Ra[s](s,t))},SUBTITLES:(s,e,t)=>{const{tech:i,requestOptions:r,segmentLoaders:{[s]:n},mediaTypes:{[s]:a}}=t;e.on("loadedmetadata",()=>{const o=e.media();n.playlist(o,r),n.track(a.activeTrack()),(!i.paused()||o.endList&&i.preload()!=="none")&&n.load()}),e.on("loadedplaylist",()=>{n.playlist(e.media(),r),i.paused()||n.load()}),e.on("error",Ra[s](s,t))}},UD={AUDIO:(s,e)=>{const{vhs:t,sourceType:i,segmentLoaders:{[s]:r},requestOptions:n,main:{mediaGroups:a},mediaTypes:{[s]:{groups:o,tracks:u,logger_:c}},mainPlaylistLoader:p}=e,y=mn(p.main);(!a[s]||Object.keys(a[s]).length===0)&&(a[s]={main:{default:{default:!0}}},y&&(a[s].main.default.playlists=p.main.playlists));for(const v in a[s]){o[v]||(o[v]=[]);for(const b in a[s][v]){let C=a[s][v][b],_;if(y?(c(`AUDIO group '${v}' label '${b}' is a main playlist`),C.isMainPlaylist=!0,_=null):i==="vhs-json"&&C.playlists?_=new Ts(C.playlists[0],t,n):C.resolvedUri?_=new Ts(C.resolvedUri,t,n):C.playlists&&i==="dash"?_=new jl(C.playlists[0],t,n,p):_=null,C=se({id:b,playlistLoader:_},C),Kh[s](s,C.playlistLoader,e),o[v].push(C),typeof u[b]>"u"){const D=new O.AudioTrack({id:b,kind:ND(C),enabled:!1,language:C.language,default:C.default,label:b});u[b]=D}}}r.on("error",Ra[s](s,e))},SUBTITLES:(s,e)=>{const{tech:t,vhs:i,sourceType:r,segmentLoaders:{[s]:n},requestOptions:a,main:{mediaGroups:o},mediaTypes:{[s]:{groups:u,tracks:c}},mainPlaylistLoader:p}=e;for(const y in o[s]){u[y]||(u[y]=[]);for(const v in o[s][y]){if(!i.options_.useForcedSubtitles&&o[s][y][v].forced)continue;let b=o[s][y][v],C;if(r==="hls")C=new Ts(b.resolvedUri,i,a);else if(r==="dash"){if(!b.playlists.filter(D=>D.excludeUntil!==1/0).length)return;C=new jl(b.playlists[0],i,a,p)}else r==="vhs-json"&&(C=new Ts(b.playlists?b.playlists[0]:b.resolvedUri,i,a));if(b=se({id:v,playlistLoader:C},b),Kh[s](s,b.playlistLoader,e),u[y].push(b),typeof c[v]>"u"){const _=t.addRemoteTextTrack({id:v,kind:"subtitles",default:b.default&&b.autoselect,language:b.language,label:v},!1).track;c[v]=_}}}n.on("error",Ra[s](s,e))},"CLOSED-CAPTIONS":(s,e)=>{const{tech:t,main:{mediaGroups:i},mediaTypes:{[s]:{groups:r,tracks:n}}}=e;for(const a in i[s]){r[a]||(r[a]=[]);for(const o in i[s][a]){const u=i[s][a][o];if(!/^(?:CC|SERVICE)/.test(u.instreamId))continue;const c=t.options_.vhs&&t.options_.vhs.captionServices||{};let p={label:o,language:u.language,instreamId:u.instreamId,default:u.default&&u.autoselect};if(c[p.instreamId]&&(p=se(p,c[p.instreamId])),p.default===void 0&&delete p.default,r[a].push(se({id:o},u)),typeof n[o]>"u"){const y=t.addRemoteTextTrack({id:p.instreamId,kind:"captions",default:p.default,language:p.language,label:p.label},!1).track;n[o]=y}}}}},Kg=(s,e)=>{for(let t=0;tt=>{const{mainPlaylistLoader:i,mediaTypes:{[s]:{groups:r}}}=e,n=i.media();if(!n)return null;let a=null;n.attributes[s]&&(a=r[n.attributes[s]]);const o=Object.keys(r);if(!a)if(s==="AUDIO"&&o.length>1&&mn(e.main))for(let u=0;u"u"?a:t===null||!a?null:a.filter(u=>u.id===t.id)[0]||null},jD={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:{tracks:t}}}=e;for(const i in t)if(t[i].enabled)return t[i];return null},SUBTITLES:(s,e)=>()=>{const{mediaTypes:{[s]:{tracks:t}}}=e;for(const i in t)if(t[i].mode==="showing"||t[i].mode==="hidden")return t[i];return null}},qD=(s,{mediaTypes:e})=>()=>{const t=e[s].activeTrack();return t?e[s].activeGroup(t):null},HD=s=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(c=>{UD[c](c,s)});const{mediaTypes:e,mainPlaylistLoader:t,tech:i,vhs:r,segmentLoaders:{["AUDIO"]:n,main:a}}=s;["AUDIO","SUBTITLES"].forEach(c=>{e[c].activeGroup=$D(c,s),e[c].activeTrack=jD[c](c,s),e[c].onGroupChanged=MD(c,s),e[c].onGroupChanging=BD(c,s),e[c].onTrackChanged=FD(c,s),e[c].getActiveGroup=qD(c,s)});const o=e.AUDIO.activeGroup();if(o){const c=(o.filter(y=>y.default)[0]||o[0]).id;e.AUDIO.tracks[c].enabled=!0,e.AUDIO.onGroupChanged(),e.AUDIO.onTrackChanged(),e.AUDIO.getActiveGroup().playlistLoader?(a.setAudio(!1),n.setAudio(!0)):a.setAudio(!0)}t.on("mediachange",()=>{["AUDIO","SUBTITLES"].forEach(c=>e[c].onGroupChanged())}),t.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(c=>e[c].onGroupChanging())});const u=()=>{e.AUDIO.onTrackChanged(),i.trigger({type:"usage",name:"vhs-audio-change"})};i.audioTracks().addEventListener("change",u),i.remoteTextTracks().addEventListener("change",e.SUBTITLES.onTrackChanged),r.on("dispose",()=>{i.audioTracks().removeEventListener("change",u),i.remoteTextTracks().removeEventListener("change",e.SUBTITLES.onTrackChanged)}),i.clearTracks("audio");for(const c in e.AUDIO.tracks)i.audioTracks().addTrack(e.AUDIO.tracks[c])},VD=()=>{const s={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{s[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:ei,activeTrack:ei,getActiveGroup:ei,onGroupChanged:ei,onTrackChanged:ei,lastTrack_:null,logger_:Ct(`MediaGroups[${e}]`)}}),s};class Xh{constructor(){this.priority_=[],this.pathwayClones_=new Map}set version(e){e===1&&(this.version_=e)}set ttl(e){this.ttl_=e||300}set reloadUri(e){e&&(this.reloadUri_=lt(this.reloadUri_,e))}set priority(e){e&&e.length&&(this.priority_=e)}set pathwayClones(e){e&&e.length&&(this.pathwayClones_=new Map(e.map(t=>[t.ID,t])))}get version(){return this.version_}get ttl(){return this.ttl_}get reloadUri(){return this.reloadUri_}get priority(){return this.priority_}get pathwayClones(){return this.pathwayClones_}}class zD extends O.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new Xh,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=Ct("Content Steering"),this.xhr_=e,this.getBandwidth_=t}assignTagProperties(e,t){this.manifestType_=t.serverUri?"HLS":"DASH";const i=t.serverUri||t.serverURL;if(!i){this.logger_(`steering manifest URL is ${i}, cannot request steering manifest.`),this.trigger("error");return}if(i.startsWith("data:")){this.decodeDataUriManifest_(i.substring(i.indexOf(",")+1));return}this.steeringManifest.reloadUri=lt(e,i),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering")}requestSteeringManifest(e){const t=this.steeringManifest.reloadUri;if(!t)return;const i=e?t:this.getRequestURI(t);if(!i){this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),this.dispose();return}const r={contentSteeringInfo:{uri:i}};this.trigger({type:"contentsteeringloadstart",metadata:r}),this.request_=this.xhr_({uri:i,requestType:"content-steering-manifest"},(n,a)=>{if(n){if(a.status===410){this.logger_(`manifest request 410 ${n}.`),this.logger_(`There will be no more content steering requests to ${i} this session.`),this.excludedSteeringManifestURLs.add(i);return}if(a.status===429){const c=a.responseHeaders["retry-after"];this.logger_(`manifest request 429 ${n}.`),this.logger_(`content steering will retry in ${c} seconds.`),this.startTTLTimeout_(parseInt(c,10));return}this.logger_(`manifest failed to load ${n}.`),this.startTTLTimeout_();return}this.trigger({type:"contentsteeringloadcomplete",metadata:r});let o;try{o=JSON.parse(this.request_.responseText)}catch(c){const p={errorType:O.Error.StreamingContentSteeringParserError,error:c};this.trigger({type:"error",metadata:p})}this.assignSteeringProperties_(o);const u={contentSteeringInfo:r.contentSteeringInfo,contentSteeringManifest:{version:this.steeringManifest.version,reloadUri:this.steeringManifest.reloadUri,priority:this.steeringManifest.priority}};this.trigger({type:"contentsteeringparsed",metadata:u}),this.startTTLTimeout_()})}setProxyServerUrl_(e){const t=new E.URL(e),i=new E.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(E.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new E.URL(e),i=this.getPathway(),r=this.getBandwidth_();if(i){const n=`_${this.manifestType_}_pathway`;t.searchParams.set(n,i)}if(r){const n=`_${this.manifestType_}_throughput`;t.searchParams.set(n,r)}return t.toString()}assignSteeringProperties_(e){if(this.steeringManifest.version=e.VERSION,!this.steeringManifest.version){this.logger_(`manifest version is ${e.VERSION}, which is not supported.`),this.trigger("error");return}this.steeringManifest.ttl=e.TTL,this.steeringManifest.reloadUri=e["RELOAD-URI"],this.steeringManifest.priority=e["PATHWAY-PRIORITY"]||e["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=e["PATHWAY-CLONES"],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_("There are no available pathways for content steering. Ending content steering."),this.trigger("error"),this.dispose());const i=(r=>{for(const n of r)if(this.availablePathways_.has(n))return n;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==i&&(this.currentPathway=i,this.trigger("content-steering"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(e){if(!e)return null;const t=r=>this.excludedSteeringManifestURLs.has(r);if(this.proxyServerUrl_){const r=this.setProxyServerUrl_(e);if(!t(r))return r}const i=this.setSteeringParams_(e);return t(i)?null:i}startTTLTimeout_(e=this.steeringManifest.ttl){const t=e*1e3;this.ttlTimeout_=E.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){E.clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off("content-steering"),this.off("error"),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new Xh}addAvailablePathway(e){e&&this.availablePathways_.add(e)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(e){return this.availablePathways_.delete(e)}didDASHTagChange(e,t){return!t&&this.steeringManifest.reloadUri||t&&(lt(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}}const GD=10;let Xt;const WD=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],KD=function(s){return this.audioSegmentLoader_[s]+this.mainSegmentLoader_[s]},XD=function({currentPlaylist:s,buffered:e,currentTime:t,nextPlaylist:i,bufferLowWaterLine:r,bufferHighWaterLine:n,duration:a,bufferBasedABR:o,log:u}){if(!i)return O.log.warn("We received no playlist to switch to. Please check your stream."),!1;const c=`allowing switch ${s&&s.id||"null"} -> ${i.id}`;if(!s)return u(`${c} as current playlist is not set`),!0;if(i.id===s.id)return!1;const p=!!vs(e,t).length;if(!s.endList)return!p&&typeof s.partTargetDuration=="number"?(u(`not ${c} as current playlist is live llhls, but currentTime isn't in buffered.`),!1):(u(`${c} as current playlist is live`),!0);const y=Qu(e,t),v=o?$e.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:$e.MAX_BUFFER_LOW_WATER_LINE;if(aC)&&y>=r){let _=`${c} as forwardBuffer >= bufferLowWaterLine (${y} >= ${r})`;return o&&(_+=` and next bandwidth > current bandwidth (${b} > ${C})`),u(_),!0}return u(`not ${c} as no switching criteria met`),!1};class YD extends O.EventTarget{constructor(e){super();const{src:t,withCredentials:i,tech:r,bandwidth:n,externVhs:a,useCueTags:o,playlistExclusionDuration:u,enableLowInitialPlaylist:c,sourceType:p,cacheEncryptionKeys:y,bufferBasedABR:v,leastPixelDiffSelector:b,captionServices:C,experimentalUseMMS:_}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:D}=e;(D===null||typeof D>"u")&&(D=1/0),Xt=a,this.bufferBasedABR=!!v,this.leastPixelDiffSelector=!!b,this.withCredentials=i,this.tech_=r,this.vhs_=r.vhs,this.player_=e.player_,this.sourceType_=p,this.useCueTags_=o,this.playlistExclusionDuration=u,this.maxPlaylistRetries=D,this.enableLowInitialPlaylist=c,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:D,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=VD(),_&&E.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new E.ManagedMediaSource,O.log("Using ManagedMediaSource")):E.MediaSource&&(this.mediaSource=new E.MediaSource),this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.seekable_=Ve(),this.hasPlayed_=!1,this.syncController_=new PD(e),this.segmentMetadataTrack_=r.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.decrypter_=new RD,this.sourceUpdater_=new zg(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new LD,this.keyStatusMap_=new Map;const w={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:C,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:n,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:y,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_=this.sourceType_==="dash"?new jl(t,this.vhs_,se(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new Ts(t,this.vhs_,se(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new Vl(se(w,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new Vl(se(w,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new AD(se(w,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((R,k)=>{function M(){r.off("vttjserror",V),R()}function V(){r.off("vttjsloaded",M),k()}r.one("vttjsloaded",M),r.one("vttjserror",V),r.addWebVttScript_()})}),e);const L=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new zD(this.vhs_.xhr,L),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_())),WD.forEach(R=>{this[R+"_"]=KD.bind(this,R)}),this.logger_=Ct("pc"),this.triggeredFmp4Usage=!1,this.tech_.preload()==="none"?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;const I=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(I,()=>{const R=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-R,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return e===-1||t===-1?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e="abr"){const t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,i){const r=this.media(),n=r&&(r.id||r.uri),a=e&&(e.id||e.uri);if(n&&n!==a){this.logger_(`switch media ${n} -> ${a} from ${t}`);const o={renditionInfo:{id:a,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:"renditionselected",metadata:o}),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,i)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{const t=this.mediaTypes_[e],i=t?t.activeGroup():null,r=this.contentSteeringController_.getPathway();if(i&&r){const a=(i.length?i[0].playlists:i.playlists).filter(o=>o.attributes.serviceLocation===r);a.length&&this.mediaTypes_[e].activePlaylistLoader.media(a[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=E.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(E.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const e=this.main(),t=e&&e.playlists||[];if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return t;const i=e.mediaGroups.AUDIO,r=Object.keys(i);let n;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)n=this.mediaTypes_.AUDIO.activeTrack();else{const o=i.main||r.length&&i[r[0]];for(const u in o)if(o[u].default){n={label:u};break}}if(!n)return t;const a=[];for(const o in i)if(i[o][n.label]){const u=i[o][n.label];if(u.playlists&&u.playlists.length)a.push.apply(a,u.playlists);else if(u.uri)a.push(u);else if(e.playlists.length)for(let c=0;c{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;Ml(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=i,t.endList&&this.tech_.preload()!=="none"&&(this.mainSegmentLoader_.playlist(t,this.requestOptions_),this.mainSegmentLoader_.load()),HD({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),t),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger("selectedinitialmedia"):this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",()=>{this.trigger("selectedinitialmedia")})}),this.mainPlaylistLoader_.on("loadedplaylist",()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let t=this.mainPlaylistLoader_.media();if(!t){this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_();let i;if(this.enableLowInitialPlaylist&&(i=this.selectInitialPlaylist()),i||(i=this.selectPlaylist()),!i||!this.shouldSwitchToMedia_(i)||(this.initialMedia_=i,this.switchMedia_(this.initialMedia_,"initial"),!(this.sourceType_==="vhs-json"&&this.initialMedia_.segments)))return;t=this.initialMedia_}this.handleUpdatedMediaPlaylist(t)}),this.mainPlaylistLoader_.on("error",()=>{const t=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:t.playlist,error:t})}),this.mainPlaylistLoader_.on("mediachanging",()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()}),this.mainPlaylistLoader_.on("mediachange",()=>{const t=this.mainPlaylistLoader_.media(),i=t.targetDuration*1.5*1e3;Ml(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=i,this.sourceType_==="dash"&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(t,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})}),this.mainPlaylistLoader_.on("playlistunchanged",()=>{const t=this.mainPlaylistLoader_.media();if(t.lastExcludeReason_==="playlist-unchanged")return;this.stuckAtPlaylistEnd_(t)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))}),this.mainPlaylistLoader_.on("renditiondisabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})}),this.mainPlaylistLoader_.on("renditionenabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-enabled"})}),["manifestrequeststart","manifestrequestcomplete","manifestparsestart","manifestparsecomplete","playlistrequeststart","playlistrequestcomplete","playlistparsestart","playlistparsecomplete","renditiondisabled","renditionenabled"].forEach(t=>{this.mainPlaylistLoader_.on(t,i=>{this.player_.trigger(xe({},i))})})}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!e.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){const i=e.mediaGroups||{};let r=!0;const n=Object.keys(i.AUDIO);for(const a in i.AUDIO)for(const o in i.AUDIO[a])i.AUDIO[a][o].uri||(r=!1);r&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(i.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),Xt.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),n.length&&Object.keys(i.AUDIO[n[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(e){const t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,i=this.tech_.currentTime(),r=this.bufferLowWaterLine(),n=this.bufferHighWaterLine(),a=this.tech_.buffered();return XD({buffered:a,currentTime:i,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:r,bufferHighWaterLine:n,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")}),this.mainSegmentLoader_.on("timeout",()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()}),this.bufferBasedABR||this.mainSegmentLoader_.on("progress",()=>{this.trigger("progress")}),this.mainSegmentLoader_.on("error",()=>{const i=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:i.playlist,error:i})}),this.mainSegmentLoader_.on("appenderror",()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.mainSegmentLoader_.on("timestampoffset",()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})}),this.audioSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.audioSegmentLoader_.on("appenderror",()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("ended",()=>{this.logger_("main segment loader ended"),this.onEndOfStream()}),this.timelineChangeController_.on("audioTimelineBehind",()=>{const i=this.audioSegmentLoader_.pendingSegment_;if(!i||!i.segment||!i.segment.syncInfo)return;const r=i.segment.syncInfo.end+.01;this.tech_.setCurrentTime(r)}),this.mainSegmentLoader_.on("earlyabort",i=>{this.bufferBasedABR||(this.delegateLoaders_("all",["abort"]),this.excludePlaylist({error:{message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},playlistExclusionDuration:GD}))});const e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const i=this.getCodecsOrExclude_();i&&this.sourceUpdater_.addOrChangeSourceBuffers(i)};this.mainSegmentLoader_.on("trackinfo",e),this.audioSegmentLoader_.on("trackinfo",e),this.mainSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("ended",()=>{this.logger_("audioSegmentLoader ended"),this.onEndOfStream()}),["segmentselected","segmentloadstart","segmentloaded","segmentkeyloadstart","segmentkeyloadcomplete","segmentdecryptionstart","segmentdecryptioncomplete","segmenttransmuxingstart","segmenttransmuxingcomplete","segmenttransmuxingtrackinfoavailable","segmenttransmuxingtiminginfoavailable","segmentappendstart","appendsdone","bandwidthupdated","timelinechange","codecschange"].forEach(i=>{this.mainSegmentLoader_.on(i,r=>{this.player_.trigger(xe({},r))}),this.audioSegmentLoader_.on(i,r=>{this.player_.trigger(xe({},r))}),this.subtitleSegmentLoader_.on(i,r=>{this.player_.trigger(xe({},r))})})}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}fastQualityChange_(e=this.selectPlaylist()){if(e&&e===this.mainPlaylistLoader_.media()){this.logger_("skipping fastQualityChange because new media is same as old");return}this.switchMedia_(e,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(()=>{this.mainSegmentLoader_.load()})}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();const e=this.tech_.seekable();if(this.tech_.duration()===1/0&&this.tech_.currentTime(){})}this.trigger("sourceopen")}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;const e=this.inbandTextTracks_.metadataTrack_.cues;if(!e||!e.length)return;const t=this.duration();e[e.length-1].endTime=isNaN(t)||Math.abs(t)===1/0?Number.MAX_VALUE:t}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let e=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){const t=this.mainSegmentLoader_.getCurrentMediaInfo_();!t||t.hasVideo?e=e&&this.audioSegmentLoader_.ended_:e=this.audioSegmentLoader_.ended_}e&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(e){if(!this.seekable().length)return!1;const i=this.syncController_.getExpiredTime(e,this.duration());if(i===null)return!1;const r=Xt.Playlist.playlistEnd(e,i),n=this.tech_.currentTime(),a=this.tech_.buffered();if(!a.length)return r-n<=Ft;const o=a.end(a.length-1);return o-n<=Ft&&r-o<=Ft}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:i}){if(e=e||this.mainPlaylistLoader_.media(),i=i||t.playlistExclusionDuration||this.playlistExclusionDuration,!e){this.error=t,this.mediaSource.readyState!=="open"?this.trigger("error"):this.sourceUpdater_.endOfStream("network");return}e.playlistErrors_++;const r=this.mainPlaylistLoader_.main.playlists,n=r.filter(co),a=n.length===1&&n[0]===e;if(r.length===1&&i!==1/0)return O.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(a);if(a){if(this.main().contentSteering){const C=this.pathwayAttribute_(e),_=this.contentSteeringController_.steeringManifest.ttl*1e3;this.contentSteeringController_.excludePathway(C),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(C)},_);return}let b=!1;r.forEach(C=>{if(C===e)return;const _=C.excludeUntil;typeof _<"u"&&_!==1/0&&(b=!0,delete C.excludeUntil)}),b&&(O.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),this.tech_.trigger("retryplaylist"))}let o;e.playlistErrors_>this.maxPlaylistRetries?o=1/0:o=Date.now()+i*1e3,e.excludeUntil=o,t.reason&&(e.lastExcludeReason_=t.reason),this.tech_.trigger("excludeplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});const u=this.selectPlaylist();if(!u){this.error="Playback cannot continue. No available working or supported playlists.",this.trigger("error");return}const c=t.internal?this.logger_:O.log.warn,p=t.message?" "+t.message:"";c(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${p} Switching to playlist ${u.id}.`),u.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),u.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);const y=u.targetDuration/2*1e3||5*1e3,v=typeof u.lastRequest=="number"&&Date.now()-u.lastRequest<=y;return this.switchMedia_(u,"exclude",a||v)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(e,t){const i=[],r=e==="all";(r||e==="main")&&i.push(this.mainPlaylistLoader_);const n=[];(r||e==="audio")&&n.push("AUDIO"),(r||e==="subtitle")&&(n.push("CLOSED-CAPTIONS"),n.push("SUBTITLES")),n.forEach(a=>{const o=this.mediaTypes_[a]&&this.mediaTypes_[a].activePlaylistLoader;o&&i.push(o)}),["main","audio","subtitle"].forEach(a=>{const o=this[`${a}SegmentLoader_`];o&&(e===a||e==="all")&&i.push(o)}),i.forEach(a=>t.forEach(o=>{typeof a[o]=="function"&&a[o]()}))}setCurrentTime(e){const t=vs(this.tech_.buffered(),e);if(!(this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media())||!this.mainPlaylistLoader_.media().segments)return 0;if(t&&t.length)return e;this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}duration(){if(!this.mainPlaylistLoader_)return 0;const e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:Xt.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}onSyncInfoUpdate_(){let e;if(!this.mainPlaylistLoader_)return;let t=this.mainPlaylistLoader_.media();if(!t)return;let i=this.syncController_.getExpiredTime(t,this.duration());if(i===null)return;const r=this.mainPlaylistLoader_.main,n=Xt.Playlist.seekable(t,i,Xt.Playlist.liveEdgeDelay(r,t));if(n.length===0||this.mediaTypes_.AUDIO.activePlaylistLoader&&(t=this.mediaTypes_.AUDIO.activePlaylistLoader.media(),i=this.syncController_.getExpiredTime(t,this.duration()),i===null||(e=Xt.Playlist.seekable(t,i,Xt.Playlist.liveEdgeDelay(r,t)),e.length===0)))return;let a,o;if(this.seekable_&&this.seekable_.length&&(a=this.seekable_.end(0),o=this.seekable_.start(0)),e?e.start(0)>n.end(0)||n.start(0)>e.end(0)?this.seekable_=n:this.seekable_=Ve([[e.start(0)>n.start(0)?e.start(0):n.start(0),e.end(0)0&&(i=Math.max(i,t.end(t.length-1))),this.mediaSource.duration!==i&&this.sourceUpdater_.setDuration(i)}dispose(){this.trigger("dispose"),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach(e=>{const t=this.mediaTypes_[e].groups;for(const i in t)t[i].forEach(r=>{r.playlistLoader&&r.playlistLoader.dispose()})}),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){const e=!!this.mediaTypes_.AUDIO.activePlaylistLoader,t=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),i=e?!!this.audioSegmentLoader_.getCurrentMediaInfo_():!0;return!(!t||!i)}getCodecsOrExclude_(){const e={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},t=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();e.video=e.main;const i=jr(this.main(),t),r={},n=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(r.video=i.video||e.main.videoCodec||px),e.main.isMuxed&&(r.video+=`,${i.audio||e.main.audioCodec||Id}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||n)&&(r.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||Id,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!r.audio&&!r.video){this.excludePlaylist({playlistToExclude:t,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});return}const a=(c,p)=>c?Nr(p):Xo(p),o={};let u;if(["video","audio"].forEach(function(c){if(r.hasOwnProperty(c)&&!a(e[c].isFmp4,r[c])){const p=e[c].isFmp4?"browser":"muxer";o[p]=o[p]||[],o[p].push(r[c]),c==="audio"&&(u=p)}}),n&&u&&t.attributes.AUDIO){const c=t.attributes.AUDIO;this.main().playlists.forEach(p=>{(p.attributes&&p.attributes.AUDIO)===c&&p!==t&&(p.excludeUntil=1/0)}),this.logger_(`excluding audio group ${c} as ${u} does not support codec(s): "${r.audio}"`)}if(Object.keys(o).length){const c=Object.keys(o).reduce((p,y)=>(p&&(p+=", "),p+=`${y} does not support codec(s): "${o[y].join(",")}"`,p),"")+".";this.excludePlaylist({playlistToExclude:t,error:{internal:!0,message:c},playlistExclusionDuration:1/0});return}if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const c=[];if(["video","audio"].forEach(p=>{const y=(Ot(this.sourceUpdater_.codecs[p]||"")[0]||{}).type,v=(Ot(r[p]||"")[0]||{}).type;y&&v&&y.toLowerCase()!==v.toLowerCase()&&c.push(`"${this.sourceUpdater_.codecs[p]}" -> "${r[p]}"`)}),c.length){this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${c.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0});return}}return r}tryToCreateSourceBuffers_(){if(this.mediaSource.readyState!=="open"||this.sourceUpdater_.hasCreatedSourceBuffers()||!this.areMediaTypesKnown_())return;const e=this.getCodecsOrExclude_();if(!e)return;this.sourceUpdater_.createSourceBuffers(e);const t=[e.video,e.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(t)}excludeUnsupportedVariants_(){const e=this.main().playlists,t=[];Object.keys(e).forEach(i=>{const r=e[i];if(t.indexOf(r.id)!==-1)return;t.push(r.id);const n=jr(this.main,r),a=[];n.audio&&!Xo(n.audio)&&!Nr(n.audio)&&a.push(`audio codec ${n.audio}`),n.video&&!Xo(n.video)&&!Nr(n.video)&&a.push(`video codec ${n.video}`),n.text&&n.text==="stpp.ttml.im1t"&&a.push(`text codec ${n.text}`),a.length&&(r.excludeUntil=1/0,this.logger_(`excluding ${r.id} for unsupported: ${a.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,r=La(Ot(e)),n=Mh(r),a=r.video&&Ot(r.video)[0]||null,o=r.audio&&Ot(r.audio)[0]||null;Object.keys(i).forEach(u=>{const c=i[u];if(t.indexOf(c.id)!==-1||c.excludeUntil===1/0)return;t.push(c.id);const p=[],y=jr(this.mainPlaylistLoader_.main,c),v=Mh(y);if(!(!y.audio&&!y.video)){if(v!==n&&p.push(`codec count "${v}" !== "${n}"`),!this.sourceUpdater_.canChangeType()){const b=y.video&&Ot(y.video)[0]||null,C=y.audio&&Ot(y.audio)[0]||null;b&&a&&b.type.toLowerCase()!==a.type.toLowerCase()&&p.push(`video codec "${b.type}" !== "${a.type}"`),C&&o&&C.type.toLowerCase()!==o.type.toLowerCase()&&p.push(`audio codec "${C.type}" !== "${o.type}"`)}p.length&&(c.excludeUntil=1/0,this.logger_(`excluding ${c.id}: ${p.join(" && ")}`))}})}updateAdCues_(e){let t=0;const i=this.seekable();i.length&&(t=i.start(0)),DD(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=$e.GOAL_BUFFER_LENGTH,i=$e.GOAL_BUFFER_LENGTH_RATE,r=Math.max(t,$e.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,r)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=$e.BUFFER_LOW_WATER_LINE,i=$e.BUFFER_LOW_WATER_LINE_RATE,r=Math.max(t,$e.MAX_BUFFER_LOW_WATER_LINE),n=Math.max(t,$e.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?n:r)}bufferHighWaterLine(){return $e.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){Uh(this.inbandTextTracks_,"com.apple.streaming",this.tech_),aD({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const r=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();Uh(this.inbandTextTracks_,e,this.tech_),sD({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:r,videoDuration:i})}pathwayAttribute_(e){return e.attributes["PATHWAY-ID"]||e.attributes.serviceLocation}initContentSteeringController_(){const e=this.main();if(e.contentSteering){for(const t of e.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(t));if(this.contentSteeringController_.assignTagProperties(e.uri,e.contentSteering),this.contentSteeringController_.queryBeforeStart){this.contentSteeringController_.requestSteeringManifest(!0);return}this.tech_.one("canplay",()=>{this.contentSteeringController_.requestSteeringManifest()})}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on("content-steering",this.excludeThenChangePathway_.bind(this)),["contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach(t=>{this.contentSteeringController_.on(t,i=>{this.trigger(xe({},i))})}),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const t=this.main();(this.contentSteeringController_.didDASHTagChange(t.uri,t.contentSteering)||(()=>{const n=this.contentSteeringController_.getAvailablePathways(),a=[];for(const o of t.playlists){const u=o.attributes.serviceLocation;if(u&&(a.push(u),!n.has(u)))return!0}return!!(!a.length&&n.size)})())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){const e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();const i=this.main().playlists,r=new Set;let n=!1;Object.keys(i).forEach(a=>{const o=i[a],u=this.pathwayAttribute_(o),c=u&&e!==u;o.excludeUntil===1/0&&o.lastExcludeReason_==="content-steering"&&!c&&(delete o.excludeUntil,delete o.lastExcludeReason_,n=!0);const y=!o.excludeUntil&&o.excludeUntil!==1/0;!r.has(o.id)&&c&&y&&(r.add(o.id),o.excludeUntil=1/0,o.lastExcludeReason_="content-steering",this.logger_(`excluding ${o.id} for ${o.lastExcludeReason_}`))}),this.contentSteeringController_.manifestType_==="DASH"&&Object.keys(this.mediaTypes_).forEach(a=>{const o=this.mediaTypes_[a];if(o.activePlaylistLoader){const u=o.activePlaylistLoader.media_;u&&u.attributes.serviceLocation!==e&&(n=!0)}}),n&&this.changeSegmentPathway_()}handlePathwayClones_(){const t=this.main().playlists,i=this.contentSteeringController_.currentPathwayClones,r=this.contentSteeringController_.nextPathwayClones;if(i&&i.size||r&&r.size){for(const[a,o]of i.entries())r.get(a)||(this.mainPlaylistLoader_.updateOrDeleteClone(o),this.contentSteeringController_.excludePathway(a));for(const[a,o]of r.entries()){const u=i.get(a);if(!u){t.filter(p=>p.attributes["PATHWAY-ID"]===o["BASE-ID"]).forEach(p=>{this.mainPlaylistLoader_.addClonePathway(o,p)}),this.contentSteeringController_.addAvailablePathway(a);continue}this.equalPathwayClones_(u,o)||(this.mainPlaylistLoader_.updateOrDeleteClone(o,!0),this.contentSteeringController_.addAvailablePathway(a))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...r])))}}equalPathwayClones_(e,t){if(e["BASE-ID"]!==t["BASE-ID"]||e.ID!==t.ID||e["URI-REPLACEMENT"].HOST!==t["URI-REPLACEMENT"].HOST)return!1;const i=e["URI-REPLACEMENT"].PARAMS,r=t["URI-REPLACEMENT"].PARAMS;for(const n in i)if(i[n]!==r[n])return!1;for(const n in r)if(i[n]!==r[n])return!1;return!0}changeSegmentPathway_(){const e=this.selectPlaylist();this.pauseLoading(),this.contentSteeringController_.manifestType_==="DASH"&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0;const t="non-usable";this.mainPlaylistLoader_.main.playlists.forEach(i=>{const r=this.mainPlaylistLoader_.getKeyIdSet(i);!r||!r.size||r.forEach(n=>{const a="usable",o=this.keyStatusMap_.has(n)&&this.keyStatusMap_.get(n)===a,u=i.lastExcludeReason_===t&&i.excludeUntil===1/0;o?o&&u&&(delete i.excludeUntil,delete i.lastExcludeReason_,this.logger_(`enabling playlist ${i.id} because key ID ${n} is ${a}`)):(i.excludeUntil!==1/0&&i.lastExcludeReason_!==t&&(i.excludeUntil=1/0,i.lastExcludeReason_=t,this.logger_(`excluding playlist ${i.id} because the key ID ${n} doesn't exist in the keyStatusMap or is not ${a}`)),e++)})}),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(i=>{const r=i&&i.attributes&&i.attributes.RESOLUTION&&i.attributes.RESOLUTION.height<720,n=i.excludeUntil===1/0&&i.lastExcludeReason_===t;r&&n&&(delete i.excludeUntil,O.log.warn(`enabling non-HD playlist ${i.id} because all playlists were excluded due to ${t} key IDs`))})}addKeyStatus_(e,t){const n=(typeof e=="string"?e:ED(e)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${t}' with key ID ${n} added to the keyStatusMap`),this.keyStatusMap_.set(n,t)}updatePlaylistByKeyStatus(e,t){this.addKeyStatus_(e,t),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}}const QD=(s,e,t)=>i=>{const r=s.main.playlists[e],n=Zu(r),a=co(r);if(typeof i>"u")return a;i?delete r.disabled:r.disabled=!0;const o={renditionInfo:{id:e,bandwidth:r.attributes.BANDWIDTH,resolution:r.attributes.RESOLUTION,codecs:r.attributes.CODECS},cause:"fast-quality"};return i!==a&&!n&&(t(r),i?s.trigger({type:"renditionenabled",metadata:o}):s.trigger({type:"renditiondisabled",metadata:o})),i};class JD{constructor(e,t,i){const{playlistController_:r}=e,n=r.fastQualityChange_.bind(r);if(t.attributes){const a=t.attributes.RESOLUTION;this.width=a&&a.width,this.height=a&&a.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=jr(r.main(),t),this.playlist=t,this.id=i,this.enabled=QD(e.playlists,t.id,n)}}const ZD=function(s){s.representations=()=>{const e=s.playlistController_.main(),t=mn(e)?s.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(i=>!Zu(i)).map((i,r)=>new JD(s,i,i.id)):[]}},Yh=["seeking","seeked","pause","playing","error"];class ek extends O.EventTarget{constructor(e){super(),this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.playedRanges_=[],this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=Ct("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),r=()=>this.techWaiting_(),n=()=>this.resetTimeUpdate_(),a=this.playlistController_,o=["main","subtitle","audio"],u={};o.forEach(p=>{u[p]={reset:()=>this.resetSegmentDownloads_(p),updateend:()=>this.checkSegmentDownloads_(p)},a[`${p}SegmentLoader_`].on("appendsdone",u[p].updateend),a[`${p}SegmentLoader_`].on("playlistupdate",u[p].reset),this.tech_.on(["seeked","seeking"],u[p].reset)});const c=p=>{["main","audio"].forEach(y=>{a[`${y}SegmentLoader_`][p]("appended",this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),c("off"))},this.clearSeekingAppendCheck_=()=>c("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),c("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",r),this.tech_.on(Yh,n),this.tech_.on("canplay",i),this.tech_.one("play",t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",r),this.tech_.off(Yh,n),this.tech_.off("canplay",i),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),o.forEach(p=>{a[`${p}SegmentLoader_`].off("appendsdone",u[p].updateend),a[`${p}SegmentLoader_`].off("playlistupdate",u[p].reset),this.tech_.off(["seeked","seeking"],u[p].reset)}),this.checkCurrentTimeTimeout_&&E.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&E.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=E.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(e){const t=this.playlistController_[`${e}SegmentLoader_`];this[`${e}StalledDownloads_`]>0&&this.logger_(`resetting possible stalled download count for ${e} loader`),this[`${e}StalledDownloads_`]=0,this[`${e}Buffered_`]=t.buffered_()}checkSegmentDownloads_(e){const t=this.playlistController_,i=t[`${e}SegmentLoader_`],r=i.buffered_(),n=$A(this[`${e}Buffered_`],r);if(this[`${e}Buffered_`]=r,n){const a={bufferedRanges:r};t.trigger({type:"bufferedrangeschanged",metadata:a}),this.resetSegmentDownloads_(e);return}this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:i.playlist_&&i.playlist_.id,buffered:ji(r)}),!(this[`${e}StalledDownloads_`]<10)&&(this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:"usage",name:`vhs-${e}-download-exclusion`}),e!=="subtitle"&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0}))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;const e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+Ft>=t.end(t.length-1)))return this.techWaiting_();if(this.consecutiveUpdates>=5&&e===this.lastRecordedTime)this.consecutiveUpdates++,this.waiting_();else if(e===this.lastRecordedTime)this.consecutiveUpdates++;else{this.playedRanges_.push(Ve([this.lastRecordedTime,e]));const i={playedRanges:this.playedRanges_};this.playlistController_.trigger({type:"playedrangeschanged",metadata:i}),this.consecutiveUpdates=0,this.lastRecordedTime=e}}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;const t=this.seekable(),i=this.tech_.currentTime(),r=this.afterSeekableWindow_(t,i,this.media(),this.allowSeeksWithinUnsafeLiveWindow);let n;if(r&&(n=t.end(t.length-1)),this.beforeSeekableWindow_(t,i)){const C=t.start(0);n=C+(C===t.end(0)?0:Ft)}if(typeof n<"u")return this.logger_(`Trying to seek outside of seekable at time ${i} with seekable range ${ag(t)}. Seeking to ${n}.`),this.tech_.setCurrentTime(n),!0;const a=this.playlistController_.sourceUpdater_,o=this.tech_.buffered(),u=a.audioBuffer?a.audioBuffered():null,c=a.videoBuffer?a.videoBuffered():null,p=this.media(),y=p.partTargetDuration?p.partTargetDuration:(p.targetDuration-Bt)*2,v=[u,c];for(let C=0;C ${i.end(0)}]. Attempting to resume playback by seeking to the current time.`),this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"});return}}techWaiting_(){const e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){const o=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${o}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(o),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}const i=this.tech_.vhs.playlistController_.sourceUpdater_,r=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:i.audioBuffered(),videoBuffered:i.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;const a=Kn(r,t);return a.length>0?(this.logger_(`Stopped at ${t} and seeking to ${a.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0):!1}afterSeekableWindow_(e,t,i,r=!1){if(!e.length)return!1;let n=e.end(e.length-1)+Ft;const a=!i.endList,o=typeof i.partTargetDuration=="number";return a&&(o||r)&&(n=e.end(e.length-1)+i.targetDuration*3),t>n}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t2)return{start:n,end:a}}return null}}const tk={errorInterval:30,getSource(s){const t=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return s(t)}},Xg=function(s,e){let t=0,i=0;const r=se(tk,e);s.ready(()=>{s.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const n=function(){i&&s.currentTime(i)},a=function(p){p!=null&&(i=s.duration()!==1/0&&s.currentTime()||0,s.one("loadedmetadata",n),s.src(p),s.trigger({type:"usage",name:"vhs-error-reload"}),s.play())},o=function(){if(Date.now()-t{Object.defineProperty(ve,s,{get(){return O.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),$e[s]},set(e){if(O.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),typeof e!="number"||e<0){O.log.warn(`value of Vhs.${s} must be greater than or equal to 0`);return}$e[s]=e}})});const Qg="videojs-vhs",Jg=function(s,e){const t=e.media();let i=-1;for(let r=0;r{s.addQualityLevel(t)}),Jg(s,e.playlists)};ve.canPlaySource=function(){return O.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const lk=(s,e,t)=>{if(!s)return s;let i={};e&&e.attributes&&e.attributes.CODECS&&(i=La(Ot(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(i.audio=t.attributes.CODECS);const r=Ls(i.video),n=Ls(i.audio),a={};for(const o in s)a[o]={},n&&(a[o].audioContentType=n),r&&(a[o].videoContentType=r),e.contentProtection&&e.contentProtection[o]&&e.contentProtection[o].pssh&&(a[o].pssh=e.contentProtection[o].pssh),typeof s[o]=="string"&&(a[o].url=s[o]);return se(s,a)},uk=(s,e)=>s.reduce((t,i)=>{if(!i.contentProtection)return t;const r=e.reduce((n,a)=>{const o=i.contentProtection[a];return o&&o.pssh&&(n[a]={pssh:o.pssh}),n},{});return Object.keys(r).length&&t.push(r),t},[]),ck=({player:s,sourceKeySystems:e,audioMedia:t,mainPlaylists:i})=>{if(!s.eme.initializeMediaKeys)return Promise.resolve();const r=t?i.concat([t]):i,n=uk(r,Object.keys(e)),a=[],o=[];return n.forEach(u=>{o.push(new Promise((c,p)=>{s.tech_.one("keysessioncreated",c)})),a.push(new Promise((c,p)=>{s.eme.initializeMediaKeys({keySystems:u},y=>{if(y){p(y);return}c()})}))}),Promise.race([Promise.all(a),Promise.race(o)])},dk=({player:s,sourceKeySystems:e,media:t,audioMedia:i})=>{const r=lk(e,t,i);return r?(s.currentSource().keySystems=r,r&&!s.eme?(O.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0):!1},Zg=()=>{if(!E.localStorage)return null;const s=E.localStorage.getItem(Qg);if(!s)return null;try{return JSON.parse(s)}catch{return null}},hk=s=>{if(!E.localStorage)return!1;let e=Zg();e=e?se(e,s):s;try{E.localStorage.setItem(Qg,JSON.stringify(e))}catch{return!1}return e},fk=s=>s.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(s.substring(s.indexOf(",")+1)):s,e0=(s,e)=>{s._requestCallbackSet||(s._requestCallbackSet=new Set),s._requestCallbackSet.add(e)},t0=(s,e)=>{s._responseCallbackSet||(s._responseCallbackSet=new Set),s._responseCallbackSet.add(e)},i0=(s,e)=>{s._requestCallbackSet&&(s._requestCallbackSet.delete(e),s._requestCallbackSet.size||delete s._requestCallbackSet)},s0=(s,e)=>{s._responseCallbackSet&&(s._responseCallbackSet.delete(e),s._responseCallbackSet.size||delete s._responseCallbackSet)};ve.supportsNativeHls=function(){if(!$||!$.createElement)return!1;const s=$.createElement("video");return O.getTech("Html5").isSupported()?["application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"].some(function(t){return/maybe|probably/i.test(s.canPlayType(t))}):!1}();ve.supportsNativeDash=function(){return!$||!$.createElement||!O.getTech("Html5").isSupported()?!1:/maybe|probably/i.test($.createElement("video").canPlayType("application/dash+xml"))}();ve.supportsTypeNatively=s=>s==="hls"?ve.supportsNativeHls:s==="dash"?ve.supportsNativeDash:!1;ve.isSupported=function(){return O.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};ve.xhr.onRequest=function(s){e0(ve.xhr,s)};ve.xhr.onResponse=function(s){t0(ve.xhr,s)};ve.xhr.offRequest=function(s){i0(ve.xhr,s)};ve.xhr.offResponse=function(s){s0(ve.xhr,s)};const pk=O.getComponent("Component");class r0 extends pk{constructor(e,t,i){if(super(t,i.vhs),typeof i.initialBandwidth=="number"&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=Ct("VhsHandler"),t.options_&&t.options_.playerId){const r=O.getPlayer(t.options_.playerId);this.player_=r}if(this.tech_=t,this.source_=e,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&t.overrideNativeAudioTracks&&t.overrideNativeVideoTracks)t.overrideNativeAudioTracks(!0),t.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(t.featuresNativeVideoTracks||t.featuresNativeAudioTracks))throw new Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on($,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],r=>{const n=$.fullscreenElement||$.webkitFullscreenElement||$.mozFullScreenElement||$.msFullscreenElement;n&&n.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()}),this.on(this.tech_,"seeking",function(){if(this.ignoreNextSeekingEvent_){this.ignoreNextSeekingEvent_=!1;return}this.setCurrentTime(this.tech_.currentTime())}),this.on(this.tech_,"error",function(){this.tech_.error()&&this.playlistController_&&this.playlistController_.pauseLoading()}),this.on(this.tech_,"play",this.play)}setOptions_(e={}){if(this.options_=se(this.options_,e),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions!==!1,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.useBandwidthFromLocalStorage=typeof this.source_.useBandwidthFromLocalStorage<"u"?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=this.options_.useNetworkInformationApi||!1,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=this.options_.llhls!==!1,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,typeof this.options_.playlistExclusionDuration!="number"&&(this.options_.playlistExclusionDuration=60),typeof this.options_.bandwidth!="number"&&this.options_.useBandwidthFromLocalStorage){const i=Zg();i&&i.bandwidth&&(this.options_.bandwidth=i.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),i&&i.throughput&&(this.options_.throughput=i.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"}))}typeof this.options_.bandwidth!="number"&&(this.options_.bandwidth=$e.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===$e.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","customPixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR","liveRangeSafeTimeDelta","llhls","useForcedSubtitles","useNetworkInformationApi","useDtsForTimestampOffset","exactManifestTimings","leastPixelDiffSelector"].forEach(i=>{typeof this.source_[i]<"u"&&(this.options_[i]=this.source_[i])}),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio;const t=this.options_.customPixelRatio;typeof t=="number"&&t>=0&&(this.customPixelRatio=t)}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=fk(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=ve,this.options_.sourceType=Yf(t),this.options_.seekTo=n=>{this.tech_.setCurrentTime(n)},this.options_.player_=this.player_,this.playlistController_=new YD(this.options_);const i=se({liveRangeSafeTimeDelta:Ft},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new ek(i),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{const n=O.players[this.tech_.options_.playerId];let a=this.playlistController_.error;typeof a=="object"&&!a.code?a.code=3:typeof a=="string"&&(a={message:a,code:3}),n.error(a)});const r=this.options_.bufferBasedABR?ve.movingAverageBandwidthSelector(.55):ve.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):r.bind(this),this.playlistController_.selectInitialPlaylist=ve.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPlaylist},set(n){this.playlistController_.selectPlaylist=n.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(n){this.playlistController_.mainSegmentLoader_.throughput.rate=n,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let n=this.playlistController_.mainSegmentLoader_.bandwidth;const a=E.navigator.connection||E.navigator.mozConnection||E.navigator.webkitConnection,o=1e7;if(this.options_.useNetworkInformationApi&&a){const u=a.downlink*1e3*1e3;u>=o&&n>=o?n=Math.max(n,u):n=u}return n},set(n){this.playlistController_.mainSegmentLoader_.bandwidth=n,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){const n=1/(this.bandwidth||1);let a;return this.throughput>0?a=1/this.throughput:a=0,Math.floor(1/(n+a))},set(){O.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playlistController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>ji(this.tech_.buffered()),enumerable:!0},currentTime:{get:()=>this.tech_.currentTime(),enumerable:!0},currentSource:{get:()=>this.tech_.currentSource_,enumerable:!0},currentTech:{get:()=>this.tech_.name_,enumerable:!0},duration:{get:()=>this.tech_.duration(),enumerable:!0},main:{get:()=>this.playlists.main,enumerable:!0},playerDimensions:{get:()=>this.tech_.currentDimensions(),enumerable:!0},seekable:{get:()=>ji(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one("canplay",this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on("bandwidthupdate",()=>{this.options_.useBandwidthFromLocalStorage&&hk({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{ZD(this)}),this.playlistController_.sourceUpdater_.on("createdsourcebuffers",()=>{this.setupEme_()}),this.on(this.playlistController_,"progress",function(){this.tech_.trigger("progress")}),this.on(this.playlistController_,"firstplay",function(){this.ignoreNextSeekingEvent_=!0}),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=E.URL.createObjectURL(this.playlistController_.mediaSource),this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),ck({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:e&&e.media(),mainPlaylists:this.playlists.main.playlists}).then(()=>{this.logger_("created EME key session"),this.playlistController_.sourceUpdater_.initializedEme()}).catch(t=>{this.logger_("error while creating EME key session",t),this.player_.error({message:"Failed to initialize media keys for EME",code:3})})}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=dk({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});if(this.player_.tech_.on("keystatuschange",i=>{this.playlistController_.updatePlaylistByKeyStatus(i.keyId,i.status)}),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),!t){this.playlistController_.sourceUpdater_.initializedEme();return}this.createKeySessions_()}setupQualityLevels_(){const e=O.players[this.tech_.options_.playerId];!e||!e.qualityLevels||this.qualityLevels_||(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{ok(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{Jg(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":Yg,"mux.js":sk,"mpd-parser":rk,"m3u8-parser":nk,"aes-decrypter":ak}}version(){return this.constructor.version()}canChangeType(){return zg.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(e){this.playlistController_.setCurrentTime(e)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&E.URL.revokeObjectURL&&(E.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return yw({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,r=2){return Dg({programTime:e,playlist:this.playlistController_.media(),retryCount:r,pauseAfterSeek:i,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{e0(this.xhr,e)},this.xhr.onResponse=e=>{t0(this.xhr,e)},this.xhr.offRequest=e=>{i0(this.xhr,e)},this.xhr.offResponse=e=>{s0(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}attachStreamingEventListeners_(){const e=["seekablerangeschanged","bufferedrangeschanged","contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"],t=["gapjumped","playedrangeschanged"];e.forEach(i=>{this.playlistController_.on(i,r=>{this.player_.trigger(xe({},r))})}),t.forEach(i=>{this.playbackWatcher_.on(i,r=>{this.player_.trigger(xe({},r))})})}}const Na={name:"videojs-http-streaming",VERSION:Yg,canHandleSource(s,e={}){const t=se(O.options,e);return!t.vhs.experimentalUseMMS&&!Nr("avc1.4d400d,mp4a.40.2",!1)?!1:Na.canPlayType(s.type,t)},handleSource(s,e,t={}){const i=se(O.options,t);return e.vhs=new r0(s,e,i),e.vhs.xhr=xg(),e.vhs.setupXhrHooks_(),e.vhs.src(s.src,s.type),e.vhs},canPlayType(s,e){const t=Yf(s);if(!t)return"";const i=Na.getOverrideNative(e);return!ve.supportsTypeNatively(t)||i?"maybe":""},getOverrideNative(s={}){const{vhs:e={}}=s,t=!(O.browser.IS_ANY_SAFARI||O.browser.IS_IOS),{overrideNative:i=t}=e;return i}},mk=()=>Nr("avc1.4d400d,mp4a.40.2",!0);mk()&&O.getTech("Html5").registerSourceHandler(Na,0);O.VhsHandler=r0;O.VhsSourceHandler=Na;O.Vhs=ve;O.use||O.registerComponent("Vhs",ve);O.options.vhs=O.options.vhs||{};(!O.getPlugin||!O.getPlugin("reloadSourceOnError"))&&O.registerPlugin("reloadSourceOnError",ik);/*! @name videojs-contrib-eme @version 3.11.2 @license Apache-2.0 */function Ma(){return Ma=Object.assign||function(s){for(var e=1;e=400&&r.statusCode<=599){var a=n;t&&(a=String.fromCharCode.apply(null,new Uint8Array(n))),e({cause:a});return}e(null,n)}});var Tk=function(e){var t=String.fromCharCode.apply(null,new Uint16Array(e)),i=new E.DOMParser().parseFromString(t,"application/xml"),r=i.getElementsByTagName("HttpHeaders")[0],n={};if(r)for(var a=r.getElementsByTagName("name"),o=r.getElementsByTagName("value"),u=0;u"u"){i.mediaKeysObject=null,i.pendingSessionData=[];var y,v;p=new Promise(function(b,C){if(i.keySystem=a.keySystem,v=Jh(a.keySystem,o.keySystems[a.keySystem]),!v.getCertificate){b(a);return}v.getCertificate(o,function(_,D){if(_){C(_);return}y=D,b()})}).then(function(){return a.createMediaKeys()}).then(function(b){return Ek({player:t,video:i,certificate:y,createdMediaKeys:b})}).catch(function(b){return b?Promise.reject(b):Promise.reject("Failed to create and initialize a MediaKeys object")})}return p.then(function(){var b=Jh(i.keySystem,o.keySystems[i.keySystem]),C=b.getLicense;return xk({player:t,video:i,initDataType:r,initData:n,options:o,getLicense:i.keySystem?wk(C,c):null,removeSession:u,eventBus:c})})},rc="com.apple.fps.1_0",kk=function(e){var t=e.initData,i=e.id,r=e.cert;typeof i=="string"&&(i=gk(i));var n=0,a=new ArrayBuffer(t.byteLength+4+i.byteLength+4+r.byteLength),o=new DataView(a),u=new Uint8Array(a,n,t.byteLength);u.set(t),n+=t.byteLength,o.setUint32(n,i.byteLength,!0),n+=4;var c=new Uint16Array(a,n,i.length);c.set(i),n+=c.byteLength,o.setUint32(n,r.byteLength,!0),n+=4;var p=new Uint8Array(a,n,r.byteLength);return p.set(r),new Uint8Array(a,0,a.byteLength)},Ik=function(e){var t=e.video,i=e.contentId,r=e.initData,n=e.cert,a=e.options,o=e.getLicense,u=e.eventBus;return new Promise(function(c,p){if(!t.webkitKeys)try{t.webkitSetMediaKeys(new E.WebKitMediaKeys(rc))}catch{p("Could not create MediaKeys");return}var y;try{y=t.webkitKeys.createSession("video/mp4",kk({id:i,initData:r,cert:n}))}catch{p("Could not create key session");return}u.trigger("keysessioncreated"),y.contentId=i,y.addEventListener("webkitkeymessage",function(v){o(a,i,v.message,function(b,C){if(u&&u.trigger("licenserequestattempted"),b){p(b);return}y.update(new Uint8Array(C))})}),y.addEventListener("webkitkeyadded",function(){c()}),y.addEventListener("webkitkeyerror",function(){var v=y.error;p("KeySession error: code "+v.code+", systemCode "+v.systemCode)})})},Pk=function(e){return function(t,i){var r=ho(t.emeHeaders,e.certificateHeaders);O.xhr({uri:e.certificateUri,responseType:"arraybuffer",headers:r},zs(function(n,a){if(n){i(n);return}i(null,new Uint8Array(a))}))}},Lk=function(e,t){return _k(yk(t))},Ok=function(e){return function(t,i,r,n){var a=ho({"Content-type":"application/octet-stream"},t.emeHeaders,e.licenseHeaders);O.xhr({uri:e.licenseUri,method:"POST",responseType:"arraybuffer",body:r,headers:a},zs(n,!0))}},Rk=function(e){var t=e.video,i=e.initData,r=e.options,n=e.eventBus,a=r.keySystems[rc],o=a.getCertificate||Pk(a),u=a.getContentId||Lk,c=a.getLicense||Ok(a);return new Promise(function(p,y){o(r,function(v,b){if(v){y(v);return}p(b)})}).then(function(p){return Ik({video:t,cert:p,initData:i,getLicense:c,options:r,contentId:u(r,i),eventBus:n})})},bs="com.microsoft.playready",Nk=function(e,t,i,r){var n=e.keySystems[bs];if(typeof n.getKey=="function"){n.getKey(e,i.destinationURL,i.message.buffer,function(o,u){if(o){r.trigger({message:"Unable to get key: "+o,target:t,type:"mskeyerror"});return}t.update(u)});return}typeof n=="string"?n={url:n}:typeof n=="boolean"&&(n={}),n.url||(n.url=i.destinationURL);var a=function(u,c){if(r&&r.trigger("licenserequestattempted"),u){r.trigger({message:"Unable to request key from url: "+n.url,target:t,type:"mskeyerror"});return}t.update(new Uint8Array(c))};n.getLicense?n.getLicense(e,i.message.buffer,a):n0(n,i.message.buffer,e,a)},Mk=function(e,t,i,r){var n=e.msKeys.createSession("video/mp4",t);if(!n)throw new Error("Could not create key session.");r.trigger("keysessioncreated"),n.addEventListener("mskeymessage",function(a){Nk(i,n,a,r)}),n.addEventListener("mskeyerror",function(a){r.trigger({message:"Unexpected key error from key session with "+("code: "+n.error.code+" and systemCode: "+n.error.systemCode),target:n,type:"mskeyerror"})}),n.addEventListener("mskeyadded",function(){r.trigger({target:n,type:"mskeyadded"})})},Bk=function(s){var e=s.video,t=s.initData,i=s.options,r=s.eventBus;e.msKeys&&delete e.msKeys;try{e.msSetMediaKeys(new E.MSMediaKeys(bs))}catch(n){throw new Error("Unable to create media keys for PlayReady key system. Error: "+n.message)}Mk(e,t,i,r)},Fk="3.11.2",Uk=function(e,t){for(var i=0;i=0)&&(t[r]=s[r]);return t}function tf(s,e){if(s==null)return{};var t=Wk(s,e),i,r;if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);for(r=0;r=0)&&Object.prototype.propertyIsEnumerable.call(s,i)&&(t[i]=s[i])}return t}var Kk="1.14.0";const Xk=O.getComponent("player");class Yk extends Xk{constructor(e,t,i){t=O.obj.merge(t,{plugins:{eme:!0}}),super(e,t,i)}audioTrack(e){const t=Array.from(this.player().audioTracks());if(!e)return t.find(a=>a.enabled);const{kind:i,language:r}=e,n=t.find(a=>a.language===r&&a.kind===i)||t.find(a=>a.language===r);return n&&(n.enabled=!0),n}bufferedRanges(){const e=[];for(let t=0;t!["chapters","metadata"].includes(a.kind));if(!e)return t.find(a=>a.mode==="showing");t.forEach(a=>a.mode="disabled");const{kind:i,language:r}=e;return t.find(a=>(a.language===r&&a.kind===i&&(a.mode="showing"),a.mode==="showing"))||t.find(a=>(a.language===r&&(a.mode="showing"),a.mode==="showing"))}}O.registerComponent("player",Yk);const he=O;he.VERSION={pillarbox:Kk,videojs:O.VERSION,[O.VhsSourceHandler.name]:O.VhsSourceHandler.VERSION,eme:O.getPlugin("eme").VERSION};he.options.enableSmoothSeeking=!0;he.options.fill=!0;he.options.html5={vhs:{useForcedSubtitles:!0}};he.options.liveTracker={trackingThreshold:120,liveTolerance:15};he.options.liveui=!0;he.options.playsinline=!0;he.options.responsive=!0;he.options.trackers={};class sf{constructor(e="il.srgssr.ch"){this.setIlHost(e)}setIlHost(e){this.baseUrl=`${e}/integrationlayer/2.1/`}handleRequest(e){var t=this;return function(){var i=gs(function*(r){const n=typeof e=="function"?e(r):t.mediaCompositionUrlHandler(r),a=yield fetch(n);if(!a.ok)throw a;return yield a.json()});return function(r){return i.apply(this,arguments)}}()}mediaCompositionUrlHandler(e){return`https://${this.baseUrl}mediaComposition/byUrn/${e}?onlyChapters=true&vector=portalplay`}}const fs={WIDTH_240:"240",WIDTH_320:"320",WIDTH_480:"480",WIDTH_960:"960",WIDTH_1920:"1920"},Jn={JPG:"jpg",WEBP:"webp",PNG:"png"},Qk="https://il.srgssr.ch/images/";class Jk{static scale({url:e,width:t=fs.WIDTH_960,format:i=Jn.JPG}={},r=Qk){if(!e)return;const n=new URL(r);return n.searchParams.set("imageUrl",e),n.searchParams.set("format",i),n.searchParams.set("width",t),decodeURIComponent(n.href)}static get JPG(){return Jn.JPG}static get PNG(){return Jn.PNG}static get WEBP(){return Jn.WEBP}static get WIDTH_240(){return fs.WIDTH_240}static get WIDTH_320(){return fs.WIDTH_320}static get WIDTH_480(){return fs.WIDTH_480}static get WIDTH_960(){return fs.WIDTH_960}static get WIDTH_1920(){return fs.WIDTH_1920}}const Zk={WIDEVINE:"com.widevine.alpha",FAIRPLAY:"com.apple.fps.1_0",PLAYREADY:"com.microsoft.playready"};class Jr{static buildKeySystems(e=[]){const t={};return e.forEach(i=>{const r=Jr.vendors[i.type];if(Jr.vendors.FAIRPLAY===r){const{certificateUrl:n,licenseUrl:a}=i;t[r]={certificateUri:n,licenseUri:a}}else t[r]=i.licenseUrl}),{keySystems:t}}static hasDrm(e){return e.some(({drmList:t})=>t&&t.length>0)}static get vendors(){return Zk}}const Zn={AKAMAI:"AKAMAI",NONE:"NONE"};class Xi{static aclPath(e){const t=e.pathname;return`${t.substring(0,t.lastIndexOf("/")+1)}*`}static get AKAMAI(){return Zn.AKAMAI}static hasToken(e){return e.some(t=>Xi.isAkamai(t.tokenType))}static isAkamai(e){return Zn.AKAMAI===e}static isNone(e){return Zn.NONE===e}static get NONE(){return Zn.NONE}static tokenize(e,t){const i=new URL(`${e.url}`),r=Xi.aclPath(i),n=`${t}${encodeURIComponent(r)}`;return fetch(n).then(a=>a.ok?a.json():Promise.reject({status:a.status,statusText:a.statusText})).then(({token:{authparams:a}})=>(new URLSearchParams(a).forEach((u,c)=>i.searchParams.set(c,u)),Object.assign({},e,{url:i.toString()}))).catch(a=>Promise.reject(a))}static tokenizeSources(e,t="https://tp.srgssr.ch/akahd/token?acl="){const i=[];return e.forEach(r=>{const n=Xi.tokenize(r,t);i.push(n)}),Promise.all(i).then(r=>r).catch(r=>Promise.reject(r))}}const rf="emptied",nf="ended",af="loadeddata",of="loadstart",fl="pause",eI="play",pl="playing",lf="ratechange",uf="seeking",ml="timeupdate",cf="waiting";class Fi{constructor(e,{debug:t=!1,environment:i="prod",playerVersion:r="none",tagCommanderScriptURL:n="//colibri-js.akamaized.net/penguin/tc_SRGGD_11.js"}={}){this.isDebugEnabled=t,this.elapsedPlaybackTime=0,this.environment=i,this.hasStarted=!1,this.heartBeatIntervalId=void 0,this.initialized=!1,this.isSeeking=!1,this.isWaiting=!1,this.mediaSession=0,this.pendingQueue=[],this.pendingTagCommanderReload=!1,this.player=e,this.playerVersion=r,this.srcMediaData=void 0,this.startPlaybackSession=0,this.tagCommanderScriptURL=n,this.trackedCurrentTime=0,this.uptimeIntervalId=void 0,this.initScript(),this.initListeners()}beforeunload(){this.notify("stop")}clearTimers(){clearInterval(this.heartBeatIntervalId),clearInterval(this.uptimeIntervalId),clearTimeout(this.uptimeTimeoutId)}currentTime(){return Math.round(this.trackedCurrentTime)}debug(e){if(e===void 0)return this.isDebugEnabled||this.player.debug();this.isDebugEnabled=!!e}destroy(){this.clearTimers(),window.tc_vars||(window.tc_vars={}),this.elapsedPlaybackTime=0,this.hasStarted=!1,this.heartBeatIntervalId=void 0,this.initialized=!1,this.isWaiting=!1,this.mediaSession=0,this.pendingQueue=[],this.srcMediaData=void 0,this.startPlaybackSession=0,this.trackedCurrentTime=0,this.uptimeIntervalId=void 0}dispose(){this.beforeunload(),this.clearTimers(),window.removeEventListener("beforeunload",this.beforeunloadListener),this.player.off(rf,this.emptiedListener),this.player.off(nf,this.endedListener),this.player.off(of,this.loadstartListener),this.player.off(af,this.loadeddataListener),this.player.off(pl,this.playListener),this.player.off(fl,this.pauseListener),this.player.off(lf,this.rateChangeListener),this.player.off(uf,this.seekingListener),this.player.off(ml,this.timeUpdateListener),this.player.off(cf,this.waitingListener)}emptied(){this.player.ended()||this.notify("stop")}ended(){this.notify("eof"),this.mediaSession=0,this.clearTimers()}flush(){this.isTrackerDisabled()||(this.pendingTagCommanderReload&&window.tC&&(window.tC.container.reload(),this.pendingTagCommanderReload=!1),window.tc_events_11&&this.pendingQueue.length>0&&(this.pendingQueue.forEach(e=>{window.tc_events_11(this.player.el(),e.action,e.labels)}),this.pendingQueue=[]))}getCurrentAudioTrack(){const e=Array.from(this.player.audioTracks()).find(i=>i.enabled);let t="und";return e&&e.language&&(t=e.language),e?t.toUpperCase():""}getCurrentTextTrack(){const e=this.player.textTrack();let t="und";return e&&e.language&&(t=e.language),e?t.toUpperCase():""}getDvrWindowPosition(){const{liveTracker:e}=this.player,t=this.currentTime()-e.seekableStart()|0,i=e.liveWindow()-t;return i<0||i===1/0?0:i*1e3}getDvrWindowSize(){const e=this.player.liveTracker.liveWindow()===1/0,t=this.player.liveTracker.liveWindow()*1e3;return e?0:t}getElapsedPlaybackTime(){return this.startPlaybackSession?this.getElapsedPlayingTime():this.elapsedPlaybackTime}getElapsedPlayingTime(){const e=Fi.now()-this.startPlaybackSession|0;return this.elapsedPlaybackTime+e}getEventLabels(e){const t={event_id:e,event_timestamp:Fi.now(),media_dvr_window_length:0,media_dvr_window_offset:0,media_is_dvr:!1,media_is_live:!1,media_mute:this.player.muted()?"1":"0",media_playback_rate:this.player.playbackRate(),media_position:this.currentTime(),media_quality:this.srcMediaData.mediaData.quality,media_subtitles_on:this.isTextTrackEnabled(),media_volume:(this.player.volume()*100).toFixed(0),navigation_environment:this.environment};return this.isAudioTrackEnabled()&&(t.media_audio_track=this.getCurrentAudioTrack()),this.isTextTrackEnabled()&&(t.media_subtitle_selection=this.getCurrentTextTrack()),this.isMediaOnDemand()||(t.media_is_live=!0,t.media_position=this.getElapsedPlaybackTime()),this.isMediaDvr()&&(t.media_dvr_window_offset=this.getDvrWindowPosition()|0,t.media_dvr_window_length=this.getDvrWindowSize()|0,t.media_is_dvr=!0,t.media_timeshift=[eI,fl].includes(e)?this.timeShifted():0),t}getInternalLabels(){const e={media_bu_distributer:this.srcMediaData.mediaData.vendor,media_chromecast_selected:!!this.player.tech(!0).isCasting,media_embedding_url:document.referrer,media_player_display:"default",media_player_name:"pillarbox-web",media_player_version:this.playerVersion,media_url:this.srcMediaData.src},t=this.srcMediaData.mediaData.analyticsMetadata||{};window.tc_vars=Object.assign({},window.tc_vars,e,t)}heartBeat(){this.heartBeatIntervalId=setInterval(()=>{this.player.paused()||this.notify("pos")},3e4)}initCallbacks(){this.beforeunloadListener=this.beforeunload.bind(this),this.emptiedListener=this.emptied.bind(this),this.endedListener=this.ended.bind(this),this.loadstartListener=this.loadstart.bind(this),this.loadeddataListener=this.loadeddata.bind(this),this.playListener=this.play.bind(this),this.pauseListener=this.pause.bind(this),this.rateChangeListener=this.rateChange.bind(this),this.seekingListener=this.seeking.bind(this),this.timeUpdateListener=this.timeUpdate.bind(this),this.waitingListener=this.waiting.bind(this)}initListeners(){this.initCallbacks(),window.addEventListener("beforeunload",this.beforeunloadListener),this.player.on(rf,this.emptiedListener),this.player.on(nf,this.endedListener),this.player.on(of,this.loadstartListener),this.player.on(af,this.loadeddataListener),this.player.on(pl,this.playListener),this.player.on(fl,this.pauseListener),this.player.on(lf,this.rateChangeListener),this.player.on(uf,this.seekingListener),this.player.on(ml,this.timeUpdateListener),this.player.on(cf,this.waitingListener),this.player.one("dispose",this.dispose.bind(this))}initScript(){const e="tc_script__11";if(!document.querySelector(`#${e}`)){const t=document.createElement("script"),i=this.tagCommanderScriptURL;t.defer=!0,t.id=e,t.src=i,t.type="text/javascript",t.onload=r=>{this.flush()},document.body.appendChild(t)}}isAudioTrackEnabled(){return!!this.getCurrentAudioTrack()}isMediaDvr(){const{trackingThreshold:e}=this.player.liveTracker.options();return!this.isMediaOnDemand()&ðis.player.liveTracker.liveWindow()}isMediaOnDemand(){return Number.isFinite(this.player.duration())}isTextTrackEnabled(){return!!this.getCurrentTextTrack()}isTrackerDisabled(){return!this.srcMediaData||!this.srcMediaData.mediaData?!0:Array.isArray(this.srcMediaData.disableTrackers)?!!this.srcMediaData.disableTrackers.find(e=>e.toLowerCase()===Fi.name.toLowerCase()):!!this.srcMediaData.disableTrackers}loadstart(){this.destroy(),this.updateSrcMediaData(this.player.currentSource()),!this.isTrackerDisabled()&&(this.getInternalLabels(),this.reloadTagCommanderContainer(),this.notify("buffer_start"),this.hasStarted=!1)}loadeddata(){this.notify("init"),this.initialized=!0,this.notify("buffer_stop")}log(e,t,i="log"){this.debug()&&console[i](`SRGAnalytics:${e}`,t,window.tc_vars)}notify(e,t){if(this.isTrackerDisabled())return;try{this.flush()}catch(r){this.log(e,r,"error")}const i=Object.assign({},this.getEventLabels(e),t);this.log(e,i);try{window.tc_events_11?window.tc_events_11(this.player.el(),e,i):this.pendingQueue.push({action:e,labels:i})}catch(r){this.log(e,r,"error")}}static now(){return(Date.now()/1e3).toFixed(0)}play(){this.hasStarted||(this.hasStarted=!0),!this.startPlaybackSession&&!this.isMediaOnDemand()&&(this.startPlaybackSession=Fi.now()),this.mediaSession===0&&(this.mediaSession=Fi.now(),this.heartBeat(),this.uptime()),this.timeUpdate(),this.notify("play"),this.isSeeking&&(this.isSeeking=!1)}pause(){if(this.isMediaOnDemand()||(this.elapsedPlaybackTime=this.getElapsedPlayingTime(),this.startPlaybackSession=0),!this.player.seeking()&&!this.isMediaLive()&&this.player.currentTime(){!this.player.paused()&&!this.isMediaOnDemand()&&this.notify("uptime")};this.uptimeTimeoutId=setTimeout(()=>{e(),this.uptimeIntervalId=setInterval(()=>{e()},6e4)},3e4)}waiting(){if(!this.initialized||this.isWaiting)return;const e=()=>{this.isWaiting=!1,this.notify("buffer_stop")};this.isWaiting=!0,this.notify("buffer_start"),he.browser.IS_ANY_SAFARI?this.player.one(ml,e):this.player.one(pl,e)}}class Ie{constructor(e,{playerName:t="none",playerVersion:i="none",platform:r="Web",schemaVersion:n=1,heartbeatInterval:a=3e4,beaconUrl:o="https://monitoring.pillarbox.ch/api/events"}={}){this.player=e,this.playerName=t,this.playerVersion=i,this.platform=r,this.schemaVersion=n,this.heartbeatInterval=a,this.beaconUrl=o,this.currentSessionId=void 0,this.lastPlaybackDuration=0,this.lastPlaybackStartTimestamp=0,this.lastStallCount=0,this.lastStallDuration=0,this.loadStartTimestamp=void 0,this.metadataRequestTime=0,this.mediaAssetUrl=void 0,this.mediaId=void 0,this.mediaMetadataUrl=void 0,this.mediaOrigin=void 0,this.tokenRequestTime=0,this.addListeners()}addListeners(){this.bindCallBacks(),this.player.on("loadstart",this.loadStart),this.player.on("loadeddata",this.loadedData),this.player.on("playing",this.playbackStart),this.player.on("pause",this.playbackStop),this.player.on("error",this.error),this.player.on(["playerreset","dispose","ended"],this.sessionStop),this.player.on(["waiting","stalled"],this.stalled),window.addEventListener("beforeunload",this.sessionStop)}bandwidth(){const e=this.player.tech(!0).vhs?this.player.tech(!0).vhs.stats:void 0;return e?e.bandwidth:void 0}bindCallBacks(){this.error=this.error.bind(this),this.loadedData=this.loadedData.bind(this),this.loadStart=this.loadStart.bind(this),this.playbackStart=this.playbackStart.bind(this),this.playbackStop=this.playbackStop.bind(this),this.stalled=this.stalled.bind(this),this.sessionStop=this.sessionStop.bind(this)}bufferDuration(){const e=this.player.buffered();let t=0;for(let i=0;ii==="metadata"&&t==="segment-metadata")||{};return e?e.value:void 0}currentResource(){let{bandwidth:e,uri:t}=this.currentRepresentation()||{};if(he.browser.IS_ANY_SAFARI){const{configuration:i}=Array.from(this.player.videoTracks()).find(r=>r.selected)||{};e=i?i.bitrate:void 0,t=this.player.currentSource().src}return{bitrate:e,url:t}}currentSourceMediaData(){return this.player.currentSource().mediaData?this.player.currentSource().mediaData:{}}error(){const e=this.player.error(),t=this.playbackPosition(),i=this.currentRepresentation(),r=i?i.uri:this.player.currentSource().src;this.player.hasStarted()||this.sendEvent("START",this.startEventData()),this.sendEvent("ERROR",Me(Me({log:JSON.stringify(e.metadata||he.log.history().slice(-15)),message:e.message,name:e.code},t),{},{url:r})),this.reset()}getDrmRequestDuration(){const e=Object.values(this.player.currentSource().keySystems||{}).map(i=>i.url);if(!e.length)return;const t=performance.getEntriesByType("resource").filter(({initiatorType:i,name:r})=>i==="xmlhttprequest"&&e.includes(r)).pop();return t&&t.duration}getMetadataInfo(e){const t=performance.getEntriesByType("resource").filter(({initiatorType:i,name:r})=>i==="fetch"&&r.includes(e)).pop();return t?{name:t.name,duration:t.duration}:{}}getTokenRequestDuration(e){if(!e)return;const t=performance.getEntriesByType("resource").filter(({initiatorType:i,name:r})=>i==="fetch"&&r.includes("/akahd/token")).pop();return t&&t.duration}heartbeat(){this.heartbeatIntervalId=setInterval(()=>{this.sendEvent("HEARTBEAT",this.statusEventData())},this.heartbeatInterval)}isTrackerDisabled(){const e=this.player.currentSource();return Array.isArray(e.disableTrackers)?!!e.disableTrackers.find(t=>t.toLowerCase()===Ie.name.toLowerCase()):!!e.disableTrackers}loadedData(){this.sendEvent("START",this.startEventData()),this.sendEvent("HEARTBEAT",this.statusEventData()),this.heartbeat()}loadStart(){!Object.keys(this.currentSourceMediaData()).length&&this.currentSessionId&&(this.sessionStop(),this.sessionStartTimestamp=Ie.timestamp()),this.loadStartTimestamp=Ie.timestamp()}mediaInfo(){return{asset_url:this.mediaAssetUrl,id:this.mediaId,metadata_url:this.mediaMetadataUrl,origin:this.mediaOrigin}}playbackDuration(){return this.lastPlaybackStartTimestamp?Ie.timestamp()+this.lastPlaybackDuration-this.lastPlaybackStartTimestamp:this.lastPlaybackDuration}playbackPosition(){const e=this.currentRepresentation(),t=Ie.secondsToMilliseconds(this.player.currentTime());let i;if(e&&(i=e.programDateTime),he.browser.IS_ANY_SAFARI){const r=Date.parse(this.player.$("video").getStartDate());i=isNaN(r)?void 0:r+t}return{position:t,position_timestamp:i}}playbackStart(){this.lastPlaybackStartTimestamp=Ie.timestamp()}playbackStop(){this.lastPlaybackDuration+=Ie.timestamp()-this.lastPlaybackStartTimestamp,this.lastPlaybackStartTimestamp=0}playerCurrentDimensions(){return this.player.currentDimensions()}playerInfo(){return{name:this.playerName,version:this.playerVersion,platform:this.platform}}qoeTimings(e,t){return{metadata:this.metadataRequestTime,asset:e,total:t-this.sessionStartTimestamp}}qosTimings(e){return{asset:e,drm:this.getDrmRequestDuration(),metadata:this.metadataRequestTime,token:this.tokenRequestTime}}removeListeners(){this.player.off("loadstart",this.loadStart),this.player.off("loadeddata",this.loadedData),this.player.off("playing",this.playbackStart),this.player.off("pause",this.playbackStop),this.player.off("error",this.error),this.player.off(["playerreset","dispose","ended"],this.sessionStop),this.player.off(["waiting","stalled"],this.stalled),window.removeEventListener("beforeunload",this.sessionStop)}removeTokenFromAssetUrl(e){if(e)try{const t=new URL(e);return t.searchParams.delete("hdnts"),t.href}catch{return}}reset(e){this.currentSessionId=void 0,this.lastPlaybackDuration=0,this.lastPlaybackStartTimestamp=0,this.lastStallCount=0,this.lastStallDuration=0,this.loadStartTimestamp=0,this.metadataRequestTime=0,this.mediaAssetUrl=void 0,this.mediaId=void 0,this.mediaMetadataUrl=void 0,this.mediaOrigin=void 0,this.sessionStartTimestamp=void 0,this.tokenRequestTime=0,clearInterval(this.heartbeatIntervalId),e&&!["ended","playerreset"].includes(e.type)&&this.removeListeners()}sendEvent(e,t={}){if(this.isTrackerDisabled()&&!this.currentSessionId||!this.currentSessionId)return;const i=JSON.stringify({event_name:e,session_id:this.currentSessionId,timestamp:Ie.timestamp(),version:this.schemaVersion,data:t});navigator.sendBeacon(this.beaconUrl,i)}sessionStart(){this.sessionStartTimestamp&&this.sessionStop(),this.sessionStartTimestamp=Ie.timestamp(),this.mediaId=this.player.currentSource().src||void 0}sessionStop(e){this.sendEvent("STOP",this.statusEventData()),this.reset(e)}stalled(){if(!this.player.hasStarted()||this.player.seeking()||this.isStalled)return;this.isStalled=!0;const e=Ie.timestamp(),t=()=>{const i=Ie.timestamp();this.isStalled=!1,this.lastStallCount+=1,this.lastStallDuration+=i-e};he.browser.IS_ANY_SAFARI?this.player.one("timeupdate",t):this.player.one("playing",t)}stallInfo(){return{count:this.lastStallCount,duration:this.lastStallDuration}}statusEventData(){const e=this.bandwidth(),t=this.bufferDuration(),{bitrate:i,url:r}=this.currentResource(),{droppedVideoFrames:n}=this.player.getVideoPlaybackQuality(),a=this.playbackDuration(),{position:o,position_timestamp:u}=this.playbackPosition(),c=isFinite(this.player.duration())?"On-demand":"Live",p=this.stallInfo();return{bandwidth:e,bitrate:i,buffered_duration:t,frame_drops:n,playback_duration:a,position:o,position_timestamp:u,stall:p,stream_type:c,url:r}}startEventData(){const e=Ie.timestamp(),t=this.loadStartTimestamp?e-this.loadStartTimestamp:0;return this.isTrackerDisabled()||(this.currentSessionId=Ie.sessionId()),this.mediaAssetUrl=this.removeTokenFromAssetUrl(this.player.currentSource().src),this.mediaMetadataUrl=this.getMetadataInfo(this.mediaId).name,this.metadataRequestTime=this.getMetadataInfo(this.mediaId).duration,this.mediaOrigin=window.location.href,this.tokenRequestTime=this.getTokenRequestDuration(this.currentSourceMediaData().tokenType),{browser:Ie.userAgent(),device:{id:Ie.deviceId()},media:this.mediaInfo(),player:this.playerInfo(),qoe_timings:this.qoeTimings(t,e),qos_timings:this.qosTimings(t),screen:this.playerCurrentDimensions()}}static sessionId(){return Ie.randomUUID()}static deviceId(){if(!localStorage)return;const e="pillarbox_device_id";let t=localStorage.getItem(e);return t||(t=Ie.randomUUID(),localStorage.setItem(e,t)),t}static randomUUID(){return crypto.randomUUID?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+e/4).toString(16))}static secondsToMilliseconds(e){return parseInt(e*1e3)}static timestamp(){return Date.now()}static userAgent(){return{user_agent:navigator.userAgent}}}class tI{findChapterByUrn(e){if(this.chapterList){const[t]=this.chapterList.filter(i=>i.urn===e);return t}}findMainSegment(){if(!this.segmentUrn)return;const e=this.getMainSegments(),[t]=e.filter(i=>i.urn===this.segmentUrn);return t}findResourceListByUrn(e){const t=this.findChapterByUrn(e);if(t)return t.resourceList||[]}getChapters(){const e="AUDIO";return this.getMainChapter().mediaType===e?[]:this.chapterList.filter(({mediaType:t})=>t!==e)}getFilteredExternalSubtitles(){const{subtitleList:e}=this.getMainChapter(),[{subtitleInformationList:t}={}]=this.getResourceList().filter(({subtitleInformationList:n})=>n),i=e&&!t;if(!e)return[];const r=e.filter(n=>n.format!=="TTML");return i?r:r.filter(n=>!t.find(o=>o.locale===n.locale&&n.type===o.type))}getMainBlockReason(){const e=this.getMainChapter();if(!e)return;let{blockReason:t}=e;return!t&&new Datee.blockReason)}getMainChapter(){return this.mainChapter||(this.mainChapter=this.findChapterByUrn(this.chapterUrn)),!this.mainChapter&&this.chapterList&&this.chapterList.length>0&&([this.mainChapter]=this.chapterList),this.mainChapter}getMainChapterImageUrl(){const e=this.getMainChapter();if(!(!e||!e.imageUrl))return e.imageUrl}getMainResources(){const e=this.getResourceList();if(!(!e||!e.length))return e.map(t=>({analyticsData:this.getMergedAnalyticsData(t.analyticsData),analyticsMetadata:this.getMergedAnalyticsMetadata(t.analyticsMetadata),blockReason:this.getMainChapter().blockReason,blockedSegments:this.getMainBlockedSegments(),imageUrl:this.getMainChapterImageUrl(),chapters:this.getChapters(),drmList:t.drmList,dvr:t.dvr,eventData:this.getMainChapter().eventData,id:this.getMainChapter().id,imageCopyright:this.getMainChapter().imageCopyright,intervals:this.getMainTimeIntervals(),live:t.live,mediaType:this.getMainChapter().mediaType,mimeType:t.mimeType,presentation:t.presentation,quality:t.quality,streaming:t.streaming,streamOffset:t.streamOffset,subtitles:this.getFilteredExternalSubtitles(),title:this.getMainChapter().title,tokenType:t.tokenType,url:t.url,urn:this.chapterUrn,vendor:this.getMainChapter().vendor}))}getMainSegments(){const e=this.getMainChapter();return!this.mainSegments&&e&&e.segmentList&&(this.mainSegments=e.segmentList),this.mainSegments||[]}getMainTimeIntervals(){const{timeIntervalList:e=[]}=this.getMainChapter()||{};return e}getMainValidFromDate(){const e=this.getMainChapter();if(!e)return new Date(0);const{validFrom:t}=e;if(t)return new Date(t)}getMergedAnalyticsData(e){return Me(Me(Me({},this.analyticsData),this.getMainChapter().analyticsData),e)}getMergedAnalyticsMetadata(e){return Me(Me(Me({},this.analyticsMetadata),this.getMainChapter().analyticsMetadata),e)}getResourceList(){const{resourceList:e}=this.getMainChapter();return e||[]}}var c0="Wiedergabe",d0="Pause",h0="Erneut abspielen",f0="Dauer",p0="LIVE",m0="Geladen",g0="Status",y0="Vollbild",_0="Stumm schalten",v0="Ton einschalten",T0="Untertitel",b0="Untertitel",S0="Kapitel",x0="Schließen",E0="Beschreibungen",C0="Schrift",A0="Weiß",w0="Schwarz",D0="Rot",k0="Grün",I0="Blau",P0="Gelb",L0="Magenta",O0="Türkis",R0="Hintergrund",N0="Fenster",M0="Durchsichtig",B0="Undurchsichtig",F0="Kein",U0="Erhoben",$0="Gedrückt",j0="Uniform",q0="Zwanglos",H0="Schreibschrift",V0="Zurücksetzen",z0="Fertig",G0="Farbe",W0="Deckkraft",iI={Play:c0,Pause:d0,Replay:h0,"Current Time":"Aktueller Zeitpunkt",Duration:f0,"Remaining Time":"Verbleibende Zeit","Stream Type":"Streamtyp",LIVE:p0,Loaded:m0,Progress:g0,Fullscreen:y0,"Exit Fullscreen":"Vollbildmodus beenden",Mute:_0,Unmute:v0,"Playback Rate":"Wiedergabegeschwindigkeit",Subtitles:T0,"subtitles off":"Untertitel aus",Captions:b0,"captions off":"Untertitel aus",Chapters:S0,"You aborted the media playback":"Sie haben die Videowiedergabe abgebrochen.","A network error caused the media download to fail part-way.":"Der Videodownload ist aufgrund eines Netzwerkfehlers fehlgeschlagen.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Das Video konnte nicht geladen werden, da entweder ein Server- oder Netzwerkfehler auftrat oder das Format nicht unterstützt wird.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Die Videowiedergabe wurde entweder wegen eines Problems mit einem beschädigten Video oder wegen verwendeten Funktionen, die vom Browser nicht unterstützt werden, abgebrochen.","No compatible source was found for this media.":"Für dieses Video wurde keine kompatible Quelle gefunden.","Play Video":"Video abspielen",Close:x0,"Modal Window":"Modales Fenster","This is a modal window":"Dies ist ein modales Fenster","This modal can be closed by pressing the Escape key or activating the close button.":'Durch Drücken der Esc-Taste bzw. Betätigung der Schaltfläche "Schließen" wird dieses modale Fenster geschlossen.',", opens captions settings dialog":", öffnet Einstellungen für Untertitel",", opens subtitles settings dialog":", öffnet Einstellungen für Untertitel",", selected":", ausgewählt","captions settings":"Untertiteleinstellungen","subtitles settings":"Untertiteleinstellungen","descriptions settings":"Einstellungen für Beschreibungen","Close Modal Dialog":"Modales Fenster schließen",Descriptions:E0,"descriptions off":"Beschreibungen aus","The media is encrypted and we do not have the keys to decrypt it.":"Die Entschlüsselungsschlüssel für den verschlüsselten Medieninhalt sind nicht verfügbar.",", opens descriptions settings dialog":", öffnet Einstellungen für Beschreibungen","Audio Track":"Tonspur",Text:C0,White:A0,Black:w0,Red:D0,Green:k0,Blue:I0,Yellow:P0,Magenta:L0,Cyan:O0,Background:R0,Window:N0,Transparent:M0,"Semi-Transparent":"Halbdurchsichtig",Opaque:B0,"Font Size":"Schriftgröße","Text Edge Style":"Textkantenstil",None:F0,Raised:U0,Depressed:$0,Uniform:j0,"Drop shadow":"Schlagschatten","Font Family":"Schriftfamilie","Proportional Sans-Serif":"Proportionale Sans-Serif","Monospace Sans-Serif":"Monospace Sans-Serif","Proportional Serif":"Proportionale Serif","Monospace Serif":"Monospace Serif",Casual:q0,Script:H0,"Small Caps":"Small-Caps",Reset:V0,"restore all settings to the default values":"Alle Einstellungen auf die Standardwerte zurücksetzen",Done:z0,"Caption Settings Dialog":"Einstellungsdialog für Untertitel","Beginning of dialog window. Escape will cancel and close the window.":"Anfang des Dialogfensters. Esc bricht ab und schließt das Fenster.","End of dialog window.":"Ende des Dialogfensters.","Audio Player":"Audio-Player","Video Player":"Video-Player","Progress Bar":"Fortschrittsbalken","progress bar timing: currentTime={1} duration={2}":"{1} von {2}","Volume Level":"Lautstärke","{1} is loading.":"{1} wird geladen.","Seek to live, currently behind live":"Zur Live-Übertragung wechseln. Aktuell wird es nicht live abgespielt.","Seek to live, currently playing live":"Zur Live-Übertragung wechseln. Es wird aktuell live abgespielt.","Exit Picture-in-Picture":"Bild-im-Bild-Modus beenden","Picture-in-Picture":"Bild-im-Bild-Modus","No content":"Kein Inhalt",Color:G0,Opacity:W0,"Text Background":"Texthintergrund","Caption Area Background":"Hintergrund des Untertitelbereichs","Playing in Picture-in-Picture":"Wird im Bild-im-Bild-Modus wiedergegeben","Skip forward {1} seconds":"{1} Sekunden vorwärts","Skip backward {1} seconds":"{1} Sekunden zurück"},sI=Object.freeze({__proto__:null,Background:R0,Black:w0,Blue:I0,Captions:b0,Casual:q0,Chapters:S0,Close:x0,Color:G0,Cyan:O0,Depressed:$0,Descriptions:E0,Done:z0,Duration:f0,Fullscreen:y0,Green:k0,LIVE:p0,Loaded:m0,Magenta:L0,Mute:_0,None:F0,Opacity:W0,Opaque:B0,Pause:d0,Play:c0,Progress:g0,Raised:U0,Red:D0,Replay:h0,Reset:V0,Script:H0,Subtitles:T0,Text:C0,Transparent:M0,Uniform:j0,Unmute:v0,White:A0,Window:N0,Yellow:P0,default:iI}),K0="Aus Gründen des Jugendschutzes steht dieser Inhalt nur zwischen 20:00 und 06:00 Uhr zur Verfügung.",X0="Aus Gründen des Jugendschutzes steht dieser Inhalt nur zwischen 23:00 und 05:00 Uhr zur Verfügung.",Y0="Die Werbung wurde übersprungen.",Q0="Dieser Inhalt ist nicht mehr verfügbar.",J0="Dieser Inhalt ist ausserhalb der Schweiz nicht verfügbar.",Z0="Dieser Inhalt steht aus publizistischen Gründen vorübergehend nicht zur Verfügung.",ey="Dieser Inhalt ist aus rechtlichen Gründen nicht verfügbar.",ty="Dieser Inhalt ist noch nicht verfügbar. Bitte probieren Sie es später noch einmal.",iy="Dieser Inhalt ist nicht verfügbar.",rI={AGERATING12:K0,AGERATING18:X0,COMMERCIAL:Y0,ENDDATE:Q0,GEOBLOCK:J0,JOURNALISTIC:Z0,LEGAL:ey,STARTDATE:ty,UNKNOWN:iy},nI=Object.freeze({__proto__:null,AGERATING12:K0,AGERATING18:X0,COMMERCIAL:Y0,ENDDATE:Q0,GEOBLOCK:J0,JOURNALISTIC:Z0,LEGAL:ey,STARTDATE:ty,UNKNOWN:iy,default:rI});he.addLanguage("de",Me(Me({},sI),nI));var sy="Play",ry="Pause",ny="Replay",ay="Duration",oy="LIVE",ly="Loaded",uy="Progress",cy="Fullscreen",dy="Mute",hy="Unmute",fy="Subtitles",py="Captions",my="Chapters",gy="Descriptions",yy="Close",_y="Text",vy="White",Ty="Black",by="Red",Sy="Green",xy="Blue",Ey="Yellow",Cy="Magenta",Ay="Cyan",wy="Background",Dy="Window",ky="Transparent",Iy="Opaque",Py="None",Ly="Raised",Oy="Depressed",Ry="Uniform",Ny="Casual",My="Script",By="Reset",Fy="Done",Uy="Color",$y="Opacity",aI={"Audio Player":"Audio Player","Video Player":"Video Player",Play:sy,Pause:ry,Replay:ny,"Current Time":"Current Time",Duration:ay,"Remaining Time":"Remaining Time","Stream Type":"Stream Type",LIVE:oy,"Seek to live, currently behind live":"Seek to live, currently behind live","Seek to live, currently playing live":"Seek to live, currently playing live",Loaded:ly,Progress:uy,"Progress Bar":"Progress Bar","progress bar timing: currentTime={1} duration={2}":"{1} of {2}",Fullscreen:cy,"Exit Fullscreen":"Exit Fullscreen",Mute:dy,Unmute:hy,"Playback Rate":"Playback Rate",Subtitles:fy,"subtitles off":"subtitles off",Captions:py,"captions off":"captions off",Chapters:my,Descriptions:gy,"descriptions off":"descriptions off","Audio Track":"Audio Track","Volume Level":"Volume Level","You aborted the media playback":"You aborted the media playback","A network error caused the media download to fail part-way.":"A network error caused the media download to fail part-way.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"The media could not be loaded, either because the server or network failed or because the format is not supported.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"The media playback was aborted due to a corruption problem or because the media used features your browser did not support.","No compatible source was found for this media.":"No compatible source was found for this media.","The media is encrypted and we do not have the keys to decrypt it.":"The media is encrypted and we do not have the keys to decrypt it.","Play Video":"Play Video",Close:yy,"Close Modal Dialog":"Close Modal Dialog","Modal Window":"Modal Window","This is a modal window":"This is a modal window","This modal can be closed by pressing the Escape key or activating the close button.":"This modal can be closed by pressing the Escape key or activating the close button.",", opens captions settings dialog":", opens captions settings dialog",", opens subtitles settings dialog":", opens subtitles settings dialog",", opens descriptions settings dialog":", opens descriptions settings dialog",", selected":", selected","captions settings":"captions settings","subtitles settings":"subtitles settings","descriptions settings":"descriptions settings",Text:_y,White:vy,Black:Ty,Red:by,Green:Sy,Blue:xy,Yellow:Ey,Magenta:Cy,Cyan:Ay,Background:wy,Window:Dy,Transparent:ky,"Semi-Transparent":"Semi-Transparent",Opaque:Iy,"Font Size":"Font Size","Text Edge Style":"Text Edge Style",None:Py,Raised:Ly,Depressed:Oy,Uniform:Ry,"Drop shadow":"Drop shadow","Font Family":"Font Family","Proportional Sans-Serif":"Proportional Sans-Serif","Monospace Sans-Serif":"Monospace Sans-Serif","Proportional Serif":"Proportional Serif","Monospace Serif":"Monospace Serif",Casual:Ny,Script:My,"Small Caps":"Small Caps",Reset:By,"restore all settings to the default values":"restore all settings to the default values",Done:Fy,"Caption Settings Dialog":"Caption Settings Dialog","Beginning of dialog window. Escape will cancel and close the window.":"Beginning of dialog window. Escape will cancel and close the window.","End of dialog window.":"End of dialog window.","{1} is loading.":"{1} is loading.","Exit Picture-in-Picture":"Exit Picture-in-Picture","Picture-in-Picture":"Picture-in-Picture","No content":"No content",Color:Uy,Opacity:$y,"Text Background":"Text Background","Caption Area Background":"Caption Area Background","Playing in Picture-in-Picture":"Playing in Picture-in-Picture","Skip backward {1} seconds":"Skip backward {1} seconds","Skip forward {1} seconds":"Skip forward {1} seconds"},oI=Object.freeze({__proto__:null,Background:wy,Black:Ty,Blue:xy,Captions:py,Casual:Ny,Chapters:my,Close:yy,Color:Uy,Cyan:Ay,Depressed:Oy,Descriptions:gy,Done:Fy,Duration:ay,Fullscreen:cy,Green:Sy,LIVE:oy,Loaded:ly,Magenta:Cy,Mute:dy,None:Py,Opacity:$y,Opaque:Iy,Pause:ry,Play:sy,Progress:uy,Raised:Ly,Red:by,Replay:ny,Reset:By,Script:My,Subtitles:fy,Text:_y,Transparent:ky,Uniform:Ry,Unmute:hy,White:vy,Window:Dy,Yellow:Ey,default:aI}),jy="To protect children this content is only available between 8PM and 6AM.",qy="To protect children this content is only available between 10PM and 5AM.",Hy="This commercial content is not available.",Vy="This content is not available anymore.",zy="This content is not available outside Switzerland.",Gy="This content is temporarily unavailable for journalistic reasons.",Wy="This content is not available due to legal restrictions.",Ky="This content is not available yet.",Xy="This content is not available.",lI={AGERATING12:jy,AGERATING18:qy,COMMERCIAL:Hy,ENDDATE:Vy,GEOBLOCK:zy,JOURNALISTIC:Gy,LEGAL:Wy,STARTDATE:Ky,UNKNOWN:Xy},uI=Object.freeze({__proto__:null,AGERATING12:jy,AGERATING18:qy,COMMERCIAL:Hy,ENDDATE:Vy,GEOBLOCK:zy,JOURNALISTIC:Gy,LEGAL:Wy,STARTDATE:Ky,UNKNOWN:Xy,default:lI});he.addLanguage("en",Me(Me({},oI),uI));var Yy="Lecture",Qy="Pause",Jy="Revoir",Zy="Durée",e_="EN DIRECT",t_="Chargé",i_="Progression",s_="Plein écran",r_="Mettre en sourdine",n_="Activer le son",a_="Sous-titres",o_="Sous-titres transcrits",l_="Chapitres",u_="Descriptions",c_="Fermer",d_="Texte",h_="Blanc",f_="Noir",p_="Rouge",m_="Vert",g_="Bleu",y_="Jaune",__="Magenta",v_="Cyan",T_="Arrière-plan",b_="Fenêtre",S_="Transparent",x_="Opaque",E_="Aucun",C_="Élevé",A_="Enfoncé",w_="Uniforme",D_="Manuscrite",k_="Scripte",I_="Réinitialiser",P_="Terminé",L_="Couleur",O_="Opacité",cI={"Audio Player":"Lecteur audio","Video Player":"Lecteur vidéo",Play:Yy,Pause:Qy,Replay:Jy,"Current Time":"Temps actuel",Duration:Zy,"Remaining Time":"Temps restant","Stream Type":"Type de flux",LIVE:e_,"Seek to live, currently behind live":"Rechercher le direct, actuellement après le direct","Seek to live, currently playing live":"Rechercher le direct, le direct actuellement en cours de lecture",Loaded:t_,Progress:i_,"Progress Bar":"Barre de progression","progress bar timing: currentTime={1} duration={2}":"{1} de {2}",Fullscreen:s_,"Exit Fullscreen":"Fenêtré",Mute:r_,Unmute:n_,"Playback Rate":"Vitesse de lecture",Subtitles:a_,"subtitles off":"Sous-titres désactivés",Captions:o_,"captions off":"Sous-titres transcrits désactivés",Chapters:l_,Descriptions:u_,"descriptions off":"descriptions désactivées","Audio Track":"Piste audio","Volume Level":"Niveau de volume","You aborted the media playback":"Vous avez interrompu la lecture de la vidéo.","A network error caused the media download to fail part-way.":"Une erreur de réseau a interrompu le téléchargement de la vidéo.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Cette vidéo n'a pas pu être chargée, soit parce que le serveur ou le réseau a échoué ou parce que le format n'est pas reconnu.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"La lecture de la vidéo a été interrompue à cause d'un problème de corruption ou parce que la vidéo utilise des fonctionnalités non prises en charge par votre navigateur.","No compatible source was found for this media.":"Aucune source compatible n'a été trouvée pour cette vidéo.","The media is encrypted and we do not have the keys to decrypt it.":"Le média est chiffré et nous n'avons pas les clés pour le déchiffrer.","Play Video":"Lire la vidéo",Close:c_,"Close Modal Dialog":"Fermer la boîte de dialogue modale","Modal Window":"Fenêtre modale","This is a modal window":"Ceci est une fenêtre modale","This modal can be closed by pressing the Escape key or activating the close button.":"Ce modal peut être fermé en appuyant sur la touche Échap ou activer le bouton de fermeture.",", opens captions settings dialog":", ouvrir les paramètres des sous-titres transcrits",", opens subtitles settings dialog":", ouvrir les paramètres des sous-titres",", opens descriptions settings dialog":", ouvrir les paramètres des descriptions",", selected":", sélectionné","captions settings":"Paramètres des sous-titres transcrits","subtitles settings":"Paramètres des sous-titres","descriptions settings":"Paramètres des descriptions",Text:d_,White:h_,Black:f_,Red:p_,Green:m_,Blue:g_,Yellow:y_,Magenta:__,Cyan:v_,Background:T_,Window:b_,Transparent:S_,"Semi-Transparent":"Semi-transparent",Opaque:x_,"Font Size":"Taille des caractères","Text Edge Style":"Style des contours du texte",None:E_,Raised:C_,Depressed:A_,Uniform:w_,"Drop shadow":"Ombre portée","Font Family":"Famille de polices","Proportional Sans-Serif":"Polices à chasse variable sans empattement (Proportional Sans-Serif)","Monospace Sans-Serif":"Polices à chasse fixe sans empattement (Monospace Sans-Serif)","Proportional Serif":"Polices à chasse variable avec empattement (Proportional Serif)","Monospace Serif":"Polices à chasse fixe avec empattement (Monospace Serif)",Casual:D_,Script:k_,"Small Caps":"Petites capitales",Reset:I_,"restore all settings to the default values":"Restaurer tous les paramètres aux valeurs par défaut",Done:P_,"Caption Settings Dialog":"Boîte de dialogue des paramètres des sous-titres transcrits","Beginning of dialog window. Escape will cancel and close the window.":"Début de la fenêtre de dialogue. La touche d'échappement annulera et fermera la fenêtre.","End of dialog window.":"Fin de la fenêtre de dialogue.","Exit Picture-in-Picture":"Quitter le mode image dans l'image","Picture-in-Picture":"Image dans l'image","{1} is loading.":"{1} en cours de chargement.","No content":"Aucun contenu",Color:L_,Opacity:O_,"Text Background":"Arrière-plan du texte","Caption Area Background":"Arrière-plan de la zone de sous-titre","Skip backward {1} seconds":"Reculer de {1} secondes","Skip forward {1} seconds":"Avancer de {1} secondes"},dI=Object.freeze({__proto__:null,Background:T_,Black:f_,Blue:g_,Captions:o_,Casual:D_,Chapters:l_,Close:c_,Color:L_,Cyan:v_,Depressed:A_,Descriptions:u_,Done:P_,Duration:Zy,Fullscreen:s_,Green:m_,LIVE:e_,Loaded:t_,Magenta:__,Mute:r_,None:E_,Opacity:O_,Opaque:x_,Pause:Qy,Play:Yy,Progress:i_,Raised:C_,Red:p_,Replay:Jy,Reset:I_,Script:k_,Subtitles:a_,Text:d_,Transparent:S_,Uniform:w_,Unmute:n_,White:h_,Window:b_,Yellow:y_,default:cI}),R_="Pour protéger les enfants, ce contenu est accessible entre 20h et 6h.",N_="Pour protéger les enfants, ce contenu est accessible entre 23h et 5h.",M_="Ce contenu n'est actuellement pas disponible.",B_="Ce contenu n'est plus disponible.",F_="La RTS ne dispose pas des droits de diffusion en dehors de la Suisse.",U_="Ce contenu est temporairement indisponible pour des raisons éditoriales.",$_="Pour des raisons juridiques, ce contenu n'est pas disponible.",j_="Ce contenu n'est pas encore disponible. Veuillez réessayer plus tard.",q_="Ce contenu n'est actuellement pas disponible.",hI={AGERATING12:R_,AGERATING18:N_,COMMERCIAL:M_,ENDDATE:B_,GEOBLOCK:F_,JOURNALISTIC:U_,LEGAL:$_,STARTDATE:j_,UNKNOWN:q_},fI=Object.freeze({__proto__:null,AGERATING12:R_,AGERATING18:N_,COMMERCIAL:M_,ENDDATE:B_,GEOBLOCK:F_,JOURNALISTIC:U_,LEGAL:$_,STARTDATE:j_,UNKNOWN:q_,default:hI});he.addLanguage("fr",Me(Me({},dI),fI));var H_="Play",V_="Pausa",z_="Replay",G_="Durata",W_="LIVE",K_="Caricato",X_="Stato",Y_="Schermo intero",Q_="Disattiva l’audio",J_="Attiva l’audio",Z_="Sottotitoli",ev="Sottotitoli non udenti",tv="Capitolo",iv="Descrizioni",sv="Chiudi",rv="Testo",nv="Bianco",av="Nero",ov="Rosso",lv="Verde",uv="Blu",cv="Giallo",dv="Magenta",hv="Ciano",fv="Sfondo",pv="Finestra",mv="Trasparente",gv="Opaco",yv="Nessuno",_v="Uniforme",vv="Reinizializza",Tv="Fatto",bv="Colore",Sv="Opacità",pI={"Audio Player":"Lettore audio","Video Player":"Lettore video",Play:H_,Pause:V_,Replay:z_,"Current Time":"Orario attuale",Duration:G_,"Remaining Time":"Tempo rimanente","Stream Type":"Tipo di streaming",LIVE:W_,Loaded:K_,Progress:X_,"Progress Bar":"Barra di avanzamento","progress bar timing: currentTime={1} duration={2}":"{1} di {2}",Fullscreen:Y_,"Exit Fullscreen":"Chiudi Schermo intero",Mute:Q_,Unmute:J_,"Playback Rate":"Velocità di riproduzione",Subtitles:Z_,"subtitles off":"Senza sottotitoli",Captions:ev,"captions off":"Senza sottotitoli non udenti",Chapters:tv,Descriptions:iv,"descriptions off":"Descrizioni disattivate","Audio Track":"Traccia audio","Volume Level":"Livello del volume","You aborted the media playback":"La riproduzione del contenuto multimediale è stata interrotta.","A network error caused the media download to fail part-way.":"Il download del contenuto multimediale è stato interrotto a causa di un problema rete.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Il contenuto multimediale non può essere caricato a causa di un errore nel server o nella rete o perché il formato non viene supportato.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"La riproduzione del contenuto multimediale è stata interrotta a causa di un file danneggiato o per l’utilizzo di impostazioni non supportate dal browser.","No compatible source was found for this media.":"Non ci sono fonti compatibili per questo contenuto multimediale.","The media is encrypted and we do not have the keys to decrypt it.":"Il contenuto multimediale è criptato e non disponiamo delle chiavi per decifrarlo.","Play Video":"Riproduci il video",Close:sv,"Close Modal Dialog":"Chiudi la finestra di dialogo","Modal Window":"Finestra di dialogo","This is a modal window":"Questa è una finestra di dialogo","This modal can be closed by pressing the Escape key or activating the close button.":"Questa finestra di dialogo può essere chiusa premendo sul tasto Esc o attivando il pulsante di chiusura.",", opens captions settings dialog":", aprire i parametri della trascrizione dei sottotitoli",", opens subtitles settings dialog":", aprire i parametri dei sottotitoli",", opens descriptions settings dialog":", aprire i parametri delle descrizioni",", selected":", selezionato","captions settings":"Parametri sottotitoli non udenti","subtitles settings":"Parametri sottotitoli","descriptions settings":"Parametri descrizioni",Text:rv,White:nv,Black:av,Red:ov,Green:lv,Blue:uv,Yellow:cv,Magenta:dv,Cyan:hv,Background:fv,Window:pv,Transparent:mv,"Semi-Transparent":"Semi-Trasparente",Opaque:gv,"Font Size":"Dimensione dei caratteri","Text Edge Style":"Stile dei bordi del testo",None:yv,Uniform:_v,"Drop shadow":"Ombra","Font Family":"Carattere","Proportional Sans-Serif":"Sans-Serif proporzionale","Monospace Sans-Serif":"Sans-Serif monospaziato","Proportional Serif":"Serif proporzionale","Monospace Serif":"Serif monospaziato","Small Caps":"Maiuscoletto",Reset:vv,"restore all settings to the default values":"Ripristina i valori predefiniti per tutti i parametri",Done:Tv,"Caption Settings Dialog":"Finestra di dialogo dei parametri della trascrizione dei sottotitoli","Beginning of dialog window. Escape will cancel and close the window.":"Inizio della finestra di dialogo. Il tasto Esc annullerà l’operazione e chiuderà la finestra.","End of dialog window.":"Fine della finestra di dialogo.","{1} is loading.":"{1} in fase di caricamento.","Exit Picture-in-Picture":"Esci dalla modalità Picture-in-Picture","Picture-in-Picture":"Picture-in-Picture",Color:bv,Opacity:Sv,"Text Background":"Sfondo testo","Caption Area Background":"Sfondo area sottotitoli","Skip forward {1} seconds":"Avanti {1} secondi","Skip backward {1} seconds":"Indietro {1} secondi"},mI=Object.freeze({__proto__:null,Background:fv,Black:av,Blue:uv,Captions:ev,Chapters:tv,Close:sv,Color:bv,Cyan:hv,Descriptions:iv,Done:Tv,Duration:G_,Fullscreen:Y_,Green:lv,LIVE:W_,Loaded:K_,Magenta:dv,Mute:Q_,None:yv,Opacity:Sv,Opaque:gv,Pause:V_,Play:H_,Progress:X_,Red:ov,Replay:z_,Reset:vv,Subtitles:Z_,Text:rv,Transparent:mv,Uniform:_v,Unmute:J_,White:nv,Window:pv,Yellow:cv,default:pI}),xv="Per proteggere i bambini, questo media è disponibile solo fra le 20 e le 6.",Ev="Per proteggere i bambini, questo media è disponibile solo fra le 23 le 5.",Cv="Questo contenuto commerciale non è disponibile.",Av="Questo media non è più disponibile.",wv="Questo media non è disponibile fuori dalla Svizzera.",Dv="Questo contenuto è temporaneamente non disponibile per motivi editoriali.",kv="Il contenuto non è fruibile a causa di restrizioni legali.",Iv="Il contenuto non è ancora disponibile. Per cortesia prova più tardi.",Pv="Questo media non è disponibile.",gI={AGERATING12:xv,AGERATING18:Ev,COMMERCIAL:Cv,ENDDATE:Av,GEOBLOCK:wv,JOURNALISTIC:Dv,LEGAL:kv,STARTDATE:Iv,UNKNOWN:Pv},yI=Object.freeze({__proto__:null,AGERATING12:xv,AGERATING18:Ev,COMMERCIAL:Cv,ENDDATE:Av,GEOBLOCK:wv,JOURNALISTIC:Dv,LEGAL:kv,STARTDATE:Iv,UNKNOWN:Pv,default:gI});he.addLanguage("it",Me(Me({},mI),yI));var Lv="Laschar ir",Ov="Pausa",Rv="Mussar danovamain",Nv="Durada",Mv="LIVE",Bv="Chargià",Fv="Progress",Uv="Entir visur",$v="Senza tun",jv="Cun tun",qv="Suttitels",Hv="Suttitels",Vv="Chapitels",zv="Descripziuns",Gv="Serrar",Wv="Text",Kv="Alv",Xv="Nair",Yv="Cotschn",Qv="Verd",Jv="Blau",Zv="Mellen",eT="Magenta",tT="Cyan",iT="Fund",sT="Fanestra",rT="Transparent",nT="Betg transparent",aT="Nagin",oT="Auzà",lT="Sbassà",uT="Uniform",cT="Sumbriva",dT="Casual",hT="Script",fT="Da nov",pT="Fatg",mT="Per proteger uffants, è quest cuntegn disponibel mo tranter las 20.00 e las 06.00.",gT="Per proteger uffants, è quest cuntegn disponibel mo tranter las 23.00 e las 05.00.",yT="Quest medium commerzial n'è betg disponibel.",_T="Quest cuntegn n'è betg pli disponibel.",vT="Quest cuntegn n'è betg disponibel ordaifer la Svizra.",TT="Quest cuntegn na stat ad interim betg a disposiziun per motivs publicistics.",bT="Quest cuntegn n'è betg disponibel perquai ch'el è scadì.",ST="Quest cuntegn n'è betg anc disponibel. Empruvai pli tard.",xT="Quest cuntegn n'è betg disponibel.",_I={"Audio Player":"Audio-Player","Video Player":"Video-Player",Play:Lv,Pause:Ov,Replay:Rv,"Current Time":"Temp actual",Duration:Nv,"Remaining Time":"Temp restant","Stream Type":"Tip dal stream",LIVE:Mv,Loaded:Bv,Progress:Fv,"Progress Bar":"Bar da progessiun","progress bar timing: currentTime={1} duration={2}":"{1} da {2}",Fullscreen:Uv,"Non-Fullscreen":"Betg entir visur",Mute:$v,Unmute:jv,"Playback Rate":"Tempo ",Subtitles:qv,"subtitles off":"senza suttitels",Captions:Hv,"captions off":"senza suttitels",Chapters:Vv,Descriptions:zv,"descriptions off":"senza descripziuns","Audio Track":"Piese audio","Volume Level":"Nivel dal volumen","You aborted the media playback":"Vus avais interrut il vdieo","A network error caused the media download to fail part-way.":"In sbagl en la rait ha impedì il download","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Il video n'è betg chargià - ubain per in sbagl da server / da la rait, ubain ch'il format n'è betg cumpatibel.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Il video è interrut: Ubain ch'il video è donnegià, ubain che funcziuns n'èn betg cumpatiblas.","No compatible source was found for this media.":"Chattà nagina funtauna cumpatibla per quest video.","The media is encrypted and we do not have the keys to decrypt it.":"Il video è codifitgà da moda nunenconuschenta.","Play Video":"Aviar video",Close:Gv,"Close Modal Dialog":"Serrar la fanestra modala","Modal Window":"Fanestra modala","This is a modal window":"Quai è ina fanestra modala","This modal can be closed by pressing the Escape key or activating the close button.":'Questa fanestra modala pudais serrar cun la tasta "Escape" ubain cun il buttun.',", opens captions settings dialog":", avra opziuns per ils suttitels",", opens subtitles settings dialog":", avra opziuns per ils suttitels",", opens descriptions settings dialog":", avra opziuns per la descripziun",", selected":", selecziunà","captions settings":"opziuns per ils suttitels","subtitles settings":"opziuns per ils suttitels","descriptions settings":"opziuns per la descripziun",Text:Wv,White:Kv,Black:Xv,Red:Yv,Green:Qv,Blue:Jv,Yellow:Zv,Magenta:eT,Cyan:tT,Background:iT,Window:sT,Transparent:rT,"Semi-Transparent":"Mez transparent",Opaque:nT,"Font Size":"Grandezza dal text","Text Edge Style":"Stil dal text",None:aT,Raised:oT,Depressed:lT,Uniform:uT,Dropshadow:cT,"Font Family":"Scrittira","Proportional Sans-Serif":"Proportionale Sans-Serif","Monospace Sans-Serif":"Monospace Sans-Serif","Proportional Serif":"Proportionale Serif","Monospace Serif":"Monospace Serif",Casual:dT,Script:hT,"Small Caps":"Bustabs pitschens",Reset:fT,"restore all settings to the default values":"Enavos tar las opziuns da standard",Done:pT,"Caption Settings Dialog":"Opziuns per suttitels","Beginning of dialog window. Escape will cancel and close the window.":"Entschatta da la fanestra da dialog. Escape stizza e serra la fanestra.","End of dialog window.":"Fin da la fanestra da dialog.",AGERATING12:mT,AGERATING18:gT,COMMERCIAL:yT,ENDDATE:_T,GEOBLOCK:vT,JOURNALISTIC:TT,LEGAL:bT,STARTDATE:ST,UNKNOWN:xT},vI=Object.freeze({__proto__:null,AGERATING12:mT,AGERATING18:gT,Background:iT,Black:Xv,Blue:Jv,COMMERCIAL:yT,Captions:Hv,Casual:dT,Chapters:Vv,Close:Gv,Cyan:tT,Depressed:lT,Descriptions:zv,Done:pT,Dropshadow:cT,Duration:Nv,ENDDATE:_T,Fullscreen:Uv,GEOBLOCK:vT,Green:Qv,JOURNALISTIC:TT,LEGAL:bT,LIVE:Mv,Loaded:Bv,Magenta:eT,Mute:$v,None:aT,Opaque:nT,Pause:Ov,Play:Lv,Progress:Fv,Raised:oT,Red:Yv,Replay:Rv,Reset:fT,STARTDATE:ST,Script:hT,Subtitles:qv,Text:Wv,Transparent:rT,UNKNOWN:xT,Uniform:uT,Unmute:jv,White:Kv,Window:sT,Yellow:Zv,default:_I});he.addLanguage("rm",Me({},vI));const TI=["url","mimeType","keySystems"],bI=["src"];class J{static addBlockedSegments(e,t=[]){const i="srgssr-blocked-segments",r=e.textTracks().getTrackById(i);if(r&&e.textTracks().removeTrack(r),!Array.isArray(t)||!t.length)return;const n=t.filter(a=>a.blockReason);n.length&&J.createTextTrack(e,i).then(a=>{n.forEach(o=>{J.addTextTrackCue(a,o)}),e.textTracks().addTrack(a)})}static addRemoteTextTracks(e,t=[]){Array.isArray(t)&&t.forEach(({type:i,language:r,locale:n,url:a})=>{e.addRemoteTextTrack({kind:i==="SDH"?"captions":"subtitles",label:r,language:n,src:a})})}static addTextTrackCue(e,t){const i=(Number.isFinite(t.markIn)?t.markIn:t.fullLengthMarkIn)/1e3,r=(Number.isFinite(t.markOut)?t.markOut:t.fullLengthMarkOut)/1e3;e.addCue(new VTTCue(i,r,JSON.stringify(t)))}static addTextTracks(e,{mediaData:t}){J.addRemoteTextTracks(e,t.subtitles),J.addChapters(e,t.urn,t.chapters),J.addBlockedSegments(e,t.blockedSegments),J.addIntervals(e,t.intervals)}static addChapters(e,t,i=[]){const r="srgssr-chapters",n=e.textTracks().getTrackById(r);n&&e.textTracks().removeTrack(n),!(!Array.isArray(i)||!i.length)&&J.createTextTrack(e,r).then(a=>{i.forEach(o=>{t===o.fullLengthUrn&&J.addTextTrackCue(a,o)}),e.textTracks().addTrack(a)})}static addIntervals(e,t=[]){const i="srgssr-intervals",r=e.textTracks().getTrackById(i);r&&e.textTracks().removeTrack(r),!(!Array.isArray(t)||!t.length)&&J.createTextTrack(e,i).then(n=>{t.forEach(a=>{J.addTextTrackCue(n,a)}),e.textTracks().addTrack(n)})}static blockingReason(e,t){if(!t.mediaData.blockReason)return;const i=e.localize(t.mediaData.blockReason);return J.error(e,{code:MediaError.MEDIA_ERR_ABORTED,message:i,metadata:{errorType:t.mediaData.blockReason,src:t}}),!0}static composeAkamaiResources(e=[]){return gs(function*(){return Xi.hasToken(e)?Xi.tokenizeSources(e):Promise.resolve(e)})()}static composeKeySystemsResources(e=[]){return Jr.hasDrm(e)?e.map(i=>Me(Me({},i),Jr.buildKeySystems(i.drmList))):e}static composeMainResources(e){return J.composeAkamaiResources(J.composeKeySystemsResources(J.filterIncompatibleResources(e.getMainResources())))}static composeSrcMediaData({mediaData:e,disableTrackers:t},i){const r=he.obj.merge(i,e),{url:n,mimeType:a,keySystems:o}=r,u=tf(r,TI);return{src:n,type:a,keySystems:o,disableTrackers:t,mediaData:u}}static createTextTrack(e,t){return new Promise(i=>{setTimeout(()=>{i(new he.TextTrack({id:t,kind:"metadata",label:t,tech:e.tech(!0)}))},100)})}static cuechangeEventProxy(e){e.textTracks().on("addtrack",({track:t})=>{["srgssr-chapters","srgssr-intervals"].includes(t.id)&&t.on("cuechange",()=>{const[i]=Array.from(t.activeCues),r=t.id.includes("srgssr-chapters")?"srgssr/chapter":"srgssr/interval";e.trigger({type:r,data:i})})})}static dataProvider(e){if(!e.options().srgOptions.dataProvider){const{dataProviderHost:t,dataProviderUrlHandler:i}=e.options().srgOptions,n=new sf(t).handleRequest(i);e.options({srgOptions:{dataProvider:n}})}return e.options().srgOptions.dataProvider}static dataProviderError(e,t){if(!t)return;const i=t.statusText?t.statusText:t.message;return J.error(e,{code:0,message:e.localize("UNKNOWN"),metadata:{errorType:"UNKNOWN",urn:e.src(),status:t.status,statusText:i,url:t.url}}),!0}static error(e,{code:t,message:i,metadata:r}){e.error(null),e.error({code:t,message:i,metadata:r})}static filterIncompatibleResources(e=[]){return e.filter(t=>!["RTMP","HDS"].includes(t.streaming))}static getBlockedSegment(e){const i=e.textTracks().getTrackById("srgssr-blocked-segments");if(!i)return;const[r]=Array.from(i.activeCues);return r}static getBlockedSegmentByTime(e,t){const i=J.getBlockedSegment(e);return i&&t>=i.startTime&&tr===t)||e[0]}static getSrcMediaObj(e,t){return gs(function*(){J.pillarboxMonitoring(e)&&J.pillarboxMonitoring(e).sessionStart();const{src:i}=t,r=tf(t,bI),n=yield J.getMediaComposition(i,J.dataProvider(e)),a=yield J.composeMainResources(n),o=J.getMediaData(a);return J.composeSrcMediaData(r,o)})()}static handleCurrentTime(e,t){const i=J.getBlockedSegmentByTime(e,t);if(!i||!Number.isFinite(i.endTime))return t;const r=i.endTime+.1;return e.trigger({type:"srgssr/blocked-segment",data:i}),e.currentTime(r),r}static handleSetCurrentTime(e,t){const{endTime:i}=J.getBlockedSegmentByTime(e,t)||{};return Number.isFinite(i)?i:t}static handleSetSource(e,t,i){return gs(function*(){try{const r=yield J.getSrcMediaObj(e,t);return J.srgAnalytics(e),J.updateTitleBar(e,r),J.updatePoster(e,r),J.blockingReason(e,r)?void 0:(J.addTextTracks(e,r),i(null,r))}catch(r){return J.dataProviderError(e,r)?void 0:i(r)}})()}static srgAnalytics(e){if(e.options().trackers.srgAnalytics!==!1&&!e.options().trackers.srgAnalytics){const t=new Fi(e,{debug:e.debug(),playerVersion:he.VERSION.pillarbox,tagCommanderScriptURL:e.options().srgOptions.tagCommanderScriptURL});e.options({trackers:{srgAnalytics:t}})}}static pillarboxMonitoring(e){if(e.options().trackers.pillarboxMonitoring!==!1){if(!e.options().trackers.pillarboxMonitoring){const t=new Ie(e,{debug:e.debug(),playerVersion:he.VERSION.pillarbox,playerName:"Pillarbox"});e.options({trackers:{pillarboxMonitoring:t}})}return e.options().trackers.pillarboxMonitoring}}static updatePoster(e,t,i=Jk){e.poster(i.scale({url:t.mediaData.imageUrl}))}static updateTitleBar(e,t){e.titleBar&&e.titleBar.update({title:t.mediaData.vendor,description:t.mediaData.title})}static middleware(e){return J.pillarboxMonitoring(e),J.cuechangeEventProxy(e),{currentTime:t=>J.handleCurrentTime(e,t),setCurrentTime:t=>J.handleSetCurrentTime(e,t),setSource:function(){var t=gs(function*(i,r){return J.handleSetSource(e,i,r)});return function(r,n){return t.apply(this,arguments)}}()}}}he.use("srgssr/urn",J.middleware);he.options.srgOptions={dataProvider:void 0,dataProviderHost:void 0,dataProviderUrlHandler:void 0,tagCommanderScriptURL:void 0};/**
+ * @license
+ * Copyright 2017 Google LLC
+ * SPDX-License-Identifier: BSD-3-Clause
+ */const SI={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},ET=s=>(...e)=>({_$litDirective$:s,values:e});class xI{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}/**
+ * @license
+ * Copyright 2017 Google LLC
+ * SPDX-License-Identifier: BSD-3-Clause
+ */class Ba extends xI{constructor(e){if(super(e),this.it=Oe,e.type!==SI.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===Oe||e==null)return this._t=void 0,this.it=e;if(e===Qi)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;const t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}}Ba.directiveName="unsafeHTML",Ba.resultType=1;const OI=ET(Ba);var tn,Kl,sn;class Wl extends Ss{constructor(){super();we(this,tn);we(this,sn,t=>{t.preventDefault();const i=new URL(`${window.location.origin}/${this.href}`),r=Object.fromEntries(i.searchParams.entries());Vo.navigateTo(i.pathname,r)});Vo.addEventListener("routechanged",()=>{Fe(this,tn,Kl).call(this)})}connectedCallback(){super.connectedCallback(),Fe(this,tn,Kl).call(this),this.addEventListener("click",U(this,sn))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("click",U(this,sn))}render(){return yf`
+
+
+
+ `}}tn=new WeakSet,Kl=function(){const t=new URL(`${window.location.origin}/${this.href}`);this.selected=Vo.isActiveRoute(t.pathname)},sn=new WeakMap,be(Wl,"properties",{href:{type:String},title:{type:String},selected:{type:Boolean,state:!0}}),be(Wl,"styles",[vf,o1]);customElements.define("route-link",Wl);const EI=`
+
+
+`,CI=""+new URL("srgssr-logo-DTU79MZS.png",import.meta.url).href;/**
+ * @license
+ * Copyright 2017 Google LLC
+ * SPDX-License-Identifier: BSD-3-Clause
+ */class Xl extends Ba{}Xl.directiveName="unsafeSVG",Xl.resultType=2;const AI=ET(Xl),wI="header{display:flex;align-items:baseline;justify-content:space-between;width:100%;margin:var(--size-4) 0}h1{display:flex;gap:.15em;align-items:center;margin:0}.pbw-logo{height:var(--size-7)}.github-link{display:flex;align-items:center}.github-icon{fill:var(--color-5)}.github-icon:hover{fill:var(--color-2)}.header-end{display:flex;align-items:center}";class CT extends Ss{render(){return yf`
+
+
+
+ Pillarbox
+
+
+ `}}be(CT,"styles",[vf,Fa(wI)]);customElements.define("core-demo-header",CT);export{J as S,Qi as T,o1 as a,Fa as b,Vo as c,SI as d,ET as e,II as f,Gs as g,xI as i,OI as o,he as p,Ss as r,vf as t,O as v,yf as x};
+//# sourceMappingURL=core-demo-header-component-CgCcolrg.js.map
diff --git a/pr-preview/pr-42/assets/core-demo-header-component-CgCcolrg.js.map b/pr-preview/pr-42/assets/core-demo-header-component-CgCcolrg.js.map
new file mode 100644
index 0000000..2f0948d
--- /dev/null
+++ b/pr-preview/pr-42/assets/core-demo-header-component-CgCcolrg.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"core-demo-header-component-CgCcolrg.js","sources":["../../node_modules/@lit/reactive-element/css-tag.js","../../node_modules/@lit/reactive-element/reactive-element.js","../../node_modules/lit-html/lit-html.js","../../node_modules/lit-element/lit-element.js","../../src/theme/theme.js","../../node_modules/balanced-match/index.js","../../node_modules/brace-expansion/index.js","../../node_modules/minimatch/dist/esm/assert-valid-pattern.js","../../node_modules/minimatch/dist/esm/brace-expressions.js","../../node_modules/minimatch/dist/esm/unescape.js","../../node_modules/minimatch/dist/esm/ast.js","../../node_modules/minimatch/dist/esm/escape.js","../../node_modules/minimatch/dist/esm/index.js","../../src/router/router.js","../../node_modules/global/window.js","../../__vite-browser-external","../../node_modules/global/document.js","../../node_modules/@babel/runtime/helpers/esm/extends.js","../../node_modules/is-function/index.js","../../node_modules/@videojs/xhr/lib/interceptors.js","../../node_modules/@videojs/xhr/lib/retry.js","../../node_modules/@videojs/xhr/lib/http-handler.js","../../node_modules/@videojs/xhr/lib/index.js","../../node_modules/videojs-vtt.js/lib/vtt.js","../../node_modules/videojs-vtt.js/lib/vttcue.js","../../node_modules/videojs-vtt.js/lib/vttregion.js","../../node_modules/videojs-vtt.js/lib/browser-index.js","../../node_modules/@videojs/vhs-utils/es/resolve-url.js","../../node_modules/@videojs/vhs-utils/es/stream.js","../../node_modules/@videojs/vhs-utils/es/decode-b64-to-uint8-array.js","../../node_modules/m3u8-parser/dist/m3u8-parser.es.js","../../node_modules/@videojs/vhs-utils/es/codecs.js","../../node_modules/@videojs/vhs-utils/es/media-types.js","../../node_modules/@videojs/vhs-utils/es/byte-helpers.js","../../node_modules/@videojs/vhs-utils/es/media-groups.js","../../node_modules/@xmldom/xmldom/lib/conventions.js","../../node_modules/@xmldom/xmldom/lib/dom.js","../../node_modules/@xmldom/xmldom/lib/entities.js","../../node_modules/@xmldom/xmldom/lib/sax.js","../../node_modules/@xmldom/xmldom/lib/dom-parser.js","../../node_modules/@xmldom/xmldom/lib/index.js","../../node_modules/mpd-parser/dist/mpd-parser.es.js","../../node_modules/mux.js/lib/utils/numbers.js","../../node_modules/mux.js/lib/tools/parse-sidx.js","../../node_modules/@videojs/vhs-utils/es/id3-helpers.js","../../node_modules/@videojs/vhs-utils/es/mp4-helpers.js","../../node_modules/@videojs/vhs-utils/es/ebml-helpers.js","../../node_modules/@videojs/vhs-utils/es/nal-helpers.js","../../node_modules/@videojs/vhs-utils/es/containers.js","../../node_modules/mux.js/lib/utils/clock.js","../../node_modules/video.js/dist/video.es.js","../../node_modules/videojs-contrib-eme/dist/videojs-contrib-eme.es.js","../../node_modules/@srgssr/pillarbox-web/dist/pillarbox.es.js","../../node_modules/lit-html/directive.js","../../node_modules/lit-html/directives/unsafe-html.js","../../src/router/route-link-component.js","../../img/github-logo.svg?raw","../../img/srgssr-logo.png","../../node_modules/lit-html/directives/unsafe-svg.js","../../src/layout/header/core-demo-header-component.js"],"sourcesContent":["/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=globalThis,e=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&\"adoptedStyleSheets\"in Document.prototype&&\"replace\"in CSSStyleSheet.prototype,s=Symbol(),o=new WeakMap;class n{constructor(t,e,o){if(this._$cssResult$=!0,o!==s)throw Error(\"CSSResult is not constructable. Use `unsafeCSS` or `css` instead.\");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const s=this.t;if(e&&void 0===t){const e=void 0!==s&&1===s.length;e&&(t=o.get(s)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),e&&o.set(s,t))}return t}toString(){return this.cssText}}const r=t=>new n(\"string\"==typeof t?t:t+\"\",void 0,s),i=(t,...e)=>{const o=1===t.length?t[0]:e.reduce(((e,s,o)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if(\"number\"==typeof t)return t;throw Error(\"Value passed to 'css' function must be a 'css' function result: \"+t+\". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.\")})(s)+t[o+1]),t[0]);return new n(o,t,s)},S=(s,o)=>{if(e)s.adoptedStyleSheets=o.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet));else for(const e of o){const o=document.createElement(\"style\"),n=t.litNonce;void 0!==n&&o.setAttribute(\"nonce\",n),o.textContent=e.cssText,s.appendChild(o)}},c=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e=\"\";for(const s of t.cssRules)e+=s.cssText;return r(e)})(t):t;export{n as CSSResult,S as adoptStyles,i as css,c as getCompatibleStyle,e as supportsAdoptingStyleSheets,r as unsafeCSS};\n//# sourceMappingURL=css-tag.js.map\n","import{getCompatibleStyle as t,adoptStyles as s}from\"./css-tag.js\";export{CSSResult,adoptStyles,css,getCompatibleStyle,supportsAdoptingStyleSheets,unsafeCSS}from\"./css-tag.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const{is:i,defineProperty:e,getOwnPropertyDescriptor:r,getOwnPropertyNames:h,getOwnPropertySymbols:o,getPrototypeOf:n}=Object,a=globalThis,c=a.trustedTypes,l=c?c.emptyScript:\"\",p=a.reactiveElementPolyfillSupport,d=(t,s)=>t,u={toAttribute(t,s){switch(s){case Boolean:t=t?l:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,s){let i=t;switch(s){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},f=(t,s)=>!i(t,s),y={attribute:!0,type:String,converter:u,reflect:!1,hasChanged:f};Symbol.metadata??=Symbol(\"metadata\"),a.litPropertyMetadata??=new WeakMap;class b extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,s=y){if(s.state&&(s.attribute=!1),this._$Ei(),this.elementProperties.set(t,s),!s.noAccessor){const i=Symbol(),r=this.getPropertyDescriptor(t,i,s);void 0!==r&&e(this.prototype,t,r)}}static getPropertyDescriptor(t,s,i){const{get:e,set:h}=r(this.prototype,t)??{get(){return this[s]},set(t){this[s]=t}};return{get(){return e?.call(this)},set(s){const r=e?.call(this);h.call(this,s),this.requestUpdate(t,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??y}static _$Ei(){if(this.hasOwnProperty(d(\"elementProperties\")))return;const t=n(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(d(\"finalized\")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(d(\"properties\"))){const t=this.properties,s=[...h(t),...o(t)];for(const i of s)this.createProperty(i,t[i])}const t=this[Symbol.metadata];if(null!==t){const s=litPropertyMetadata.get(t);if(void 0!==s)for(const[t,i]of s)this.elementProperties.set(t,i)}this._$Eh=new Map;for(const[t,s]of this.elementProperties){const i=this._$Eu(t,s);void 0!==i&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(s){const i=[];if(Array.isArray(s)){const e=new Set(s.flat(1/0).reverse());for(const s of e)i.unshift(t(s))}else void 0!==s&&i.push(t(s));return i}static _$Eu(t,s){const i=s.attribute;return!1===i?void 0:\"string\"==typeof i?i:\"string\"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,s=this.constructor.elementProperties;for(const i of s.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return s(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,s,i){this._$AK(t,i)}_$EC(t,s){const i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(void 0!==e&&!0===i.reflect){const r=(void 0!==i.converter?.toAttribute?i.converter:u).toAttribute(s,i.type);this._$Em=t,null==r?this.removeAttribute(e):this.setAttribute(e,r),this._$Em=null}}_$AK(t,s){const i=this.constructor,e=i._$Eh.get(t);if(void 0!==e&&this._$Em!==e){const t=i.getPropertyOptions(e),r=\"function\"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:u;this._$Em=e,this[e]=r.fromAttribute(s,t.type),this._$Em=null}}requestUpdate(t,s,i){if(void 0!==t){if(i??=this.constructor.getPropertyOptions(t),!(i.hasChanged??f)(this[t],s))return;this.P(t,s,i)}!1===this.isUpdatePending&&(this._$ES=this._$ET())}P(t,s,i){this._$AL.has(t)||this._$AL.set(t,s),!0===i.reflect&&this._$Em!==t&&(this._$Ej??=new Set).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,s]of this._$Ep)this[t]=s;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[s,i]of t)!0!==i.wrapped||this._$AL.has(s)||void 0===this[s]||this.P(s,this[s],i)}let t=!1;const s=this._$AL;try{t=this.shouldUpdate(s),t?(this.willUpdate(s),this._$EO?.forEach((t=>t.hostUpdate?.())),this.update(s)):this._$EU()}catch(s){throw t=!1,this._$EU(),s}t&&this._$AE(s)}willUpdate(t){}_$AE(t){this._$EO?.forEach((t=>t.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&=this._$Ej.forEach((t=>this._$EC(t,this[t]))),this._$EU()}updated(t){}firstUpdated(t){}}b.elementStyles=[],b.shadowRootOptions={mode:\"open\"},b[d(\"elementProperties\")]=new Map,b[d(\"finalized\")]=new Map,p?.({ReactiveElement:b}),(a.reactiveElementVersions??=[]).push(\"2.0.4\");export{b as ReactiveElement,u as defaultConverter,f as notEqual};\n//# sourceMappingURL=reactive-element.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=globalThis,i=t.trustedTypes,s=i?i.createPolicy(\"lit-html\",{createHTML:t=>t}):void 0,e=\"$lit$\",h=`lit$${Math.random().toFixed(9).slice(2)}$`,o=\"?\"+h,n=`<${o}>`,r=document,l=()=>r.createComment(\"\"),c=t=>null===t||\"object\"!=typeof t&&\"function\"!=typeof t,a=Array.isArray,u=t=>a(t)||\"function\"==typeof t?.[Symbol.iterator],d=\"[ \\t\\n\\f\\r]\",f=/<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g,v=/-->/g,_=/>/g,m=RegExp(`>|${d}(?:([^\\\\s\"'>=/]+)(${d}*=${d}*(?:[^ \\t\\n\\f\\r\"'\\`<>=]|(\"|')|))|$)`,\"g\"),p=/'/g,g=/\"/g,$=/^(?:script|style|textarea|title)$/i,y=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),x=y(1),b=y(2),w=y(3),T=Symbol.for(\"lit-noChange\"),E=Symbol.for(\"lit-nothing\"),A=new WeakMap,C=r.createTreeWalker(r,129);function P(t,i){if(!a(t)||!t.hasOwnProperty(\"raw\"))throw Error(\"invalid template strings array\");return void 0!==s?s.createHTML(i):i}const V=(t,i)=>{const s=t.length-1,o=[];let r,l=2===i?\"\":3===i?\"\":\"\",c=f;for(let i=0;i\"===u[0]?(c=r??f,d=-1):void 0===u[1]?d=-2:(d=c.lastIndex-u[2].length,a=u[1],c=void 0===u[3]?m:'\"'===u[3]?g:p):c===g||c===p?c=m:c===v||c===_?c=f:(c=m,r=void 0);const x=c===m&&t[i+1].startsWith(\"/>\")?\" \":\"\";l+=c===f?s+n:d>=0?(o.push(a),s.slice(0,d)+e+s.slice(d)+h+x):s+h+(-2===d?i:x)}return[P(t,l+(t[s]||\">\")+(2===i?\" \":3===i?\"\":\"\")),o]};class N{constructor({strings:t,_$litType$:s},n){let r;this.parts=[];let c=0,a=0;const u=t.length-1,d=this.parts,[f,v]=V(t,s);if(this.el=N.createElement(f,n),C.currentNode=this.el.content,2===s||3===s){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(r=C.nextNode())&&d.length0){r.textContent=i?i.emptyScript:\"\";for(let i=0;i2||\"\"!==s[0]||\"\"!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=E}_$AI(t,i=this,s,e){const h=this.strings;let o=!1;if(void 0===h)t=S(this,t,i,0),o=!c(t)||t!==this._$AH&&t!==T,o&&(this._$AH=t);else{const e=t;let n,r;for(t=h[0],n=0;n{const e=s?.renderBefore??i;let h=e._$litPart$;if(void 0===h){const t=s?.renderBefore??null;e._$litPart$=h=new R(i.insertBefore(l(),t),t,void 0,s??{})}return h._$AI(t),h};export{Z as _$LH,x as html,w as mathml,T as noChange,E as nothing,B as render,b as svg};\n//# sourceMappingURL=lit-html.js.map\n","import{ReactiveElement as t}from\"@lit/reactive-element\";export*from\"@lit/reactive-element\";import{render as e,noChange as s}from\"lit-html\";export*from\"lit-html\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */class r extends t{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const s=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=e(s,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return s}}r._$litElement$=!0,r[\"finalized\"]=!0,globalThis.litElementHydrateSupport?.({LitElement:r});const i=globalThis.litElementPolyfillSupport;i?.({LitElement:r});const o={_$AK:(t,e,s)=>{t._$AK(e,s)},_$AL:t=>t._$AL};(globalThis.litElementVersions??=[]).push(\"4.1.1\");export{r as LitElement,o as _$LE};\n//# sourceMappingURL=lit-element.js.map\n","import themeCSS from './theme.scss?inline';\nimport animationsCSS from './animations.scss?inline';\nimport { unsafeCSS } from 'lit';\n\nexport const theme = unsafeCSS(themeCSS);\nexport const animations = unsafeCSS(animationsCSS);\n","'use strict';\nmodule.exports = balanced;\nfunction balanced(a, b, str) {\n if (a instanceof RegExp) a = maybeMatch(a, str);\n if (b instanceof RegExp) b = maybeMatch(b, str);\n\n var r = range(a, b, str);\n\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + a.length, r[1]),\n post: str.slice(r[1] + b.length)\n };\n}\n\nfunction maybeMatch(reg, str) {\n var m = str.match(reg);\n return m ? m[0] : null;\n}\n\nbalanced.range = range;\nfunction range(a, b, str) {\n var begs, beg, left, right, result;\n var ai = str.indexOf(a);\n var bi = str.indexOf(b, ai + 1);\n var i = ai;\n\n if (ai >= 0 && bi > 0) {\n if(a===b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n\n while (i >= 0 && !result) {\n if (i == ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length == 1) {\n result = [ begs.pop(), bi ];\n } else {\n beg = begs.pop();\n if (beg < left) {\n left = beg;\n right = bi;\n }\n\n bi = str.indexOf(b, i + 1);\n }\n\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n\n if (begs.length) {\n result = [ left, right ];\n }\n }\n\n return result;\n}\n","var balanced = require('balanced-match');\n\nmodule.exports = expandTop;\n\nvar escSlash = '\\0SLASH'+Math.random()+'\\0';\nvar escOpen = '\\0OPEN'+Math.random()+'\\0';\nvar escClose = '\\0CLOSE'+Math.random()+'\\0';\nvar escComma = '\\0COMMA'+Math.random()+'\\0';\nvar escPeriod = '\\0PERIOD'+Math.random()+'\\0';\n\nfunction numeric(str) {\n return parseInt(str, 10) == str\n ? parseInt(str, 10)\n : str.charCodeAt(0);\n}\n\nfunction escapeBraces(str) {\n return str.split('\\\\\\\\').join(escSlash)\n .split('\\\\{').join(escOpen)\n .split('\\\\}').join(escClose)\n .split('\\\\,').join(escComma)\n .split('\\\\.').join(escPeriod);\n}\n\nfunction unescapeBraces(str) {\n return str.split(escSlash).join('\\\\')\n .split(escOpen).join('{')\n .split(escClose).join('}')\n .split(escComma).join(',')\n .split(escPeriod).join('.');\n}\n\n\n// Basically just str.split(\",\"), but handling cases\n// where we have nested braced sections, which should be\n// treated as individual members, like {a,{b,c},d}\nfunction parseCommaParts(str) {\n if (!str)\n return [''];\n\n var parts = [];\n var m = balanced('{', '}', str);\n\n if (!m)\n return str.split(',');\n\n var pre = m.pre;\n var body = m.body;\n var post = m.post;\n var p = pre.split(',');\n\n p[p.length-1] += '{' + body + '}';\n var postParts = parseCommaParts(post);\n if (post.length) {\n p[p.length-1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n\n parts.push.apply(parts, p);\n\n return parts;\n}\n\nfunction expandTop(str) {\n if (!str)\n return [];\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.substr(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.substr(2);\n }\n\n return expand(escapeBraces(str), true).map(unescapeBraces);\n}\n\nfunction embrace(str) {\n return '{' + str + '}';\n}\nfunction isPadded(el) {\n return /^-?0\\d/.test(el);\n}\n\nfunction lte(i, y) {\n return i <= y;\n}\nfunction gte(i, y) {\n return i >= y;\n}\n\nfunction expand(str, isTop) {\n var expansions = [];\n\n var m = balanced('{', '}', str);\n if (!m) return [str];\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n var pre = m.pre;\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n\n if (/\\$$/.test(m.pre)) { \n for (var k = 0; k < post.length; k++) {\n var expansion = pre+ '{' + m.body + '}' + post[k];\n expansions.push(expansion);\n }\n } else {\n var isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n var isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n var isSequence = isNumericSequence || isAlphaSequence;\n var isOptions = m.body.indexOf(',') >= 0;\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,.*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post;\n return expand(str);\n }\n return [str];\n }\n\n var n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand(n[0], false).map(embrace);\n if (n.length === 1) {\n return post.map(function(p) {\n return m.pre + n[0] + p;\n });\n }\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n var N;\n\n if (isSequence) {\n var x = numeric(n[0]);\n var y = numeric(n[1]);\n var width = Math.max(n[0].length, n[1].length)\n var incr = n.length == 3\n ? Math.abs(numeric(n[2]))\n : 1;\n var test = lte;\n var reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n var pad = n.some(isPadded);\n\n N = [];\n\n for (var i = x; test(i, y); i += incr) {\n var c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === '\\\\')\n c = '';\n } else {\n c = String(i);\n if (pad) {\n var need = width - c.length;\n if (need > 0) {\n var z = new Array(need + 1).join('0');\n if (i < 0)\n c = '-' + z + c.slice(1);\n else\n c = z + c;\n }\n }\n }\n N.push(c);\n }\n } else {\n N = [];\n\n for (var j = 0; j < n.length; j++) {\n N.push.apply(N, expand(n[j], false));\n }\n }\n\n for (var j = 0; j < N.length; j++) {\n for (var k = 0; k < post.length; k++) {\n var expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion)\n expansions.push(expansion);\n }\n }\n }\n\n return expansions;\n}\n\n","const MAX_PATTERN_LENGTH = 1024 * 64;\nexport const assertValidPattern = (pattern) => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern');\n }\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long');\n }\n};\n//# sourceMappingURL=assert-valid-pattern.js.map","// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n// { : [, /u flag required, negated]\nconst posixClasses = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n '[:cntrl:]': ['\\\\p{Cc}', true],\n '[:digit:]': ['\\\\p{Nd}', true],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n '[:lower:]': ['\\\\p{Ll}', true],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}', true],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n '[:upper:]': ['\\\\p{Lu}', true],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n '[:xdigit:]': ['A-Fa-f0-9', false],\n};\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s) => s.replace(/[[\\]\\\\-]/g, '\\\\$&');\n// escape all regexp magic characters\nconst regexpEscape = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges) => ranges.join('');\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (glob, position) => {\n const pos = position;\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression');\n }\n /* c8 ignore stop */\n const ranges = [];\n const negs = [];\n let i = pos + 1;\n let sawStart = false;\n let uflag = false;\n let escaping = false;\n let negate = false;\n let endPos = pos;\n let rangeStart = '';\n WHILE: while (i < glob.length) {\n const c = glob.charAt(i);\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true;\n i++;\n continue;\n }\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1;\n break;\n }\n sawStart = true;\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true;\n i++;\n continue;\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return ['$.', false, glob.length - pos, true];\n }\n i += cls.length;\n if (neg)\n negs.push(unip);\n else\n ranges.push(unip);\n uflag = uflag || u;\n continue WHILE;\n }\n }\n }\n // now it's just a normal character, effectively\n escaping = false;\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (c > rangeStart) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));\n }\n else if (c === rangeStart) {\n ranges.push(braceEscape(c));\n }\n rangeStart = '';\n i++;\n continue;\n }\n // now might be the start of a range.\n // can be either c-d or c-] or c] or c] at this point\n if (glob.startsWith('-]', i + 1)) {\n ranges.push(braceEscape(c + '-'));\n i += 2;\n continue;\n }\n if (glob.startsWith('-', i + 1)) {\n rangeStart = c;\n i += 2;\n continue;\n }\n // not the start of a range, just a single character\n ranges.push(braceEscape(c));\n i++;\n }\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return ['', false, 0, false];\n }\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return ['$.', false, glob.length - pos, true];\n }\n // if we got one positive range, and it's a single character, then that's\n // not actually a magic pattern, it's just that one literal character.\n // we should not treat that as \"magic\", we should just return the literal\n // character. [_] is a perfectly valid way to escape glob magic chars.\n if (negs.length === 0 &&\n ranges.length === 1 &&\n /^\\\\?.$/.test(ranges[0]) &&\n !negate) {\n const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];\n return [regexpEscape(r), false, endPos - pos, false];\n }\n const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';\n const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';\n const comb = ranges.length && negs.length\n ? '(' + sranges + '|' + snegs + ')'\n : ranges.length\n ? sranges\n : snegs;\n return [comb, uflag, endPos - pos, true];\n};\n//# sourceMappingURL=brace-expressions.js.map","/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link windowsPathsNoEscape} option is used, then square-brace\n * escapes are removed, but not backslash escapes. For example, it will turn\n * the string `'[*]'` into `*`, but it will not turn `'\\\\*'` into `'*'`,\n * becuase `\\` is a path separator in `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both brace escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n */\nexport const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {\n return windowsPathsNoEscape\n ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2').replace(/\\\\([^\\/])/g, '$1');\n};\n//# sourceMappingURL=unescape.js.map","// parse a single path portion\nimport { parseClass } from './brace-expressions.js';\nimport { unescape } from './unescape.js';\nconst types = new Set(['!', '?', '+', '*', '@']);\nconst isExtglobType = (c) => types.has(c);\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))';\nconst startNoDot = '(?!\\\\.)';\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.']);\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.']);\nconst reSpecials = new Set('().*{}+?[]^$\\\\!');\nconst regExpEscape = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n// any single thing other than /\nconst qmark = '[^/]';\n// * => any number of characters\nconst star = qmark + '*?';\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?';\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\nexport class AST {\n type;\n #root;\n #hasMagic;\n #uflag = false;\n #parts = [];\n #parent;\n #parentIndex;\n #negs;\n #filledNegs = false;\n #options;\n #toString;\n // set to true if it's an extglob with no children\n // (which really means one child of '')\n #emptyExt = false;\n constructor(type, parent, options = {}) {\n this.type = type;\n // extglobs are inherently magical\n if (type)\n this.#hasMagic = true;\n this.#parent = parent;\n this.#root = this.#parent ? this.#parent.#root : this;\n this.#options = this.#root === this ? options : this.#root.#options;\n this.#negs = this.#root === this ? [] : this.#root.#negs;\n if (type === '!' && !this.#root.#filledNegs)\n this.#negs.push(this);\n this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;\n }\n get hasMagic() {\n /* c8 ignore start */\n if (this.#hasMagic !== undefined)\n return this.#hasMagic;\n /* c8 ignore stop */\n for (const p of this.#parts) {\n if (typeof p === 'string')\n continue;\n if (p.type || p.hasMagic)\n return (this.#hasMagic = true);\n }\n // note: will be undefined until we generate the regexp src and find out\n return this.#hasMagic;\n }\n // reconstructs the pattern\n toString() {\n if (this.#toString !== undefined)\n return this.#toString;\n if (!this.type) {\n return (this.#toString = this.#parts.map(p => String(p)).join(''));\n }\n else {\n return (this.#toString =\n this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');\n }\n }\n #fillNegs() {\n /* c8 ignore start */\n if (this !== this.#root)\n throw new Error('should only call on root');\n if (this.#filledNegs)\n return this;\n /* c8 ignore stop */\n // call toString() once to fill this out\n this.toString();\n this.#filledNegs = true;\n let n;\n while ((n = this.#negs.pop())) {\n if (n.type !== '!')\n continue;\n // walk up the tree, appending everthing that comes AFTER parentIndex\n let p = n;\n let pp = p.#parent;\n while (pp) {\n for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {\n for (const part of n.#parts) {\n /* c8 ignore start */\n if (typeof part === 'string') {\n throw new Error('string part in extglob AST??');\n }\n /* c8 ignore stop */\n part.copyIn(pp.#parts[i]);\n }\n }\n p = pp;\n pp = p.#parent;\n }\n }\n return this;\n }\n push(...parts) {\n for (const p of parts) {\n if (p === '')\n continue;\n /* c8 ignore start */\n if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {\n throw new Error('invalid part: ' + p);\n }\n /* c8 ignore stop */\n this.#parts.push(p);\n }\n }\n toJSON() {\n const ret = this.type === null\n ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))\n : [this.type, ...this.#parts.map(p => p.toJSON())];\n if (this.isStart() && !this.type)\n ret.unshift([]);\n if (this.isEnd() &&\n (this === this.#root ||\n (this.#root.#filledNegs && this.#parent?.type === '!'))) {\n ret.push({});\n }\n return ret;\n }\n isStart() {\n if (this.#root === this)\n return true;\n // if (this.type) return !!this.#parent?.isStart()\n if (!this.#parent?.isStart())\n return false;\n if (this.#parentIndex === 0)\n return true;\n // if everything AHEAD of this is a negation, then it's still the \"start\"\n const p = this.#parent;\n for (let i = 0; i < this.#parentIndex; i++) {\n const pp = p.#parts[i];\n if (!(pp instanceof AST && pp.type === '!')) {\n return false;\n }\n }\n return true;\n }\n isEnd() {\n if (this.#root === this)\n return true;\n if (this.#parent?.type === '!')\n return true;\n if (!this.#parent?.isEnd())\n return false;\n if (!this.type)\n return this.#parent?.isEnd();\n // if not root, it'll always have a parent\n /* c8 ignore start */\n const pl = this.#parent ? this.#parent.#parts.length : 0;\n /* c8 ignore stop */\n return this.#parentIndex === pl - 1;\n }\n copyIn(part) {\n if (typeof part === 'string')\n this.push(part);\n else\n this.push(part.clone(this));\n }\n clone(parent) {\n const c = new AST(this.type, parent);\n for (const p of this.#parts) {\n c.copyIn(p);\n }\n return c;\n }\n static #parseAST(str, ast, pos, opt) {\n let escaping = false;\n let inBrace = false;\n let braceStart = -1;\n let braceNeg = false;\n if (ast.type === null) {\n // outside of a extglob, append until we find a start\n let i = pos;\n let acc = '';\n while (i < str.length) {\n const c = str.charAt(i++);\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping;\n acc += c;\n continue;\n }\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true;\n }\n }\n else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false;\n }\n acc += c;\n continue;\n }\n else if (c === '[') {\n inBrace = true;\n braceStart = i;\n braceNeg = false;\n acc += c;\n continue;\n }\n if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {\n ast.push(acc);\n acc = '';\n const ext = new AST(c, ast);\n i = AST.#parseAST(str, ext, i, opt);\n ast.push(ext);\n continue;\n }\n acc += c;\n }\n ast.push(acc);\n return i;\n }\n // some kind of extglob, pos is at the (\n // find the next | or )\n let i = pos + 1;\n let part = new AST(null, ast);\n const parts = [];\n let acc = '';\n while (i < str.length) {\n const c = str.charAt(i++);\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping;\n acc += c;\n continue;\n }\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true;\n }\n }\n else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false;\n }\n acc += c;\n continue;\n }\n else if (c === '[') {\n inBrace = true;\n braceStart = i;\n braceNeg = false;\n acc += c;\n continue;\n }\n if (isExtglobType(c) && str.charAt(i) === '(') {\n part.push(acc);\n acc = '';\n const ext = new AST(c, part);\n part.push(ext);\n i = AST.#parseAST(str, ext, i, opt);\n continue;\n }\n if (c === '|') {\n part.push(acc);\n acc = '';\n parts.push(part);\n part = new AST(null, ast);\n continue;\n }\n if (c === ')') {\n if (acc === '' && ast.#parts.length === 0) {\n ast.#emptyExt = true;\n }\n part.push(acc);\n acc = '';\n ast.push(...parts, part);\n return i;\n }\n acc += c;\n }\n // unfinished extglob\n // if we got here, it was a malformed extglob! not an extglob, but\n // maybe something else in there.\n ast.type = null;\n ast.#hasMagic = undefined;\n ast.#parts = [str.substring(pos - 1)];\n return i;\n }\n static fromGlob(pattern, options = {}) {\n const ast = new AST(null, undefined, options);\n AST.#parseAST(pattern, ast, 0, options);\n return ast;\n }\n // returns the regular expression if there's magic, or the unescaped\n // string if not.\n toMMPattern() {\n // should only be called on root\n /* c8 ignore start */\n if (this !== this.#root)\n return this.#root.toMMPattern();\n /* c8 ignore stop */\n const glob = this.toString();\n const [re, body, hasMagic, uflag] = this.toRegExpSource();\n // if we're in nocase mode, and not nocaseMagicOnly, then we do\n // still need a regular expression if we have to case-insensitively\n // match capital/lowercase characters.\n const anyMagic = hasMagic ||\n this.#hasMagic ||\n (this.#options.nocase &&\n !this.#options.nocaseMagicOnly &&\n glob.toUpperCase() !== glob.toLowerCase());\n if (!anyMagic) {\n return body;\n }\n const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');\n return Object.assign(new RegExp(`^${re}$`, flags), {\n _src: re,\n _glob: glob,\n });\n }\n get options() {\n return this.#options;\n }\n // returns the string match, the regexp source, whether there's magic\n // in the regexp (so a regular expression is required) and whether or\n // not the uflag is needed for the regular expression (for posix classes)\n // TODO: instead of injecting the start/end at this point, just return\n // the BODY of the regexp, along with the start/end portions suitable\n // for binding the start/end in either a joined full-path makeRe context\n // (where we bind to (^|/), or a standalone matchPart context (where\n // we bind to ^, and not /). Otherwise slashes get duped!\n //\n // In part-matching mode, the start is:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n // - if dots allowed or not possible: ^\n // - if dots possible and not allowed: ^(?!\\.)\n // end is:\n // - if not isEnd(): nothing\n // - else: $\n //\n // In full-path matching mode, we put the slash at the START of the\n // pattern, so start is:\n // - if first pattern: same as part-matching mode\n // - if not isStart(): nothing\n // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n // - if dots allowed or not possible: /\n // - if dots possible and not allowed: /(?!\\.)\n // end is:\n // - if last pattern, same as part-matching mode\n // - else nothing\n //\n // Always put the (?:$|/) on negated tails, though, because that has to be\n // there to bind the end of the negated pattern portion, and it's easier to\n // just stick it in now rather than try to inject it later in the middle of\n // the pattern.\n //\n // We can just always return the same end, and leave it up to the caller\n // to know whether it's going to be used joined or in parts.\n // And, if the start is adjusted slightly, can do the same there:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n // - if dots allowed or not possible: (?:/|^)\n // - if dots possible and not allowed: (?:/|^)(?!\\.)\n //\n // But it's better to have a simpler binding without a conditional, for\n // performance, so probably better to return both start options.\n //\n // Then the caller just ignores the end if it's not the first pattern,\n // and the start always gets applied.\n //\n // But that's always going to be $ if it's the ending pattern, or nothing,\n // so the caller can just attach $ at the end of the pattern when building.\n //\n // So the todo is:\n // - better detect what kind of start is needed\n // - return both flavors of starting pattern\n // - attach $ at the end of the pattern when creating the actual RegExp\n //\n // Ah, but wait, no, that all only applies to the root when the first pattern\n // is not an extglob. If the first pattern IS an extglob, then we need all\n // that dot prevention biz to live in the extglob portions, because eg\n // +(*|.x*) can match .xy but not .yx.\n //\n // So, return the two flavors if it's #root and the first child is not an\n // AST, otherwise leave it to the child AST to handle it, and there,\n // use the (?:^|/) style of start binding.\n //\n // Even simplified further:\n // - Since the start for a join is eg /(?!\\.) and the start for a part\n // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n // or start or whatever) and prepend ^ or / at the Regexp construction.\n toRegExpSource(allowDot) {\n const dot = allowDot ?? !!this.#options.dot;\n if (this.#root === this)\n this.#fillNegs();\n if (!this.type) {\n const noEmpty = this.isStart() && this.isEnd();\n const src = this.#parts\n .map(p => {\n const [re, _, hasMagic, uflag] = typeof p === 'string'\n ? AST.#parseGlob(p, this.#hasMagic, noEmpty)\n : p.toRegExpSource(allowDot);\n this.#hasMagic = this.#hasMagic || hasMagic;\n this.#uflag = this.#uflag || uflag;\n return re;\n })\n .join('');\n let start = '';\n if (this.isStart()) {\n if (typeof this.#parts[0] === 'string') {\n // this is the string that will match the start of the pattern,\n // so we need to protect against dots and such.\n // '.' and '..' cannot match unless the pattern is that exactly,\n // even if it starts with . or dot:true is set.\n const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);\n if (!dotTravAllowed) {\n const aps = addPatternStart;\n // check if we have a possibility of matching . or ..,\n // and prevent that.\n const needNoTrav = \n // dots are allowed, and the pattern starts with [ or .\n (dot && aps.has(src.charAt(0))) ||\n // the pattern starts with \\., and then [ or .\n (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n // the pattern starts with \\.\\., and then [ or .\n (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)));\n // no need to prevent dots if it can't match a dot, or if a\n // sub-pattern will be preventing it anyway.\n const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));\n start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';\n }\n }\n }\n // append the \"end of path portion\" pattern to negation tails\n let end = '';\n if (this.isEnd() &&\n this.#root.#filledNegs &&\n this.#parent?.type === '!') {\n end = '(?:$|\\\\/)';\n }\n const final = start + src + end;\n return [\n final,\n unescape(src),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ];\n }\n // We need to calculate the body *twice* if it's a repeat pattern\n // at the start, once in nodot mode, then again in dot mode, so a\n // pattern like *(?) can match 'x.y'\n const repeated = this.type === '*' || this.type === '+';\n // some kind of extglob\n const start = this.type === '!' ? '(?:(?!(?:' : '(?:';\n let body = this.#partsToRegExp(dot);\n if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n // invalid extglob, has to at least be *something* present, if it's\n // the entire path portion.\n const s = this.toString();\n this.#parts = [s];\n this.type = null;\n this.#hasMagic = undefined;\n return [s, unescape(this.toString()), false, false];\n }\n // XXX abstract out this map method\n let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot\n ? ''\n : this.#partsToRegExp(true);\n if (bodyDotAllowed === body) {\n bodyDotAllowed = '';\n }\n if (bodyDotAllowed) {\n body = `(?:${body})(?:${bodyDotAllowed})*?`;\n }\n // an empty !() is exactly equivalent to a starNoEmpty\n let final = '';\n if (this.type === '!' && this.#emptyExt) {\n final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;\n }\n else {\n const close = this.type === '!'\n ? // !() must match something,but !(x) can match ''\n '))' +\n (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n star +\n ')'\n : this.type === '@'\n ? ')'\n : this.type === '?'\n ? ')?'\n : this.type === '+' && bodyDotAllowed\n ? ')'\n : this.type === '*' && bodyDotAllowed\n ? `)?`\n : `)${this.type}`;\n final = start + body + close;\n }\n return [\n final,\n unescape(body),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ];\n }\n #partsToRegExp(dot) {\n return this.#parts\n .map(p => {\n // extglob ASTs should only contain parent ASTs\n /* c8 ignore start */\n if (typeof p === 'string') {\n throw new Error('string type in extglob ast??');\n }\n /* c8 ignore stop */\n // can ignore hasMagic, because extglobs are already always magic\n const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);\n this.#uflag = this.#uflag || uflag;\n return re;\n })\n .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n .join('|');\n }\n static #parseGlob(glob, hasMagic, noEmpty = false) {\n let escaping = false;\n let re = '';\n let uflag = false;\n for (let i = 0; i < glob.length; i++) {\n const c = glob.charAt(i);\n if (escaping) {\n escaping = false;\n re += (reSpecials.has(c) ? '\\\\' : '') + c;\n continue;\n }\n if (c === '\\\\') {\n if (i === glob.length - 1) {\n re += '\\\\\\\\';\n }\n else {\n escaping = true;\n }\n continue;\n }\n if (c === '[') {\n const [src, needUflag, consumed, magic] = parseClass(glob, i);\n if (consumed) {\n re += src;\n uflag = uflag || needUflag;\n i += consumed - 1;\n hasMagic = hasMagic || magic;\n continue;\n }\n }\n if (c === '*') {\n if (noEmpty && glob === '*')\n re += starNoEmpty;\n else\n re += star;\n hasMagic = true;\n continue;\n }\n if (c === '?') {\n re += qmark;\n hasMagic = true;\n continue;\n }\n re += regExpEscape(c);\n }\n return [re, unescape(glob), !!hasMagic, uflag];\n }\n}\n//# sourceMappingURL=ast.js.map","/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n */\nexport const escape = (s, { windowsPathsNoEscape = false, } = {}) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n return windowsPathsNoEscape\n ? s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&');\n};\n//# sourceMappingURL=escape.js.map","import expand from 'brace-expansion';\nimport { assertValidPattern } from './assert-valid-pattern.js';\nimport { AST } from './ast.js';\nimport { escape } from './escape.js';\nimport { unescape } from './unescape.js';\nexport const minimatch = (p, pattern, options = {}) => {\n assertValidPattern(pattern);\n // shortcut: comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n return false;\n }\n return new Minimatch(pattern, options).match(p);\n};\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?\\*\\[\\(]*)$/;\nconst starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);\nconst starDotExtTestDot = (ext) => (f) => f.endsWith(ext);\nconst starDotExtTestNocase = (ext) => {\n ext = ext.toLowerCase();\n return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);\n};\nconst starDotExtTestNocaseDot = (ext) => {\n ext = ext.toLowerCase();\n return (f) => f.toLowerCase().endsWith(ext);\n};\nconst starDotStarRE = /^\\*+\\.\\*+$/;\nconst starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');\nconst starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');\nconst dotStarRE = /^\\.\\*+$/;\nconst dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');\nconst starRE = /^\\*+$/;\nconst starTest = (f) => f.length !== 0 && !f.startsWith('.');\nconst starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';\nconst qmarksRE = /^\\?+([^+@!?\\*\\[\\(]*)?$/;\nconst qmarksTestNocase = ([$0, ext = '']) => {\n const noext = qmarksTestNoExt([$0]);\n if (!ext)\n return noext;\n ext = ext.toLowerCase();\n return (f) => noext(f) && f.toLowerCase().endsWith(ext);\n};\nconst qmarksTestNocaseDot = ([$0, ext = '']) => {\n const noext = qmarksTestNoExtDot([$0]);\n if (!ext)\n return noext;\n ext = ext.toLowerCase();\n return (f) => noext(f) && f.toLowerCase().endsWith(ext);\n};\nconst qmarksTestDot = ([$0, ext = '']) => {\n const noext = qmarksTestNoExtDot([$0]);\n return !ext ? noext : (f) => noext(f) && f.endsWith(ext);\n};\nconst qmarksTest = ([$0, ext = '']) => {\n const noext = qmarksTestNoExt([$0]);\n return !ext ? noext : (f) => noext(f) && f.endsWith(ext);\n};\nconst qmarksTestNoExt = ([$0]) => {\n const len = $0.length;\n return (f) => f.length === len && !f.startsWith('.');\n};\nconst qmarksTestNoExtDot = ([$0]) => {\n const len = $0.length;\n return (f) => f.length === len && f !== '.' && f !== '..';\n};\n/* c8 ignore start */\nconst defaultPlatform = (typeof process === 'object' && process\n ? (typeof process.env === 'object' &&\n process.env &&\n process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n process.platform\n : 'posix');\nconst path = {\n win32: { sep: '\\\\' },\n posix: { sep: '/' },\n};\n/* c8 ignore stop */\nexport const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;\nminimatch.sep = sep;\nexport const GLOBSTAR = Symbol('globstar **');\nminimatch.GLOBSTAR = GLOBSTAR;\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]';\n// * => any number of characters\nconst star = qmark + '*?';\n// ** when dots are allowed. Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?';\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?';\nexport const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);\nminimatch.filter = filter;\nconst ext = (a, b = {}) => Object.assign({}, a, b);\nexport const defaults = (def) => {\n if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n return minimatch;\n }\n const orig = minimatch;\n const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));\n return Object.assign(m, {\n Minimatch: class Minimatch extends orig.Minimatch {\n constructor(pattern, options = {}) {\n super(pattern, ext(def, options));\n }\n static defaults(options) {\n return orig.defaults(ext(def, options)).Minimatch;\n }\n },\n AST: class AST extends orig.AST {\n /* c8 ignore start */\n constructor(type, parent, options = {}) {\n super(type, parent, ext(def, options));\n }\n /* c8 ignore stop */\n static fromGlob(pattern, options = {}) {\n return orig.AST.fromGlob(pattern, ext(def, options));\n }\n },\n unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),\n escape: (s, options = {}) => orig.escape(s, ext(def, options)),\n filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),\n defaults: (options) => orig.defaults(ext(def, options)),\n makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),\n braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),\n match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),\n sep: orig.sep,\n GLOBSTAR: GLOBSTAR,\n });\n};\nminimatch.defaults = defaults;\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (pattern, options = {}) => {\n assertValidPattern(pattern);\n // Thanks to Yeting Li for\n // improving this regexp to avoid a ReDOS vulnerability.\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n // shortcut. no need to expand.\n return [pattern];\n }\n return expand(pattern);\n};\nminimatch.braceExpand = braceExpand;\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion. Otherwise, any series\n// of * is equivalent to a single *. Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\nexport const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();\nminimatch.makeRe = makeRe;\nexport const match = (list, pattern, options = {}) => {\n const mm = new Minimatch(pattern, options);\n list = list.filter(f => mm.match(f));\n if (mm.options.nonull && !list.length) {\n list.push(pattern);\n }\n return list;\n};\nminimatch.match = match;\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/;\nconst regExpEscape = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\nexport class Minimatch {\n options;\n set;\n pattern;\n windowsPathsNoEscape;\n nonegate;\n negate;\n comment;\n empty;\n preserveMultipleSlashes;\n partial;\n globSet;\n globParts;\n nocase;\n isWindows;\n platform;\n windowsNoMagicRoot;\n regexp;\n constructor(pattern, options = {}) {\n assertValidPattern(pattern);\n options = options || {};\n this.options = options;\n this.pattern = pattern;\n this.platform = options.platform || defaultPlatform;\n this.isWindows = this.platform === 'win32';\n this.windowsPathsNoEscape =\n !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, '/');\n }\n this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;\n this.regexp = null;\n this.negate = false;\n this.nonegate = !!options.nonegate;\n this.comment = false;\n this.empty = false;\n this.partial = !!options.partial;\n this.nocase = !!this.options.nocase;\n this.windowsNoMagicRoot =\n options.windowsNoMagicRoot !== undefined\n ? options.windowsNoMagicRoot\n : !!(this.isWindows && this.nocase);\n this.globSet = [];\n this.globParts = [];\n this.set = [];\n // make the set of regexps etc.\n this.make();\n }\n hasMagic() {\n if (this.options.magicalBraces && this.set.length > 1) {\n return true;\n }\n for (const pattern of this.set) {\n for (const part of pattern) {\n if (typeof part !== 'string')\n return true;\n }\n }\n return false;\n }\n debug(..._) { }\n make() {\n const pattern = this.pattern;\n const options = this.options;\n // empty patterns and comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n this.comment = true;\n return;\n }\n if (!pattern) {\n this.empty = true;\n return;\n }\n // step 1: figure out negation, etc.\n this.parseNegate();\n // step 2: expand braces\n this.globSet = [...new Set(this.braceExpand())];\n if (options.debug) {\n this.debug = (...args) => console.error(...args);\n }\n this.debug(this.pattern, this.globSet);\n // step 3: now we have a set, so turn each one into a series of\n // path-portion matching patterns.\n // These will be regexps, except in the case of \"**\", which is\n // set to the GLOBSTAR object for globstar behavior,\n // and will not contain any / characters\n //\n // First, we preprocess to make the glob pattern sets a bit simpler\n // and deduped. There are some perf-killing patterns that can cause\n // problems with a glob walk, but we can simplify them down a bit.\n const rawGlobParts = this.globSet.map(s => this.slashSplit(s));\n this.globParts = this.preprocess(rawGlobParts);\n this.debug(this.pattern, this.globParts);\n // glob --> regexps\n let set = this.globParts.map((s, _, __) => {\n if (this.isWindows && this.windowsNoMagicRoot) {\n // check if it's a drive or unc path.\n const isUNC = s[0] === '' &&\n s[1] === '' &&\n (s[2] === '?' || !globMagic.test(s[2])) &&\n !globMagic.test(s[3]);\n const isDrive = /^[a-z]:/i.test(s[0]);\n if (isUNC) {\n return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];\n }\n else if (isDrive) {\n return [s[0], ...s.slice(1).map(ss => this.parse(ss))];\n }\n }\n return s.map(ss => this.parse(ss));\n });\n this.debug(this.pattern, set);\n // filter out everything that didn't compile properly.\n this.set = set.filter(s => s.indexOf(false) === -1);\n // do not treat the ? in UNC paths as magic\n if (this.isWindows) {\n for (let i = 0; i < this.set.length; i++) {\n const p = this.set[i];\n if (p[0] === '' &&\n p[1] === '' &&\n this.globParts[i][2] === '?' &&\n typeof p[3] === 'string' &&\n /^[a-z]:$/i.test(p[3])) {\n p[2] = '?';\n }\n }\n }\n this.debug(this.pattern, this.set);\n }\n // various transforms to equivalent pattern sets that are\n // faster to process in a filesystem walk. The goal is to\n // eliminate what we can, and push all ** patterns as far\n // to the right as possible, even if it increases the number\n // of patterns that we have to process.\n preprocess(globParts) {\n // if we're not in globstar mode, then turn all ** into *\n if (this.options.noglobstar) {\n for (let i = 0; i < globParts.length; i++) {\n for (let j = 0; j < globParts[i].length; j++) {\n if (globParts[i][j] === '**') {\n globParts[i][j] = '*';\n }\n }\n }\n }\n const { optimizationLevel = 1 } = this.options;\n if (optimizationLevel >= 2) {\n // aggressive optimization for the purpose of fs walking\n globParts = this.firstPhasePreProcess(globParts);\n globParts = this.secondPhasePreProcess(globParts);\n }\n else if (optimizationLevel >= 1) {\n // just basic optimizations to remove some .. parts\n globParts = this.levelOneOptimize(globParts);\n }\n else {\n // just collapse multiple ** portions into one\n globParts = this.adjascentGlobstarOptimize(globParts);\n }\n return globParts;\n }\n // just get rid of adjascent ** portions\n adjascentGlobstarOptimize(globParts) {\n return globParts.map(parts => {\n let gs = -1;\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let i = gs;\n while (parts[i + 1] === '**') {\n i++;\n }\n if (i !== gs) {\n parts.splice(gs, i - gs);\n }\n }\n return parts;\n });\n }\n // get rid of adjascent ** and resolve .. portions\n levelOneOptimize(globParts) {\n return globParts.map(parts => {\n parts = parts.reduce((set, part) => {\n const prev = set[set.length - 1];\n if (part === '**' && prev === '**') {\n return set;\n }\n if (part === '..') {\n if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n set.pop();\n return set;\n }\n }\n set.push(part);\n return set;\n }, []);\n return parts.length === 0 ? [''] : parts;\n });\n }\n levelTwoFileOptimize(parts) {\n if (!Array.isArray(parts)) {\n parts = this.slashSplit(parts);\n }\n let didSomething = false;\n do {\n didSomething = false;\n // // -> /\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i];\n // don't squeeze out UNC patterns\n if (i === 1 && p === '' && parts[0] === '')\n continue;\n if (p === '.' || p === '') {\n didSomething = true;\n parts.splice(i, 1);\n i--;\n }\n }\n if (parts[0] === '.' &&\n parts.length === 2 &&\n (parts[1] === '.' || parts[1] === '')) {\n didSomething = true;\n parts.pop();\n }\n }\n // //../ -> /\n let dd = 0;\n while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n const p = parts[dd - 1];\n if (p && p !== '.' && p !== '..' && p !== '**') {\n didSomething = true;\n parts.splice(dd - 1, 2);\n dd -= 2;\n }\n }\n } while (didSomething);\n return parts.length === 0 ? [''] : parts;\n }\n // First phase: single-pattern processing\n // is 1 or more portions\n // is 1 or more portions\n // is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n // /**/..//
/ -> {/../