r.width&&(d=r.width),d=Math.round(d),this.el_.style.right=`-${d}px`,this.write(i)}write(e){Ti(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(),l=o-t*o;n=(l<1?"":"-")+Ki(l,o)}else n=Ki(i,a);this.update(e,t,n),r&&r()})}}N.registerComponent("TimeTooltip",HC);class Ul extends N{constructor(e,t){super(e,t),this.setIcon("circle"),this.update=Vt(de(this,this.update),Tt)}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)}}Ul.prototype.options_={children:[]};!Qe&&!jt&&Ul.prototype.options_.children.push("timeTooltip");N.registerComponent("PlayProgressBar",Ul);class Tm extends N{constructor(e,t){super(e,t),this.update=Vt(de(this,this.update),Tt)}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`})}}Tm.prototype.options_={children:["timeTooltip"]};N.registerComponent("MouseTimeDisplay",Tm);const jn=5,dh=12;class Fl extends Bl{constructor(e,t){super(e,t),this.setEventHandlers_()}setEventHandlers_(){this.update_=de(this,this.update),this.update=Vt(this.update_,Tt),this.on(this.player_,["ended","durationchange","timeupdate"],this.update),this.player_.liveTracker&&this.on(this.player_.liveTracker,"liveedgechange",this.update),this.updateInterval=null,this.enableIntervalHandler_=e=>this.enableInterval_(e),this.disableIntervalHandler_=e=>this.disableInterval_(e),this.on(this.player_,["playing"],this.enableIntervalHandler_),this.on(this.player_,["ended","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,Tt))}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}",[Ki(i,n),Ki(n,n)],"{1} of {2}")),this.currentTime_=i,this.duration_=n),this.bar&&this.bar.update(Rs(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){Hr(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){if(!Hr(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?Ot(this.player_.play()):this.update_()}stepForward(){this.userSeek_(this.player_.currentTime()+jn)}stepBack(){this.userSeek_(this.player_.currentTime()-jn)}handleAction(e){this.player_.paused()?this.player_.play():this.player_.pause()}handleKeyDown(e){const t=this.player_.liveTracker;if(X.isEventKey(e,"Space")||X.isEventKey(e,"Enter"))e.preventDefault(),e.stopPropagation(),this.handleAction(e);else if(X.isEventKey(e,"Home"))e.preventDefault(),e.stopPropagation(),this.userSeek_(0);else if(X.isEventKey(e,"End"))e.preventDefault(),e.stopPropagation(),t&&t.isLive()?this.userSeek_(t.liveCurrentTime()):this.userSeek_(this.player_.duration());else if(/^[0-9]$/.test(X(e))){e.preventDefault(),e.stopPropagation();const i=(X.codes[X(e)]-X.codes[0])*10/100;t&&t.isLive()?this.userSeek_(t.seekableStart()+t.liveWindow()*i):this.userSeek_(this.player_.duration()*i)}else X.isEventKey(e,"PgDn")?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()-jn*dh)):X.isEventKey(e,"PgUp")?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()+jn*dh)):super.handleKeyDown(e)}dispose(){this.disableInterval_(),this.off(this.player_,["ended","durationchange","timeupdate"],this.update),this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.update),this.off(this.player_,["playing"],this.enableIntervalHandler_),this.off(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in $&&"visibilityState"in $&&this.off($,"visibilitychange",this.toggleVisibility_),super.dispose()}}Fl.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar"};!Qe&&!jt&&Fl.prototype.options_.children.splice(1,0,"mouseTimeDisplay");N.registerComponent("SeekBar",Fl);class bm extends N{constructor(e,t){super(e,t),this.handleMouseMove=Vt(de(this,this.handleMouseMove),Tt),this.throttledHandleMouseSeek=Vt(de(this,this.handleMouseSeek),Tt),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=Vr(n);let o=Qa(n,e).x;o=an(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&&Ot(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()}}bm.prototype.options_={children:["seekBar"]};N.registerComponent("ProgressControl",bm);class Sm extends ht{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 C?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()}}Sm.prototype.controlText_="Picture-in-Picture";N.registerComponent("PictureInPictureToggle",Sm);class xm extends ht{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()}}xm.prototype.controlText_="Fullscreen";N.registerComponent("FullscreenToggle",xm);const zC=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 GC extends N{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}}N.registerComponent("VolumeLevel",GC);class WC extends N{constructor(e,t){super(e,t),this.update=Vt(de(this,this.update),Tt)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(e,t,i,r){if(!i){const n=Rs(this.el_),a=Rs(this.player_.el()),o=e.width*t;if(!a||!n)return;const l=e.left-a.left+o,d=e.width-o+(a.right-e.right);let p=n.width/2;ln.width&&(p=n.width),this.el_.style.right=`-${p}px`}this.write(`${r}%`)}write(e){Ti(this.el_,e)}updateVolume(e,t,i,r,n){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",()=>{this.update(e,t,i,r.toFixed(0)),n&&n()})}}N.registerComponent("VolumeLevelTooltip",WC);class Em extends N{constructor(e,t){super(e,t),this.update=Vt(de(this,this.update),Tt)}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`})}}Em.prototype.options_={children:["volumeLevelTooltip"]};N.registerComponent("MouseVolumeLevelDisplay",Em);class ro extends Bl{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){Hr(e)&&super.handleMouseDown(e)}handleMouseMove(e){const t=this.getChild("mouseVolumeLevelDisplay");if(t){const i=this.el(),r=Rs(i),n=this.vertical();let a=Qa(i,e);a=n?a.y:a.x,a=an(a,0,1),t.update(r,a,n)}Hr(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)})}}ro.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"};!Qe&&!jt&&ro.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay");ro.prototype.playerEvent="volumechange";N.registerComponent("VolumeBar",ro);class Cm extends N{constructor(e,t={}){t.vertical=t.vertical||!1,(typeof t.volumeBar>"u"||Ls(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),zC(this,e),this.throttledHandleMouseMove=Vt(de(this,this.handleMouseMove),Tt),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)}}Cm.prototype.options_={children:["volumeBar"]};N.registerComponent("VolumeControl",Cm);const KC=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 wm extends ht{constructor(e,t){super(e,t),KC(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"),Qe&&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),Xa(this.el_,[0,1,2,3].reduce((i,r)=>i+`${r?" ":""}vjs-vol-${r}`,"")),qi(this.el_,`vjs-vol-${t}`)}updateControlText_(){const t=this.player_.muted()||this.player_.volume()===0?"Unmute":"Mute";this.controlText()!==t&&this.controlText(t)}}wm.prototype.controlText_="Mute";N.registerComponent("MuteToggle",wm);class Am extends N{constructor(e,t={}){typeof t.inline<"u"?t.inline=t.inline:t.inline=!0,(typeof t.volumeControl>"u"||Ls(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){X.isEventKey(e,"Esc")&&this.muteToggle.focus()}handleMouseOver(e){this.addClass("vjs-hover"),ft($,"keyup",this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass("vjs-hover"),He($,"keyup",this.handleKeyPressHandler_)}handleKeyPress(e){X.isEventKey(e,"Esc")&&this.handleMouseOut()}}Am.prototype.options_={children:["muteToggle","volumeControl"]};N.registerComponent("VolumePanel",Am);class Dm extends ht{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]))}}Dm.prototype.controlText_="Skip Forward";N.registerComponent("SkipForward",Dm);class km extends ht{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]))}}km.prototype.controlText_="Skip Backward";N.registerComponent("SkipBackward",km);class Im extends N{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 N&&(this.on(e,"blur",this.boundHandleBlur_),this.on(e,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof N&&(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_=Q(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_),ft(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){X.isEventKey(e,"Left")||X.isEventKey(e,"Down")?(e.preventDefault(),e.stopPropagation(),this.stepForward()):(X.isEventKey(e,"Right")||X.isEventKey(e,"Up"))&&(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())}}N.registerComponent("Menu",Im);class $l extends N{constructor(e,t={}){super(e,t),this.menuButton_=new ht(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");const i=ht.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(),ft($,"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 Im(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){const t=Q("li",{className:"vjs-menu-title",textContent:xe(this.options_.title),tabIndex:-1}),i=new N(this.player_,{el:t});e.addItem(i)}if(this.items=this.createItems(),this.items)for(let t=0;tX.isEventKey(e,t))||super.handleKeyDown(e)}handleClick(e){this.selected(!0)}selected(e){this.selectable&&(e?(this.addClass("vjs-selected"),this.el_.setAttribute("aria-checked","true"),this.controlText(", selected"),this.isSelected_=!0):(this.removeClass("vjs-selected"),this.el_.setAttribute("aria-checked","false"),this.controlText(""),this.isSelected_=!1))}}N.registerComponent("MenuItem",on);class un extends on{constructor(e,t){const i=t.track,r=e.textTracks();t.label=i.label||i.language||"Unknown",t.selected=i.mode==="showing",super(e,t),this.track=i,this.kinds=(t.kinds||[t.kind||this.track.kind]).filter(Boolean);const n=(...o)=>{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 C.Event!="object")try{o=new C.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()}}N.registerComponent("OffTextTrackMenuItem",Pm);class zs extends jl{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=un){let i;this.label_&&(i=`${this.label_} off`),e.push(new Pm(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}}N.registerComponent("TextTrackButton",zs);class Lm extends on{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(xe(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(xe(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 zl(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,Om),e}}Wl.prototype.kinds_=["captions","subtitles"];Wl.prototype.controlText_="Subtitles";N.registerComponent("SubsCapsButton",Wl);class Rm extends on{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","description"].indexOf(this.options_.track.kind)>=0&&(n.appendChild(Q("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),n.appendChild(Q("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)}}Kl.prototype.contentElType="button";N.registerComponent("PlaybackRateMenuItem",Kl);class Nm extends $l{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_=Q("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 Kl(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")}}Nm.prototype.controlText_="Playback Rate";N.registerComponent("PlaybackRateMenuButton",Nm);class Bm extends N{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e="div",t={},i={}){return t.className||(t.className=this.buildCSSClass()),super.createEl(e,t,i)}}N.registerComponent("Spacer",Bm);class YC extends Bm{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:" "})}}N.registerComponent("CustomControlSpacer",YC);class Um extends N{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}Um.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]};N.registerComponent("ControlBar",Um);class Fm extends Vs{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):""}}Fm.prototype.options_=Object.assign({},Vs.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0});N.registerComponent("ErrorDisplay",Fm);const eu="vjs-text-track-settings",hh=["#000","Black"],fh=["#00F","Blue"],ph=["#0FF","Cyan"],mh=["#0F0","Green"],gh=["#F0F","Magenta"],yh=["#F00","Red"],_h=["#FFF","White"],vh=["#FF0","Yellow"],tu=["1","Opaque"],iu=["0.5","Semi-Transparent"],Th=["0","Transparent"],Oi={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[hh,_h,yh,mh,fh,vh,gh,ph]},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[tu,iu,Th]},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[_h,hh,yh,mh,fh,vh,gh,ph]},edgeStyle:{selector:".vjs-edge-style > select",id:"%s",label:"Text Edge Style",options:[["none","None"],["raised","Raised"],["depressed","Depressed"],["uniform","Uniform"],["dropshadow","Drop shadow"]]},fontFamily:{selector:".vjs-font-family > select",id:"captions-font-family-%s",label:"Font Family",options:[["proportionalSansSerif","Proportional Sans-Serif"],["monospaceSansSerif","Monospace Sans-Serif"],["proportionalSerif","Proportional Serif"],["monospaceSerif","Monospace Serif"],["casual","Casual"],["script","Script"],["small-caps","Small Caps"]]},fontPercent:{selector:".vjs-font-percent > select",id:"captions-font-size-%s",label:"Font Size",options:[["0.50","50%"],["0.75","75%"],["1.00","100%"],["1.25","125%"],["1.50","150%"],["1.75","175%"],["2.00","200%"],["3.00","300%"],["4.00","400%"]],default:2,parser:s=>s==="1.00"?null:Number(s)},textOpacity:{selector:".vjs-text-opacity > select",id:"captions-foreground-opacity-%s",label:"Opacity",options:[tu,iu]},windowColor:{selector:".vjs-window-color > select",id:"captions-window-color-%s",label:"Color"},windowOpacity:{selector:".vjs-window-opacity > select",id:"captions-window-opacity-%s",label:"Opacity",options:[Th,iu,tu]}};Oi.windowColor.options=Oi.backgroundColor.options;function $m(s,e){if(e&&(s=e(s)),s&&s!=="none")return s}function QC(s,e){const t=s.options[s.options.selectedIndex].value;return $m(t,e)}function JC(s,e,t){if(e){for(let i=0;i{this.saveSettings(),this.close()}),this.on(this.$(".vjs-default-button"),"click",()=>{this.setDefaults(),this.updateDisplay()}),gs(Oi,i=>{this.on(this.$(i.selector),"change",this.updateDisplay)}),this.options_.persistTextTrackSettings&&this.restoreSettings()}dispose(){this.endDialog=null,super.dispose()}createElSelect_(e,t="",i="label"){const r=Oi[e],n=r.id.replace("%s",this.id_),a=[t,n].join(" ").trim(),o=`vjs_select_${At()}`;return[`<${i} id="${n}"${i==="label"?` for="${o}" class="vjs-label"`:""}>`,this.localize(r.label),`${i}>`,``].concat(r.options.map(l=>{const d=n+"-"+l[1].replace(/\W+/g,"");return[``,this.localize(l[1])," "].join("")})).concat(" ").join("")}createElFgColor_(){const e=`captions-text-legend-${this.id_}`;return['',``,this.localize("Text")," ",'',this.createElSelect_("color",e)," ",'',this.createElSelect_("textOpacity",e)," "," "].join("")}createElBgColor_(){const e=`captions-background-${this.id_}`;return['',``,this.localize("Text Background")," ",'',this.createElSelect_("backgroundColor",e)," ",'',this.createElSelect_("backgroundOpacity",e)," "," "].join("")}createElWinColor_(){const e=`captions-window-${this.id_}`;return['',``,this.localize("Caption Area Background")," ",'',this.createElSelect_("windowColor",e)," ",'',this.createElSelect_("windowOpacity",e)," "," "].join("")}createElColors_(){return Q("div",{className:"vjs-track-settings-colors",innerHTML:[this.createElFgColor_(),this.createElBgColor_(),this.createElWinColor_()].join("")})}createElFont_(){return Q("div",{className:"vjs-track-settings-font",innerHTML:['',this.createElSelect_("fontPercent","","legend")," ",'',this.createElSelect_("edgeStyle","","legend")," ",'',this.createElSelect_("fontFamily","","legend")," "].join("")})}createElControls_(){const e=this.localize("restore all settings to the default values");return Q("div",{className:"vjs-track-settings-controls",innerHTML:[``,this.localize("Reset"),` ${e} `," ",`${this.localize("Done")} `].join("")})}content(){return[this.createElColors_(),this.createElFont_(),this.createElControls_()]}label(){return this.localize("Caption Settings Dialog")}description(){return this.localize("Beginning of dialog window. Escape will cancel and close the window.")}buildCSSClass(){return super.buildCSSClass()+" vjs-text-track-settings"}getValues(){return Rp(Oi,(e,t,i)=>{const r=QC(this.$(t.selector),t.parser);return r!==void 0&&(e[i]=r),e},{})}setValues(e){gs(Oi,(t,i)=>{JC(this.$(t.selector),e[i],t.parser)})}setDefaults(){gs(Oi,e=>{const t=e.hasOwnProperty("default")?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(C.localStorage.getItem(eu))}catch(t){ee.warn(t)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;const e=this.getValues();try{Object.keys(e).length?C.localStorage.setItem(eu,JSON.stringify(e)):C.localStorage.removeItem(eu)}catch(t){ee.warn(t)}}updateDisplay(){const e=this.player_.getChild("textTrackDisplay");e&&e.updateDisplay()}conditionalBlur_(){this.previouslyActiveEl_=null;const e=this.player_.controlBar,t=e&&e.subsCapsButton,i=e&&e.captionsButton;t?t.focus():i&&i.focus()}handleLanguagechange(){this.fill()}}N.registerComponent("TextTrackSettings",ZC);class ew extends N{constructor(e,t){let i=t.ResizeObserver||C.ResizeObserver;t.ResizeObserver===null&&(i=!1);const r=ce({createEl:!i,reportTouchActivity:!1},t);super(e,r),this.ResizeObserver=t.ResizeObserver||C.ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=sm(()=>{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(){He(this,"resize",n),He(this,"unload",a),a=null};ft(this.el_.contentWindow,"unload",a),ft(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()}}N.registerComponent("ResizeManager",ew);const tw={trackingThreshold:20,liveTolerance:15};class iw extends N{constructor(e,t){const i=ce(tw,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(C.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_,Tt),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()}}N.registerComponent("LiveTracker",iw);class sw extends N{constructor(e,t){super(e,t),this.on("statechanged",i=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:Q("div",{className:"vjs-title-bar-title",id:`vjs-title-bar-title-${At()}`}),description:Q("div",{className:"vjs-title-bar-description",id:`vjs-title-bar-description-${At()}`})},Q("div",{className:"vjs-title-bar"},{},Mp(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];Ja(a),n&&Ti(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}}N.registerComponent("TitleBar",sw);const Ru=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;ijm([s.el(),C.HTMLMediaElement.prototype,C.Element.prototype,rw],"innerHTML"),bh=function(s){const e=s.el();if(e.resetSourceWatch_)return;const t={},i=nw(s),r=n=>(...a)=>{const o=n.apply(e,a);return Ru(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_)},aw=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?fm(C.Element.prototype.getAttribute.call(this,"src")):""},set(s){return C.Element.prototype.setAttribute.call(this,"src",s),s}}),ow=s=>jm([s.el(),C.HTMLMediaElement.prototype,aw],"src"),uw=function(s){if(!s.featuresSourceset)return;const e=s.el();if(e.resetSourceset_)return;const t=ow(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 Ru(s)||(s.triggerSourceset(""),bh(s)),n},e.currentSrc?s.triggerSourceset(e.currentSrc):Ru(s)||bh(s),e.resetSourceset_=()=>{e.resetSourceset_=null,e.load=r,e.setAttribute=i,Object.defineProperty(e,"src",t),e.resetSourceWatch_&&e.resetSourceWatch_()}};class q extends Y{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 l=n[a];l.nodeName.toLowerCase()==="track"&&(this.featuresNativeTextTracks?(this.remoteTextTrackEls().addTrackElement_(l),this.remoteTextTracks().addTrack(l.track),this.textTracks().addTrack(l.track),!r&&!this.el_.hasAttribute("crossorigin")&&io(l.src)&&(r=!0)):o.push(l))}for(let l=0;l{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=vt[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 l={type:"change",target:r,currentTarget:r,srcElement:r};r.trigger(l),e==="text"&&this[Bs.remoteText.getterName]().trigger(l)},addtrack(o){r.addTrack(o.track)},removetrack(o){r.removeTrack(o.track)}},a=function(){const o=[];for(let l=0;l{const l=n[o];i.addEventListener(o,l),this.on("dispose",d=>i.removeEventListener(o,l))}),this.on("loadstart",a),this.on("dispose",o=>this.off("loadstart",a))}proxyNativeTracks_(){vt.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),q.disposeMediaElement(e),e=i}else{e=$.createElement("video");const i=this.options_.tag&&hi(this.options_.tag),r=ce({},i);(!qr||this.options_.nativeControlsForTouch!==!0)&&delete r.controls,Hp(e,Object.assign(r,{id:this.options_.techId,class:"vjs-tech"}))}e.playerId=this.options_.playerId}typeof this.options_.preload<"u"&&Os(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&&Ka?this.el_.fastSeek(e):this.el_.currentTime=e}catch(t){ee(t,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&jt&&qt&&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)Ot(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(){q.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),C.performance&&(e.creationTime=C.performance.now()),e}}Ha(q,"TEST_VID",function(){if(!$s())return;const s=$.createElement("video"),e=$.createElement("track");return e.kind="captions",e.srclang="en",e.label="English",s.appendChild(e),s});q.isSupported=function(){try{q.TEST_VID.volume=.5}catch{return!1}return!!(q.TEST_VID&&q.TEST_VID.canPlayType)};q.canPlayType=function(s){return q.TEST_VID.canPlayType(s)};q.canPlaySource=function(s,e){return q.canPlayType(s.type)};q.canControlVolume=function(){try{const s=q.TEST_VID.volume;q.TEST_VID.volume=s/2+.1;const e=s!==q.TEST_VID.volume;return e&&Qe?(C.setTimeout(()=>{q&&q.prototype&&(q.prototype.featuresVolumeControl=s!==q.TEST_VID.volume)}),!1):e}catch{return!1}};q.canMuteVolume=function(){try{const s=q.TEST_VID.muted;return q.TEST_VID.muted=!s,q.TEST_VID.muted?Os(q.TEST_VID,"muted","muted"):Ya(q.TEST_VID,"muted","muted"),s!==q.TEST_VID.muted}catch{return!1}};q.canControlPlaybackRate=function(){if(jt&&qt&&za<58)return!1;try{const s=q.TEST_VID.playbackRate;return q.TEST_VID.playbackRate=s/2+.1,s!==q.TEST_VID.playbackRate}catch{return!1}};q.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};q.supportsNativeTextTracks=function(){return Ka||Qe&&qt};q.supportsNativeVideoTracks=function(){return!!(q.TEST_VID&&q.TEST_VID.videoTracks)};q.supportsNativeAudioTracks=function(){return!!(q.TEST_VID&&q.TEST_VID.audioTracks)};q.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]){Ha(q.prototype,s,()=>q[e](),!0)});q.prototype.featuresVolumeControl=q.canControlVolume();q.prototype.movingMediaElementInDOM=!Qe;q.prototype.featuresFullscreenResize=!0;q.prototype.featuresProgressEvents=!0;q.prototype.featuresTimeupdateEvents=!0;q.prototype.featuresVideoFrameCallback=!!(q.TEST_VID&&q.TEST_VID.requestVideoFrameCallback);q.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{}}()}};q.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){q.prototype[s]=function(){return this.el_[s]||this.el_.hasAttribute(s)}});["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(s){q.prototype["set"+xe(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){q.prototype[s]=function(){return this.el_[s]}});["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(s){q.prototype["set"+xe(s)]=function(e){this.el_[s]=e}});["pause","load","play"].forEach(function(s){q.prototype[s]=function(){return this.el_[s]()}});Y.withSourceHandlers(q);q.nativeSourceHandler={};q.nativeSourceHandler.canPlayType=function(s){try{return q.TEST_VID.canPlayType(s)}catch{return""}};q.nativeSourceHandler.canHandleSource=function(s,e){if(s.type)return q.nativeSourceHandler.canPlayType(s.type);if(s.src){const t=Ll(s.src);return q.nativeSourceHandler.canPlayType(`video/${t}`)}return""};q.nativeSourceHandler.handleSource=function(s,e,t){e.setSrc(s.src)};q.nativeSourceHandler.dispose=function(){};q.registerSourceHandler(q.nativeSourceHandler);Y.registerTech("Html5",q);const qm=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],su={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},Mu=["tiny","xsmall","small","medium","large","xlarge","huge"],Jn={};Mu.forEach(s=>{const e=s.charAt(0)==="x"?`x-${s.substring(1)}`:s;Jn[s]=`vjs-layout-${e}`});const lw={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};let Re=class us extends N{constructor(e,t,i){if(e.id=e.id||t.id||`vjs_video_${At()}`,t=Object.assign(us.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.isFullscreen_=!1,this.log=Lp(this.id_),this.fsApi_=ca,this.isPosterFromTech_=!1,this.queuedCallbacks_=[],this.isReady_=!1,this.hasStarted_=!1,this.userActive_=!1,this.debugEnabled_=!1,this.audioOnlyMode_=!1,this.audioPosterMode_=!1,this.audioOnlyCache_={playerHeight:null,hiddenChildren:[]},!this.options_||!this.options_.techOrder||!this.options_.techOrder.length)throw new Error("No techOrder specified. Did you overwrite videojs.options instead of just changing the properties you want to override?");if(this.tag=e,this.tagAttributes=e&&hi(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_=us.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(),Dl(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&(ft($,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 C.DOMParser().parseFromString(RC,"image/svg+xml");if(o.querySelector("parsererror"))ee.warn("Failed to load SVG Icons. Falling back to Font Icons."),this.options_.experimentalSvgIcons=null;else{const d=o.documentElement;d.style.display="none",this.el_.appendChild(d),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"),qr&&this.addClass("vjs-touch-enabled"),Qe||this.addClass("vjs-workinghover"),us.players[this.id_]=this;const n=bu.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"),He($,this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),He($,"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),us.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),IC(this),Ke.names.forEach(e=>{const t=Ke[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=hi(e);if(r){for(t=this.el_=e,e=this.tag=$.createElement("video");t.children.length;)e.appendChild(t.firstChild);Dr(t,"video-js")||qi(t,"video-js"),t.appendChild(e),i=this.playerElIngest_=t,Object.keys(t).forEach(l=>{try{e[l]=t[l]}catch{}})}e.setAttribute("tabindex","-1"),n.tabindex="-1",qt&&Ga&&(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(l){r&&l==="class"||t.setAttribute(l,n[l]),r&&e.setAttribute(l,n[l])}),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"].filter(l=>$p[l]).map(l=>"vjs-device-"+l.substring(3).toLowerCase().replace(/\_/g,"-"));if(this.addClass(...a),C.VIDEOJS_NO_DYNAMIC_STYLE!==!0){this.styleEl_=tm("vjs-styles-dimensions");const l=_i(".vjs-styles-defaults"),d=_i("head");d.insertBefore(this.styleEl_,l?l.nextSibling:d.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 l=0;l"u")return this.techGet_("crossOrigin");if(e!==null&&e!=="anonymous"&&e!=="use-credentials"){ee.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)){ee.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,ei(this)&&this.off(["playerreset","resize"],this.boundUpdateStyleEl_),e?(this.addClass("vjs-fluid"),this.fill(!1),aC(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(C.VIDEOJS_NO_DYNAMIC_STYLE===!0){const o=typeof this.width_=="number"?this.width_:this.options_.width,l=typeof this.height_=="number"?this.height_:this.options_.height,d=this.tech_&&this.tech_.el();d&&(o>=0&&(d.width=o),l>=0&&(d.height=l));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),im(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=xe(e),r=e.charAt(0).toLowerCase()+e.slice(1);i!=="Html5"&&this.tag&&(Y.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};Ke.names.forEach(l=>{const d=Ke[l];a[d.getterName]=this[d.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=Y.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),ih.jsonToTextTracks(this.textTracksJson_||[],this.tech_),qm.forEach(l=>{this.on(this.tech_,l,d=>this[`handleTech${xe(l)}_`](d))}),Object.keys(su).forEach(l=>{this.on(this.tech_,l,d=>{if(this.tech_.playbackRate()===0&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${su[l]}_`].bind(this),event:d});return}this[`handleTech${su[l]}_`](d)})}),this.on(this.tech_,"loadstart",l=>this.handleTechLoadStart_(l)),this.on(this.tech_,"sourceset",l=>this.handleTechSourceset_(l)),this.on(this.tech_,"waiting",l=>this.handleTechWaiting_(l)),this.on(this.tech_,"ended",l=>this.handleTechEnded_(l)),this.on(this.tech_,"seeking",l=>this.handleTechSeeking_(l)),this.on(this.tech_,"play",l=>this.handleTechPlay_(l)),this.on(this.tech_,"pause",l=>this.handleTechPause_(l)),this.on(this.tech_,"durationchange",l=>this.handleTechDurationChange_(l)),this.on(this.tech_,"fullscreenchange",(l,d)=>this.handleTechFullscreenChange_(l,d)),this.on(this.tech_,"fullscreenerror",(l,d)=>this.handleTechFullscreenError_(l,d)),this.on(this.tech_,"enterpictureinpicture",l=>this.handleTechEnterPictureInPicture_(l)),this.on(this.tech_,"leavepictureinpicture",l=>this.handleTechLeavePictureInPicture_(l)),this.on(this.tech_,"error",l=>this.handleTechError_(l)),this.on(this.tech_,"posterchange",l=>this.handleTechPosterChange_(l)),this.on(this.tech_,"textdata",l=>this.handleTechTextData_(l)),this.on(this.tech_,"ratechange",l=>this.handleTechRateChange_(l)),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)&&wu(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){Ke.names.forEach(e=>{const t=Ke[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=ih.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&&ee.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":bu}}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(Ir(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(),Ir(i)&&(i=i.catch(t))):e==="muted"&&!this.muted()?i=t():i=this.play(),!!Ir(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=OC(this,t)),this.cache_.source=ce({},e,{src:t,type:i});const r=this.cache_.sources.filter(l=>l.src&&l.src===t),n=[],a=this.$$("source"),o=[];for(let l=0;lthis.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()?Ot(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 DC)return wC(this.middleware_,this.tech_,e,t);if(e in oh)return ah(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(i){throw ee(i),i}},!0)}techGet_(e){if(!(!this.tech_||!this.tech_.isReady_)){if(e in AC)return CC(this.middleware_,this.tech_,e);if(e in oh)return ah(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){throw this.tech_[e]===void 0?(ee(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t):t.name==="TypeError"?(ee(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t):(ee(t),t)}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=Ot){this.playCallbacks_.push(e);const t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),i=!!(Ka||Qe);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")||wt(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=wt(0,0)),e}seekable(){let e=this.techGet_("seekable");return(!e||!e.length)&&(e=wt(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 dm(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(d,p){n(),r(p)}t.one("fullscreenchange",a),t.one("fullscreenerror",o);const l=t.requestFullscreenHelper_(e);l&&(l.then(n,n),l.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(l,d){r(),i(d)}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&&Ot(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,ft($,"keydown",this.boundFullWindowOnEscKey_),$.documentElement.style.overflow="hidden",qi($.body,"vjs-full-window"),this.trigger("enterFullWindow")}fullWindowOnEscKey(e){X.isEventKey(e,"Esc")&&this.isFullscreen()===!0&&(this.isFullWindow?this.exitFullWindow():this.exitFullscreen())}exitFullWindow(){this.isFullscreen(!1),this.isFullWindow=!1,He($,"keydown",this.boundFullWindowOnEscKey_),$.documentElement.style.overflow=this.docOrigOverflow,Xa($.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&&C.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(Q("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),C.documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(Jp(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(C.documentPictureInPicture&&C.documentPictureInPicture.window)return C.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=>X.isEventKey(a,"f"),muteKey:r=a=>X.isEventKey(a,"m"),playPauseKey:n=a=>X.isEventKey(a,"k")||X.isEventKey(a,"Space")}=t;if(i.call(this,e)){e.preventDefault(),e.stopPropagation();const a=N.getComponent("FullscreenToggle");$[this.fsApi_.fullscreenEnabled]!==!1&&a.prototype.handleClick.call(this,e)}else r.call(this,e)?(e.preventDefault(),e.stopPropagation(),N.getComponent("MuteToggle").prototype.handleClick.call(this,e)):n.call(this,e)&&(e.preventDefault(),e.stopPropagation(),N.getComponent("PlayToggle").prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let i=0,r=this.options_.techOrder;i[o,Y.getTech(o)]).filter(([o,l])=>l?l.isSupported():(ee.error(`The "${o}" tech is undefined. Skipped browser support check for that tech.`),!1)),i=function(o,l,d){let p;return o.some(y=>l.some(_=>{if(p=d(y,_),p)return!0})),p};let r;const n=o=>(l,d)=>o(d,l),a=([o,l],d)=>{if(l.canPlaySource(d,this.options_[o.toLowerCase()]))return{source:d,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=gm(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]),xC(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}EC(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?om(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();Ot(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}),ei(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(yi("beforeerror").forEach(t=>{const i=t(this,e);if(!($t(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 be(e),this.addClass("vjs-error"),ee.error(`(CODE:${this.error_.code} ${be.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger("error"),yi("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 l=this.getChild("controlBar");l&&!Qe&&!jt&&(l.on("mouseenter",function(y){this.player().options_.inactivityTimeout!==0&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0}),l.on("mouseleave",function(y){this.player().options_.inactivityTimeout=this.player().cache_.inactivityTimeout})),this.on("keydown",r),this.on("keyup",r);let d;const p=function(){if(!this.userActivity_)return;this.userActivity_=!1,this.userActive(!0),this.clearTimeout(d);const y=this.options_.inactivityTimeout;y<=0||(d=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_}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.height(i),this.trigger("audioonlymodechange")}disableAudioOnlyUI_(){this.removeClass("vjs-audio-only-mode"),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(),ei(this)&&this.trigger("languagechange"))}languages(){return ce(us.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:ga(r.poster)}]),r}return ce(this.cache_.media)}static getTagSettings(e){const t={sources:[],tracks:[]},i=hi(e),r=i["data-setup"];if(Dr(e,"vjs-fill")&&(i.fill=!0),Dr(e,"vjs-fluid")&&(i.fluid=!0),r!==null){const[n,a]=W1(r||"{}");n&&ee.error(n),Object.assign(i,a)}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"))}};Ke.names.forEach(function(s){const e=Ke[s];Re.prototype[e.getterName]=function(){return this.tech_?this.tech_[e.getterName]():(this[e.privateName]=this[e.privateName]||new e.ListClass,this[e.privateName])}});Re.prototype.crossorigin=Re.prototype.crossOrigin;Re.players={};const fr=C.navigator;Re.prototype.options_={techOrder:Y.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","titleBar","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:fr&&(fr.languages&&fr.languages[0]||fr.userLanguage||fr.language)||"en",languages:{},notSupportedMessage:"No compatible source was found for this media.",normalizeAutoplay:!1,fullscreen:{options:{navigationUI:"hide"}},breakpoints:{},responsive:!1,audioOnlyMode:!1,audioPosterMode:!1,enableSmoothSeeking:!1};qm.forEach(function(s){Re.prototype[`handleTech${xe(s)}_`]=function(){return this.trigger(s)}});N.registerComponent("Player",Re);const ya="plugin",vs="activePlugins_",ds={},_a=s=>ds.hasOwnProperty(s),Zn=s=>_a(s)?ds[s]:void 0,Vm=(s,e)=>{s[vs]=s[vs]||{},s[vs][e]=!0},va=(s,e,t)=>{const i=(t?"before":"")+"pluginsetup";s.trigger(i,e),s.trigger(i+":"+e.name,e)},cw=function(s,e){const t=function(){va(this,{name:s,plugin:e,instance:null},!0);const i=e.apply(this,arguments);return Vm(this,s),va(this,{name:s,plugin:e,instance:i}),i};return Object.keys(e).forEach(function(i){t[i]=e[i]}),t},Sh=(s,e)=>(e.prototype.name=s,function(...t){va(this,{name:s,plugin:e,instance:null},!0);const i=new e(this,...t);return this[s]=()=>i,va(this,i.getEventHash()),i});class rt{constructor(e){if(this.constructor===rt)throw new Error("Plugin must be sub-classed; not directly instantiated.");this.player=e,this.log||(this.log=this.player.log.createLogger(this.name)),Dl(this),delete this.trigger,am(this,this.constructor.defaultState),Vm(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 qs(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[vs][e]=!1,this.player=this.state=null,t[e]=Sh(e,ds[e])}static isBasic(e){const t=typeof e=="string"?Zn(e):e;return typeof t=="function"&&!rt.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(_a(e))ee.warn(`A plugin named "${e}" already exists. You may want to avoid re-registering plugins!`);else if(Re.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 ds[e]=t,e!==ya&&(rt.isBasic(t)?Re.prototype[e]=cw(e,t):Re.prototype[e]=Sh(e,t)),t}static deregisterPlugin(e){if(e===ya)throw new Error("Cannot de-register base plugin.");_a(e)&&(delete ds[e],delete Re.prototype[e])}static getPlugins(e=Object.keys(ds)){let t;return e.forEach(i=>{const r=Zn(i);r&&(t=t||{},t[i]=r)}),t}static getPluginVersion(e){const t=Zn(e);return t&&t.VERSION||""}}rt.getPlugin=Zn;rt.BASE_PLUGIN_NAME=ya;rt.registerPlugin(ya,rt);Re.prototype.usingPlugin=function(s){return!!this[vs]&&this[vs][s]===!0};Re.prototype.hasPlugin=function(s){return!!_a(s)};function dw(s,e){let t=!1;return function(...i){return t||ee.warn(s),t=!0,e.apply(this,i)}}function Dt(s,e,t,i){return dw(`${e} is deprecated and will be removed in ${s}.0; please use ${t} instead.`,i)}var hw={UnsupportedSidxContainer:"unsupported-sidx-container-error",DashManifestSidxParsingError:"dash-manifest-sidx-parsing-error",HlsPlaylistRequestError:"hls-playlist-request-error",SegmentUnsupportedMediaFormat:"segment-unsupported-media-format-error",UnsupportedMediaInitialization:"unsupported-media-initialization-error",SegmentSwitchError:"segment-switch-error",SegmentExceedsSourceBufferQuota:"segment-exceeds-source-buffer-quota-error",SegmentAppendError:"segment-append-error",VttLoadError:"vtt-load-error",VttCueParsingError:"vtt-cue-parsing-error",AdsBeforePrerollError:"ads-before-preroll-error",AdsPrerollError:"ads-preroll-error",AdsMidrollError:"ads-midroll-error",AdsPostrollError:"ads-postroll-error",AdsMacroReplacementFailed:"ads-macro-replacement-failed",AdsResumeContentFailed:"ads-resume-content-failed",EMEFailedToRequestMediaKeySystemAccess:"eme-failed-request-media-key-system-access",EMEFailedToCreateMediaKeys:"eme-failed-create-media-keys",EMEFailedToAttachMediaKeysToVideoElement:"eme-failed-attach-media-keys-to-video",EMEFailedToCreateMediaKeySession:"eme-failed-create-media-key-session",EMEFailedToSetServerCertificate:"eme-failed-set-server-certificate",EMEFailedToGenerateLicenseRequest:"eme-failed-generate-license-request",EMEFailedToUpdateSessionWithReceivedLicenseKeys:"eme-failed-update-session",EMEFailedToCloseSession:"eme-failed-close-session",EMEFailedToRemoveKeysFromSession:"eme-failed-remove-keys",EMEFailedToLoadSessionBySessionId:"eme-failed-load-session"};const Hm=s=>s.indexOf("#")===0?s.slice(1):s;function L(s,e,t){let i=L.getPlayer(s);if(i)return e&&ee.warn(`Player "${s}" is already initialised. Options will not be applied.`),t&&i.ready(t),i;const r=typeof s=="string"?_i("#"+Hm(s)):s;if(!js(r))throw new TypeError("The element or ID supplied is not valid. (videojs)");const a=("getRootNode"in r?r.getRootNode()instanceof C.ShadowRoot:!1)?r.getRootNode():r.ownerDocument.body;(!r.ownerDocument.defaultView||!a.contains(r))&&ee.warn("The element supplied is not included in the DOM"),e=e||{},e.restoreEl===!0&&(e.restoreEl=(r.parentNode&&r.parentNode.hasAttribute("data-vjs-player")?r.parentNode:r).cloneNode(!0)),yi("beforesetup").forEach(l=>{const d=l(r,ce(e));if(!$t(d)||Array.isArray(d)){ee.error("please return an object in beforesetup hooks");return}e=ce(e,d)});const o=N.getComponent("Player");return i=new o(r,e,t),yi("setup").forEach(l=>l(i)),i}L.hooks_=Qt;L.hooks=yi;L.hook=WE;L.hookOnce=KE;L.removeHook=Pp;if(C.VIDEOJS_NO_DYNAMIC_STYLE!==!0&&$s()){let s=_i(".vjs-styles-defaults");if(!s){s=tm("vjs-styles-defaults");const e=_i("head");e&&e.insertBefore(s,e.firstChild),im(s,`
+ .video-js {
+ width: 300px;
+ height: 150px;
+ }
+
+ .vjs-fluid:not(.vjs-audio-only-mode) {
+ padding-top: 56.25%
+ }
+ `)}}Du(1,L);L.VERSION=bu;L.options=Re.prototype.options_;L.getPlayers=()=>Re.players;L.getPlayer=s=>{const e=Re.players;let t;if(typeof s=="string"){const i=Hm(s),r=e[i];if(r)return r;t=_i("#"+i)}else t=s;if(js(t)){const{player:i,playerId:r}=t;if(i||e[r])return i||e[r]}};L.getAllPlayers=()=>Object.keys(Re.players).map(s=>Re.players[s]).filter(Boolean);L.players=Re.players;L.getComponent=N.getComponent;L.registerComponent=(s,e)=>(Y.isTech(e)&&ee.warn(`The ${s} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),N.registerComponent.call(N,s,e));L.getTech=Y.getTech;L.registerTech=Y.registerTech;L.use=SC;Object.defineProperty(L,"middleware",{value:{},writeable:!1,enumerable:!0});Object.defineProperty(L.middleware,"TERMINATOR",{value:ma,writeable:!1,enumerable:!0});L.browser=$p;L.obj=QE;L.mergeOptions=Dt(9,"videojs.mergeOptions","videojs.obj.merge",ce);L.defineLazyProperty=Dt(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",Ha);L.bind=Dt(9,"videojs.bind","native Function.prototype.bind",de);L.registerPlugin=rt.registerPlugin;L.deregisterPlugin=rt.deregisterPlugin;L.plugin=(s,e)=>(ee.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),rt.registerPlugin(s,e));L.getPlugins=rt.getPlugins;L.getPlugin=rt.getPlugin;L.getPluginVersion=rt.getPluginVersion;L.addLanguage=function(s,e){return s=(""+s).toLowerCase(),L.options.languages=ce(L.options.languages,{[s]:e}),L.options.languages[s]};L.log=ee;L.createLogger=Lp;L.time=dC;L.createTimeRange=Dt(9,"videojs.createTimeRange","videojs.time.createTimeRanges",wt);L.createTimeRanges=Dt(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",wt);L.formatTime=Dt(9,"videojs.formatTime","videojs.time.formatTime",Ki);L.setFormatTime=Dt(9,"videojs.setFormatTime","videojs.time.setFormatTime",lm);L.resetFormatTime=Dt(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",cm);L.parseUrl=Dt(9,"videojs.parseUrl","videojs.url.parseUrl",Pl);L.isCrossOrigin=Dt(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",io);L.EventTarget=bt;L.any=Al;L.on=ft;L.one=eo;L.off=He;L.trigger=qs;L.xhr=Mf;L.TextTrack=nn;L.AudioTrack=pm;L.VideoTrack=mm;["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(s=>{L[s]=function(){return ee.warn(`videojs.${s}() is deprecated; use videojs.dom.${s}() instead`),Zp[s].apply(null,arguments)}});L.computedStyle=Dt(9,"videojs.computedStyle","videojs.dom.computedStyle",Ms);L.dom=Zp;L.fn=nC;L.num=qC;L.str=lC;L.url=TC;L.Error=hw;/*! @name videojs-contrib-quality-levels @version 4.1.0 @license Apache-2.0 */class fw{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 Ta extends L.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 fw(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=zm,i},Gm=function(s){return pw(this,L.obj.merge({},s))};L.registerPlugin("qualityLevels",Gm);Gm.VERSION=zm;/*! @name @videojs/http-streaming @version 3.12.1 @license Apache-2.0 */const it=Ba,ba=(s,e)=>e&&e.responseURL&&s!==e.responseURL?e.responseURL:s,St=s=>L.log.debug?L.log.debug.bind(L,"VHS:",`${s} >`):function(){};function re(...s){const e=L.obj||L;return(e.merge||e.mergeOptions).apply(e,s)}function Ve(...s){const e=L.time||L;return(e.createTimeRanges||e.createTimeRanges).apply(e,s)}function mw(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 Rt=1/30,Mt=Rt*3,Wm=function(s,e){const t=[];let i;if(s&&s.length)for(i=0;i=e})},qn=function(s,e){return Wm(s,function(t){return t-Rt>=e})},gw=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(", ")},_w=function(s,e,t=1){return((s.length?s.end(s.length-1):0)-e)/t},Bi=s=>{const e=[];for(let t=0;tn)){if(e>r&&e<=n){t+=n-e;continue}t+=n-r}}return t},Yl=(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},Nu=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),[]),Xm=s=>{const e=s.segments&&s.segments.length&&s.segments[s.segments.length-1];return e&&e.parts||[]},Ym=({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},Qm=(s,e)=>{if(e.endList)return 0;if(s&&s.suggestedPresentationDelay)return s.suggestedPresentationDelay;const t=Xm(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},Tw=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+=Yl(s,r),typeof r.start<"u")return{result:t+r.start,precise:!0}}return{result:t,precise:!1}},bw=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 C.Infinity}return Jm(s,e,t)},Pr=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 d=l-1;d>=0;d--){const p=o[d];if(a+=p.duration,n){if(a<0)continue}else if(a+Rt<=0)continue;return{partIndex:p.partIndex,segmentIndex:p.segmentIndex,startTime:r-Pr({defaultDuration:s.targetDuration,durationList:o,startIndex:l,endIndex:d})}}return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:e}}if(l<0){for(let d=l;d<0;d++)if(a-=s.targetDuration,a<0)return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:e};l=0}for(let d=l;dRt,_=a===0,b=y&&a+Rt>=0;if(!((_||b)&&d!==o.length-1)){if(n){if(a>0)continue}else if(a-Rt>=0)continue;return{partIndex:p.partIndex,segmentIndex:p.segmentIndex,startTime:r+Pr({defaultDuration:s.targetDuration,durationList:o,startIndex:l,endIndex:d})}}}return{segmentIndex:o[o.length-1].segmentIndex,partIndex:o[o.length-1].partIndex,startTime:e}},tg=function(s){return s.excludeUntil&&s.excludeUntil>Date.now()},Ql=function(s){return s.excludeUntil&&s.excludeUntil===1/0},no=function(s){const e=tg(s);return!s.disabled&&!e},Ew=function(s){return s.disabled},Cw=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=>no(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),xh=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},ln=s=>{if(!s||!s.playlists||!s.playlists.length)return xh(s,t=>t.playlists&&t.playlists.length||t.uri);for(let e=0;ejf(n))||xh(s,n=>Jl(t,n))))return!1}return!0};var st={liveEdgeDelay:Qm,duration:Zm,seekable:Sw,getMediaInfoForTime:xw,isEnabled:no,isDisabled:Ew,isExcluded:tg,isIncompatible:Ql,playlistEnd:eg,isAes:Cw,hasAttribute:ig,estimateSegmentRequestTime:ww,isLowestEnabledRendition:Bu,isAudioOnly:ln,playlistMatch:Jl,segmentDurationWithParts:Yl};const{log:sg}=L,Ts=(s,e)=>`${s}-${e}`,rg=(s,e,t)=>`placeholder-uri-${s}-${e}-${t}`,Aw=({onwarn:s,oninfo:e,manifestString:t,customTagParsers:i=[],customTagMappers:r=[],llhls:n})=>{const a=new HS;s&&a.on("warn",s),e&&a.on("info",e),i.forEach(d=>a.addParser(d)),r.forEach(d=>a.addTagMapper(d)),a.push(t),a.end();const o=a.manifest;if(n||(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach(function(d){o.hasOwnProperty(d)&&delete o[d]}),o.segments&&o.segments.forEach(function(d){["parts","preloadHints"].forEach(function(p){d.hasOwnProperty(p)&&delete d[p]})})),!o.targetDuration){let d=10;o.segments&&o.segments.length&&(d=o.segments.reduce((p,y)=>Math.max(p,y.duration),0)),s&&s({message:`manifest has no targetDuration defaulting to ${d}`}),o.targetDuration=d}const l=Xm(o);if(l.length&&!o.partTargetDuration){const d=l.reduce((p,y)=>Math.max(p,y.duration),0);s&&(s({message:`manifest has no partTargetDuration defaulting to ${d}`}),sg.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=d}return o},Gs=(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)}})},ng=({playlist:s,uri:e,id:t})=>{s.id=t,s.playlistErrors_=0,e&&(s.uri=e),s.attributes=s.attributes||{}},Dw=s=>{let e=s.playlists.length;for(;e--;){const t=s.playlists[e];ng({playlist:t,id:Ts(e,t.uri)}),t.resolvedUri=it(s.uri,t.uri),s.playlists[t.id]=t,s.playlists[t.uri]=t,t.attributes.BANDWIDTH||sg.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},kw=s=>{Gs(s,e=>{e.uri&&(e.resolvedUri=it(s.uri,e.uri))})},Iw=(s,e)=>{const t=Ts(0,e),i={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:C.location.href,resolvedUri:C.location.href,playlists:[{uri:e,id:t,resolvedUri:e,attributes:{}}]};return i.playlists[t]=i.playlists[0],i.playlists[e]=i.playlists[0],i},ag=(s,e,t=rg)=>{s.uri=e;for(let r=0;r{if(!r.playlists||!r.playlists.length){if(i&&n==="AUDIO"&&!r.uri)for(let l=0;l(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(){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=Ym(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 C.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},Ow=(s,e)=>{if(!s)return e;const t=re(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=it(e,s.uri)),s.key&&!s.key.resolvedUri&&(s.key.resolvedUri=it(e,s.key.uri)),s.map&&!s.map.resolvedUri&&(s.map.resolvedUri=it(e,s.map.uri)),s.map&&s.map.key&&!s.map.key.resolvedUri&&(s.map.key.resolvedUri=it(e,s.map.key.uri)),s.parts&&s.parts.length&&s.parts.forEach(t=>{t.resolvedUri||(t.resolvedUri=it(e,t.uri))}),s.preloadHints&&s.preloadHints.length&&s.preloadHints.forEach(t=>{t.resolvedUri||(t.resolvedUri=it(e,t.uri))})},ug=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,Uu=(s,e,t=lg)=>{const i=re(s,{}),r=i.playlists[e.id];if(!r||t(r,e))return null;e.segments=ug(e);const n=re(r,e);if(n.preloadSegment&&!e.preloadSegment&&delete n.preloadSegment,r.segments){if(e.skip){e.segments=e.segments||[];for(let a=0;a{og(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};class fs extends Pw{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=St("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 Eh,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=it(this.main.uri,e.uri);this.llhls&&(t=Lw(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:{errorType:L.Error.HlsPlaylistRequestError}},this.trigger("error")}parseManifest_({url:e,manifestString:t}){return Aw({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})}haveMetadata({playlistString:e,playlistObject:t,url:i,id:r}){this.request=null,this.state="HAVE_METADATA";const n=t||this.parseManifest_({url:i,manifestString:e});n.lastRequest=Date.now(),ng({playlist:n,uri:i,id:r});const a=Uu(this.main,n);this.targetDuration=n.partTargetDuration||n.targetDuration,this.pendingMedia_=null,a?(this.main=a,this.media_=this.main.playlists[r]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(Fu(this.media(),!!a)),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),C.clearTimeout(this.mediaUpdateTimeout),C.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new Eh,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(C.clearTimeout(this.finalRenditionTimeout),t){const a=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=C.setTimeout(this.media.bind(this,e,!1),a);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_(Fu(e,!0)),!!r){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,this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},(a,o)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=ba(e.resolvedUri,o),a)return this.playlistRequestError(this.request,e,i);this.haveMetadata({playlistString:o.responseText,url:e.uri,id:e.id}),i==="HAVE_MAIN_MANIFEST"?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}}pause(){this.mediaUpdateTimeout&&(C.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&&(C.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const i=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=C.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&&(C.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),!(!this.media()||this.media().endList)&&(this.mediaUpdateTimeout=C.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=C.location.href),this.src.resolvedUri=this.src.uri,setTimeout(()=>{this.setupInitialPlaylist(this.src)},0);return}this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials,requestType:"hls-playlist"},(e,t)=>{if(!this.request)return;if(this.request=null,e)return this.error={status:t.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:t.responseText,code:2,metadata:{errorType:L.Error.HlsPlaylistRequestError}},this.state==="HAVE_NOTHING"&&(this.started=!1),this.trigger("error");this.src=ba(this.src,t);const i=this.parseManifest_({manifestString:t.responseText,url:this.src});this.setupInitialPlaylist(i)})}srcUri(){return typeof this.src=="string"?this.src:this.src.uri}setupInitialPlaylist(e){if(this.state="HAVE_MAIN_MANIFEST",e.playlists){this.main=e,ag(this.main,this.srcUri()),e.playlists.forEach(i=>{i.segments=ug(i),i.segments.forEach(r=>{og(r,i.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);return}const t=this.srcUri()||C.location.href;this.main=Iw(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,l=a.id;if(t){const d=this.createCloneURI_(a.resolvedUri,e),p=Ts(r,d),y=this.createCloneAttributes_(r,a.attributes),_=this.createClonePlaylist_(a,p,e,y);i.playlists[n]=_,i.playlists[p]=_,i.playlists[d]=_}else i.playlists.splice(n,1);delete i.playlists[l],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((d,p)=>{const y=i.playlists[d.id],_=y.id,b=y.resolvedUri;delete i.playlists[_],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=Ts(e.ID,n),o=this.createCloneAttributes_(e.ID,t.attributes),l=this.createClonePlaylist_(t,a,e,o);i.playlists[r]=l,i.playlists[a]=l,i.playlists[n]=l,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 l=r.mediaGroups[n][a][o];r.mediaGroups[n][t][o]=_t({},l);const d=r.mediaGroups[n][t][o],p=this.createCloneURI_(l.resolvedUri,e);d.resolvedUri=p,d.uri=p,d.playlists=[],l.playlists.forEach((y,_)=>{const b=r.playlists[y.id],v=rg(n,t,o),x=Ts(t,v);if(b&&!r.playlists[x]){const A=this.createClonePlaylist_(b,x,e),D=A.resolvedUri;r.playlists[x]=A,r.playlists[D]=A}d.playlists[_]=this.createClonePlaylist_(y,x,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),re(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 $u=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)},Mw=(s,e)=>{if(!s||!s.size)return;let t=e;return s.forEach(i=>{t=i(t)}),t},Nw=(s,e,t,i)=>{!s||!s.size||s.forEach(r=>{r(e,t,i)})},cg=function(){const s=function e(t,i){t=re({timeout:45e3},t);const r=e.beforeRequest||L.Vhs.xhr.beforeRequest,n=e._requestCallbackSet||L.Vhs.xhr._requestCallbackSet||new Set,a=e._responseCallbackSet||L.Vhs.xhr._responseCallbackSet;r&&typeof r=="function"&&(L.log.warn("beforeRequest is deprecated, use onRequest instead."),n.add(r));const o=L.Vhs.xhr.original===!0?L.xhr:L.Vhs.xhr,l=Mw(n,t);n.delete(r);const d=o(l||t,function(y,_){return Nw(a,d,y,_),$u(d,y,_,i)}),p=d.abort;return d.abort=function(){return d.aborted=!0,p.apply(d,arguments)},d.uri=t.uri,d.requestTime=Date.now(),d};return s.original=!0,s},Bw=function(s){let e;const t=s.offset;return typeof s.offset=="bigint"||typeof s.length=="bigint"?e=C.BigInt(s.offset)+C.BigInt(s.length)-C.BigInt(1):e=s.offset+s.length-1,"bytes="+t+"-"+e},ju=function(s){const e={};return s.byterange&&(e.Range=Bw(s.byterange)),e},Uw=function(s,e){return s.start(e)+"-"+s.end(e)},Fw=function(s,e){const t=s.toString(16);return"00".substring(0,2-t.length)+t+(e%2?" ":"")},$w=function(s){return s>=32&&s<126?String.fromCharCode(s):"."},dg=function(s){const e={};return Object.keys(s).forEach(t=>{const i=s[t];Vf(i)?e[t]={bytes:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength}:e[t]=i}),e},Sa=function(s){const e=s.byterange||{length:1/0,offset:0};return[e.length,e.offset,s.resolvedUri].join(",")},hg=function(s){return s.resolvedUri},fg=s=>{const e=Array.prototype.slice.call(s),t=16;let i="",r,n;for(let a=0;afg(s),qw=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)},zw=s=>s.transmuxedPresentationEnd-s.transmuxedPresentationStart-s.transmuxerPrependedSeconds,Gw=(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:st.duration(e,e.mediaSequence+e.segments.indexOf(i)),type:i.videoTimingInfo?"accurate":"estimate"})},Ww=(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*pg)return null;i=r}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:t-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}},Kw=(s,e)=>{let t,i;try{t=new Date(s),i=new Date(e)}catch{}const r=t.getTime();return(i.getTime()-r)/1e3},Xw=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=Ww(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=Hw(e,i.segment);return n&&(r.programDateTime=n.toISOString()),t(null,r)},mg=({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(!Xw(e))return a({message:"programDateTime tags must be provided in the manifest "+e.resolvedUri});const o=Gw(s,e);if(!o)return a({message:`${s} was not found in the stream`});const l=o.segment,d=Kw(l.dateTimeObject,s);if(o.type==="estimate"){if(t===0)return a({message:`${s} is not buffered yet. Try again`});i(o.estimatedStart+d),n.one("seeked",()=>{mg({programTime:s,playlist:e,retryCount:t-1,seekTo:i,pauseAfterSeek:r,tech:n,callback:a})});return}const p=l.start+d,y=()=>a(null,n.currentTime());n.one("seeked",y),r&&n.pause(),i(p)},nu=(s,e)=>{if(s.readyState===4)return e()},Qw=(s,e,t)=>{let i=[],r,n=!1;const a=function(p,y,_,b){return y.abort(),n=!0,t(p,y,_,b)},o=function(p,y){if(n)return;if(p)return a(p,y,"",i);const _=y.responseText.substring(i&&i.byteLength||0,y.responseText.length);if(i=ix(i,Hf(_,!0)),r=r||br(i),i.length<10||r&&i.lengtha(p,y,"",i));const b=_l(i);return b==="ts"&&i.length<188?nu(y,()=>a(p,y,"",i)):!b&&i.length<376?nu(y,()=>a(p,y,"",i)):a(null,y,b,i)},d=e({uri:s,beforeSend(p){p.overrideMimeType("text/plain; charset=x-user-defined"),p.addEventListener("progress",function({total:y,loaded:_}){return $u(p,null,{statusCode:p.status},o)})}},function(p,y){return $u(d,p,y,o)});return d},{EventTarget:Jw}=L,Ch=function(s,e){if(!lg(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}`},eA=({mainXml:s,srcUrl:e,clientOffset:t,sidxMapping:i,previousManifest:r})=>{const n=CE(s,{manifestUri:e,clientOffset:t,sidxMapping:i,previousManifest:r});return ag(n,e,Zw),n},tA=(s,e)=>{Gs(s,(t,i,r,n)=>{n in e.mediaGroups[i][r]||delete s.mediaGroups[i][r][n]})},iA=(s,e,t)=>{let i=!0,r=re(s,{duration:e.duration,minimumUpdatePeriod:e.minimumUpdatePeriod,timelineStarts:e.timelineStarts});for(let n=0;n{if(n.playlists&&n.playlists.length){const d=n.playlists[0].id,p=Uu(r,n.playlists[0],Ch);p&&(r=p,l in r.mediaGroups[a][o]||(r.mediaGroups[a][o][l]=n),r.mediaGroups[a][o][l].playlists[0]=r.playlists[d],i=!1)}}),tA(r,e),e.minimumUpdatePeriod!==s.minimumUpdatePeriod&&(i=!1),i?null:r},sA=(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,wh=(s,e)=>{const t={};for(const i in s){const n=s[i].sidx;if(n){const a=ja(n);if(!e[a])break;const o=e[a].sidxInfo;sA(o,n)&&(t[a]=e[a])}}return t},rA=(s,e)=>{let i=wh(s.playlists,e);return Gs(s,(r,n,a,o)=>{if(r.playlists&&r.playlists.length){const l=r.playlists;i=re(i,wh(l,e))}}),i};class qu extends Jw{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_=St("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&&ja(e.sidx);if(!e.sidx||!r||this.mainPlaylistLoader_.sidxMapping_[r]){this.mediaRequest_=C.setTimeout(()=>i(!1),0);return}const n=ba(e.sidx.resolvedUri),a=(o,l)=>{if(this.requestErrored_(o,l,t))return;const d=this.mainPlaylistLoader_.sidxMapping_;let p;try{p=PE(z(l.response).subarray(8))}catch(y){y.metadata={errorType:L.Error.DashManifestSidxParsingError},this.requestErrored_(y,l,t);return}return d[r]={sidxInfo:e.sidx,sidx:p},ml(e,p,e.sidx.resolvedUri),i(!0)};this.request=Qw(n,this.vhs_.xhr,(o,l,d,p)=>{if(o)return a(o,l);if(!d||d!=="mp4"){const b=d||"unknown";return a({status:l.status,message:`Unsupported ${b} container type for sidx segment at URL: ${n}`,response:"",playlist:e,internal:!0,playlistExclusionDuration:1/0,code:2,metadata:{errorType:L.Error.UnsupportedSidxContainer,sidxContainer:b}},l)}const{offset:y,length:_}=e.sidx.byterange;if(p.length>=_+y)return a(o,{response:p.subarray(y,y+_),status:l.status,uri:l.uri});this.request=this.vhs_.xhr({uri:n,responseType:"arraybuffer",headers:ju({byterange:e.sidx.byterange})},a)})}dispose(){this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},C.clearTimeout(this.minimumUpdatePeriodTimeout_),C.clearTimeout(this.mediaRequest_),C.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(),C.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(C.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),this.state==="HAVE_NOTHING"&&(this.started=!1)}load(e){C.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const i=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=C.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_=C.setTimeout(()=>this.haveMain_(),0);return}this.requestMain_((e,t)=>{this.haveMain_(),!this.hasPendingRequest()&&!this.media_&&this.media(this.mainPlaylistLoader_.main.playlists[0])})}requestMain_(e){this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,requestType:"dash-manifest"},(t,i)=>{if(this.requestErrored_(t,i)){this.state==="HAVE_NOTHING"&&(this.started=!1);return}const r=i.responseText!==this.mainPlaylistLoader_.mainXml_;if(this.mainPlaylistLoader_.mainXml_=i.responseText,i.responseHeaders&&i.responseHeaders.date?this.mainLoaded_=Date.parse(i.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=ba(this.mainPlaylistLoader_.srcUrl,i),r){this.handleMain_(),this.syncClientServerClock_(()=>e(i,r));return}return e(i,r)})}syncClientServerClock_(e){const t=wE(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:it(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials,requestType:"dash-clock-sync"},(i,r)=>{if(!this.request)return;if(i)return 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;let t=eA({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:e});e&&(t=iA(e,t,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=t||e;const i=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];return i&&i!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=i),(!e||t&&t.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(t),!!t}updateMinimumUpdatePeriodTimeout_(){const e=this.mainPlaylistLoader_;e.createMupOnMedia_&&(e.off("loadedmetadata",e.createMupOnMedia_),e.createMupOnMedia_=null),e.minimumUpdatePeriodTimeout_&&(C.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_=C.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_=rA(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=C.setTimeout(()=>{this.trigger("mediaupdatetimeout"),r()},Fu(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 Ne={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 nA=s=>{const e=new Uint8Array(new ArrayBuffer(s.length));for(let t=0;t-1):!1},this.trigger=function(c){var f,h,m,g;if(f=u[c],!!f)if(arguments.length===2)for(m=f.length,h=0;h"u")){for(u in H)H.hasOwnProperty(u)&&(H[u]=[u.charCodeAt(0),u.charCodeAt(1),u.charCodeAt(2),u.charCodeAt(3)]);ie=new Uint8Array([105,115,111,109]),se=new Uint8Array([97,118,99,49]),ot=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]),Ht=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]),bi={video:Ee,audio:Ht},Ei=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),xi=new Uint8Array([0,0,0,0,0,0,0,0]),cn=new Uint8Array([0,0,0,0,0,0,0,0]),sc=cn,rc=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),nc=cn,Si=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}})(),o=function(u){var c=[],f=0,h,m,g;for(h=1;h>>1,u.samplingfrequencyindex<<7|u.channelcount<<3,6,1,2]))},p=function(){return o(H.ftyp,ie,ot,ie,se)},U=function(u){return o(H.hdlr,bi[u])},y=function(u){return o(H.mdat,u)},P=function(u){var c=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,u.duration>>>24&255,u.duration>>>16&255,u.duration>>>8&255,u.duration&255,85,196,0,0]);return u.samplerate&&(c[12]=u.samplerate>>>24&255,c[13]=u.samplerate>>>16&255,c[14]=u.samplerate>>>8&255,c[15]=u.samplerate&255),o(H.mdhd,c)},O=function(u){return o(H.mdia,P(u),U(u.type),b(u))},_=function(u){return o(H.mfhd,new Uint8Array([0,0,0,0,(u&4278190080)>>24,(u&16711680)>>16,(u&65280)>>8,u&255]))},b=function(u){return o(H.minf,u.type==="video"?o(H.vmhd,Si):o(H.smhd,xi),l(),J(u))},v=function(u,c){for(var f=[],h=c.length;h--;)f[h]=ue(c[h]);return o.apply(null,[H.moof,_(u)].concat(f))},x=function(u){for(var c=u.length,f=[];c--;)f[c]=k(u[c]);return o.apply(null,[H.moov,D(4294967295)].concat(f).concat(A(u)))},A=function(u){for(var c=u.length,f=[];c--;)f[c]=te(u[c]);return o.apply(null,[H.mvex].concat(f))},D=function(u){var c=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(u&4278190080)>>24,(u&16711680)>>16,(u&65280)>>8,u&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(H.mvhd,c)},V=function(u){var c=u.samples||[],f=new Uint8Array(4+c.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(E=[H.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(H.avcC,new Uint8Array([1,f.profileIdc,f.profileCompatibility,f.levelIdc,255].concat([h.length],g,[m.length],T))),o(H.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],f.sarRatio){var w=f.sarRatio[0],I=f.sarRatio[1];E.push(o(H.pasp,new Uint8Array([(w&4278190080)>>24,(w&16711680)>>16,(w&65280)>>8,w&255,(I&4278190080)>>24,(I&16711680)>>16,(I&65280)>>8,I&255])))}return o.apply(null,E)},c=function(f){return o(H.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]),d(f))}}(),M=function(u){var c=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(u.id&4278190080)>>24,(u.id&16711680)>>16,(u.id&65280)>>8,u.id&255,0,0,0,0,(u.duration&4278190080)>>24,(u.duration&16711680)>>16,(u.duration&65280)>>8,u.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,(u.width&65280)>>8,u.width&255,0,0,(u.height&65280)>>8,u.height&255,0,0]);return o(H.tkhd,c)},ue=function(u){var c,f,h,m,g,T,S;return c=o(H.tfhd,new Uint8Array([0,0,0,58,(u.id&4278190080)>>24,(u.id&16711680)>>16,(u.id&65280)>>8,u.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),T=Math.floor(u.baseMediaDecodeTime/a),S=Math.floor(u.baseMediaDecodeTime%a),f=o(H.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,u.type==="audio"?(h=he(u,g),o(H.traf,c,f,h)):(m=V(u),h=he(u,m.length+g),o(H.traf,c,f,h,m))},k=function(u){return u.duration=u.duration||4294967295,o(H.trak,M(u),O(u))},te=function(u){var c=new Uint8Array([0,0,0,0,(u.id&4278190080)>>24,(u.id&16711680)>>16,(u.id&65280)>>8,u.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return u.type!=="video"&&(c[c.length-1]=0),o(H.trex,c)},function(){var u,c,f;f=function(h,m){var g=0,T=0,S=0,E=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&&(E=8)),[0,0,g|T|S|E,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]},c=function(h,m){var g,T,S,E,w,I;for(E=h.samples||[],m+=20+16*E.length,S=f(E,m),T=new Uint8Array(S.length+E.length*16),T.set(S),g=S.length,I=0;I>>24,T[g++]=(w.duration&16711680)>>>16,T[g++]=(w.duration&65280)>>>8,T[g++]=w.duration&255,T[g++]=(w.size&4278190080)>>>24,T[g++]=(w.size&16711680)>>>16,T[g++]=(w.size&65280)>>>8,T[g++]=w.size&255,T[g++]=w.flags.isLeading<<2|w.flags.dependsOn,T[g++]=w.flags.isDependedOn<<6|w.flags.hasRedundancy<<4|w.flags.paddingValue<<1|w.flags.isNonSyncSample,T[g++]=w.flags.degradationPriority&61440,T[g++]=w.flags.degradationPriority&15,T[g++]=(w.compositionTimeOffset&4278190080)>>>24,T[g++]=(w.compositionTimeOffset&16711680)>>>16,T[g++]=(w.compositionTimeOffset&65280)>>>8,T[g++]=w.compositionTimeOffset&255;return o(H.trun,T)},u=function(h,m){var g,T,S,E,w,I;for(E=h.samples||[],m+=20+8*E.length,S=f(E,m),g=new Uint8Array(S.length+E.length*8),g.set(S),T=S.length,I=0;I>>24,g[T++]=(w.duration&16711680)>>>16,g[T++]=(w.duration&65280)>>>8,g[T++]=w.duration&255,g[T++]=(w.size&4278190080)>>>24,g[T++]=(w.size&16711680)>>>16,g[T++]=(w.size&65280)>>>8,g[T++]=w.size&255;return o(H.trun,g)},he=function(h,m){return h.type==="audio"?u(h,m):c(h,m)}}();var uT={ftyp:p,mdat:y,moof:v,moov:x,initSegment:function(u){var c=p(),f=x(u),h;return h=new Uint8Array(c.byteLength+f.byteLength),h.set(c),h.set(f,c.byteLength),h}},lT=function(u){var c,f,h=[],m=[];for(m.byteLength=0,m.nalCount=0,m.duration=0,h.byteLength=0,c=0;c1&&(c=u.shift(),u.byteLength-=c.byteLength,u.nalCount-=c.nalCount,u[0][0].dts=c.dts,u[0][0].pts=c.pts,u[0][0].duration+=c.duration),u},hT=function(){return{size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}}},ac=function(u,c){var f=hT();return f.dataOffset=c,f.compositionTimeOffset=u.pts-u.dts,f.duration=u.duration,f.size=4*u.length,f.size+=u.byteLength,u.keyFrame&&(f.flags.dependsOn=2,f.flags.isNonSyncSample=0),f},fT=function(u,c){var f,h,m,g,T,S=c||0,E=[];for(f=0;fhn.ONE_SECOND_IN_TS/2))){for(w=TT()[u.samplerate],w||(w=c[0].data),I=0;I=f?u:(c.minSegmentDts=1/0,u.filter(function(h){return h.dts>=f?(c.minSegmentDts=Math.min(c.minSegmentDts,h.dts),c.minSegmentPts=c.minSegmentDts,!0):!1}))},ET=function(u){var c,f,h=[];for(c=0;c=this.virtualRowCount&&typeof this.beforeRowOverflow=="function"&&this.beforeRowOverflow(u),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},zt.prototype.isEmpty=function(){return this.rows.length===0?!0:this.rows.length===1?this.rows[0]==="":!1},zt.prototype.addText=function(u){this.rows[this.rowIdx]+=u},zt.prototype.backspace=function(){if(!this.isEmpty()){var u=this.rows[this.rowIdx];this.rows[this.rowIdx]=u.substr(0,u.length-1)}};var mn=function(u,c,f){this.serviceNum=u,this.text="",this.currentWindow=new zt(-1),this.windows=[],this.stream=f,typeof c=="string"&&this.createTextDecoder(c)};mn.prototype.init=function(u,c){this.startPts=u;for(var f=0;f<8;f++)this.windows[f]=new zt(f),typeof c=="function"&&(this.windows[f].beforeRowOverflow=c)},mn.prototype.setCurrentWindow=function(u){this.currentWindow=this.windows[u]},mn.prototype.createTextDecoder=function(u){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(u)}catch(c){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+u+" encoding. "+c})}};var le=function(u){u=u||{},le.prototype.init.call(this);var c=this,f=u.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?(c.new708Packet(),c.add708Bytes(g)):(c.current708Packet===null&&c.new708Packet(),c.add708Bytes(g))}};le.prototype=new po,le.prototype.new708Packet=function(){this.current708Packet!==null&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},le.prototype.add708Bytes=function(u){var c=u.ccData,f=c>>>8,h=c&255;this.current708Packet.ptsVals.push(u.pts),this.current708Packet.data.push(f),this.current708Packet.data.push(h)},le.prototype.push708Packet=function(){var u=this.current708Packet,c=u.data,f=null,h=null,m=0,g=c[m++];for(u.seq=g>>6,u.sizeCode=g&63;m>5,h=g&31,f===7&&h>0&&(g=c[m++],f=g),this.pushServiceBlock(f,m,h),h>0&&(m+=h-1)},le.prototype.pushServiceBlock=function(u,c,f){var h,m=c,g=this.current708Packet.data,T=this.services[u];for(T||(T=this.initService(u,m));m("0"+(G&255).toString(16)).slice(-2)).join("")}if(m?(R=[S,E],u++):R=[S],c.textDecoder_&&!h)I=c.textDecoder_.decode(new Uint8Array(R));else if(m){const B=j(R);I=String.fromCharCode(parseInt(B,16))}else I=UT(T|S);return w.pendingNewLine&&!w.isEmpty()&&w.newLine(this.getPts(u)),w.pendingNewLine=!1,w.addText(I),u},le.prototype.multiByteCharacter=function(u,c){var f=this.current708Packet.data,h=f[u+1],m=f[u+2];return pn(h)&&pn(m)&&(u=this.handleText(++u,c,{isMultiByte:!0})),u},le.prototype.setCurrentWindow=function(u,c){var f=this.current708Packet.data,h=f[u],m=h&7;return c.setCurrentWindow(m),u},le.prototype.defineWindow=function(u,c){var f=this.current708Packet.data,h=f[u],m=h&7;c.setCurrentWindow(m);var g=c.currentWindow;return h=f[++u],g.visible=(h&32)>>5,g.rowLock=(h&16)>>4,g.columnLock=(h&8)>>3,g.priority=h&7,h=f[++u],g.relativePositioning=(h&128)>>7,g.anchorVertical=h&127,h=f[++u],g.anchorHorizontal=h,h=f[++u],g.anchorPoint=(h&240)>>4,g.rowCount=h&15,h=f[++u],g.columnCount=h&63,h=f[++u],g.windowStyle=(h&56)>>3,g.penStyle=h&7,g.virtualRowCount=g.rowCount+1,u},le.prototype.setWindowAttributes=function(u,c){var f=this.current708Packet.data,h=f[u],m=c.currentWindow.winAttr;return h=f[++u],m.fillOpacity=(h&192)>>6,m.fillRed=(h&48)>>4,m.fillGreen=(h&12)>>2,m.fillBlue=h&3,h=f[++u],m.borderType=(h&192)>>6,m.borderRed=(h&48)>>4,m.borderGreen=(h&12)>>2,m.borderBlue=h&3,h=f[++u],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[++u],m.effectSpeed=(h&240)>>4,m.effectDirection=(h&12)>>2,m.displayEffect=h&3,u},le.prototype.flushDisplayed=function(u,c){for(var f=[],h=0;h<8;h++)c.windows[h].visible&&!c.windows[h].isEmpty()&&f.push(c.windows[h].getText());c.endPts=u,c.text=f.join(`
+
+`),this.pushCaption(c),c.startPts=u},le.prototype.pushCaption=function(u){u.text!==""&&(this.trigger("data",{startPts:u.startPts,endPts:u.endPts,text:u.text,stream:"cc708_"+u.serviceNum}),u.text="",u.startPts=u.endPts)},le.prototype.displayWindows=function(u,c){var f=this.current708Packet.data,h=f[++u],m=this.getPts(u);this.flushDisplayed(m,c);for(var g=0;g<8;g++)h&1<>4,m.offset=(h&12)>>2,m.penSize=h&3,h=f[++u],m.italics=(h&128)>>7,m.underline=(h&64)>>6,m.edgeType=(h&56)>>3,m.fontStyle=h&7,u},le.prototype.setPenColor=function(u,c){var f=this.current708Packet.data,h=f[u],m=c.currentWindow.penColor;return h=f[++u],m.fgOpacity=(h&192)>>6,m.fgRed=(h&48)>>4,m.fgGreen=(h&12)>>2,m.fgBlue=h&3,h=f[++u],m.bgOpacity=(h&192)>>6,m.bgRed=(h&48)>>4,m.bgGreen=(h&12)>>2,m.bgBlue=h&3,h=f[++u],m.edgeRed=(h&48)>>4,m.edgeGreen=(h&12)>>2,m.edgeBlue=h&3,u},le.prototype.setPenLocation=function(u,c){var f=this.current708Packet.data,h=f[u],m=c.currentWindow.penLoc;return c.currentWindow.pendingNewLine=!0,h=f[++u],m.row=h&15,h=f[++u],m.column=h&63,u},le.prototype.reset=function(u,c){var f=this.getPts(u);return this.flushDisplayed(f,c),this.initService(c.serviceNum,u)};var FT={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},gn=function(u){return u===null?"":(u=FT[u]||u,String.fromCharCode(u))},yn=14,$T=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],Ci=function(){for(var u=[],c=yn+1;c--;)u.push({text:"",indent:0,offset:0});return u},ge=function(u,c){ge.prototype.init.call(this),this.field_=u||0,this.dataChannel_=c||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_=Ci();else if(h===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=Ci();else if(h===this.RESUME_DIRECT_CAPTIONING_)this.mode_!=="paintOn"&&(this.flushDisplayed(f.pts),this.displayed_=Ci()),this.mode_="paintOn",this.startPts_=f.pts;else if(this.isSpecialCharacter(g,T))g=(g&3)<<8,S=gn(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=gn(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 w=T&3;this.nonDisplayed_[this.row_].offset=w,this.column_+=w}else if(this.isPAC(g,T)){var E=$T.indexOf(h&7968);if(this.mode_==="rollUp"&&(E-this.rollUpRows_+1<0&&(E=this.rollUpRows_-1),this.setRollUp(f.pts,E)),E!==this.row_&&E>=0&&E<=14&&(this.clearFormatting(f.pts),this.row_=E),T&1&&this.formatting_.indexOf("u")===-1&&this.addFormatting(f.pts,["u"]),(h&16)===16){const w=(h&14)>>1;this.column_=w*4,this.nonDisplayed_[this.row_].indent+=w}this.isColorPAC(T)&&(T&14)===14&&this.addFormatting(f.pts,["i"])}else this.isNormalChar(g)&&(T===0&&(T=null),S=gn(g),S+=gn(T),this[this.mode_](f.pts,S),this.column_+=S.length)}};ge.prototype=new po,ge.prototype.flushDisplayed=function(u){const c=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{c(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&&c(m)}),f.length&&this.trigger("data",{startPts:this.startPts_,endPts:u,content:f,stream:this.name_})},ge.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=Ci(),this.nonDisplayed_=Ci(),this.lastControlCode_=null,this.column_=0,this.row_=yn,this.rollUpRows_=2,this.formatting_=[]},ge.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},ge.prototype.isSpecialCharacter=function(u,c){return u===this.EXT_&&c>=48&&c<=63},ge.prototype.isExtCharacter=function(u,c){return(u===this.EXT_+1||u===this.EXT_+2)&&c>=32&&c<=63},ge.prototype.isMidRowCode=function(u,c){return u===this.EXT_&&c>=32&&c<=47},ge.prototype.isOffsetControlCode=function(u,c){return u===this.OFFSET_&&c>=33&&c<=35},ge.prototype.isPAC=function(u,c){return u>=this.BASE_&&u=64&&c<=127},ge.prototype.isColorPAC=function(u){return u>=64&&u<=79||u>=96&&u<=127},ge.prototype.isNormalChar=function(u){return u>=32&&u<=127},ge.prototype.setRollUp=function(u,c){if(this.mode_!=="rollUp"&&(this.row_=yn,this.mode_="rollUp",this.flushDisplayed(u),this.nonDisplayed_=Ci(),this.displayed_=Ci()),c!==void 0&&c!==this.row_)for(var f=0;f"},"");this[this.mode_](u,f)},ge.prototype.clearFormatting=function(u){if(this.formatting_.length){var c=this.formatting_.reverse().reduce(function(f,h){return f+""+h+">"},"");this.formatting_=[],this[this.mode_](u,c)}},ge.prototype.popOn=function(u,c){var f=this.nonDisplayed_[this.row_].text;f+=c,this.nonDisplayed_[this.row_].text=f},ge.prototype.rollUp=function(u,c){var f=this.displayed_[this.row_].text;f+=c,this.displayed_[this.row_].text=f},ge.prototype.shiftRowsUp_=function(){var u;for(u=0;uc&&(f=-1);Math.abs(c-u)>VT;)u+=f*qT;return u},go=function(u){var c,f;go.prototype.init.call(this),this.type_=u||fc,this.push=function(h){if(h.type==="metadata"){this.trigger("data",h);return}this.type_!==fc&&h.type!==this.type_||(f===void 0&&(f=h.dts),h.dts=mo(h.dts,f),h.pts=mo(h.pts,f),c=h.dts,this.trigger("data",h))},this.flush=function(){f=c,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){f=void 0,c=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};go.prototype=new jT;var pc={TimestampRolloverStream:go,handleRollover:mo},HT=(u,c,f)=>{if(!u)return-1;for(var h=f;h";u.data[0]===Tn.Utf8&&(f=vn(u.data,0,c),!(f<0)&&(u.mimeType=Ks(u.data,c,f),c=f+1,u.pictureType=u.data[c],c++,h=vn(u.data,0,c),!(h<0)&&(u.description=Ws(u.data,c,h),c=h+1,u.mimeType===m?u.url=Ks(u.data,c,u.data.length):u.pictureData=u.data.subarray(c,u.data.length))))},"T*":function(u){u.data[0]===Tn.Utf8&&(u.value=Ws(u.data,1,u.data.length).replace(/\0*$/,""),u.values=u.value.split("\0"))},TXXX:function(u){var c;u.data[0]===Tn.Utf8&&(c=vn(u.data,0,1),c!==-1&&(u.description=Ws(u.data,1,c),u.value=Ws(u.data,c+1,u.data.length).replace(/\0*$/,""),u.data=u.value))},"W*":function(u){u.url=Ks(u.data,0,u.data.length).replace(/\0.*$/,"")},WXXX:function(u){var c;u.data[0]===Tn.Utf8&&(c=vn(u.data,0,1),c!==-1&&(u.description=Ws(u.data,1,c),u.url=Ks(u.data,c+1,u.data.length).replace(/\0.*$/,"")))},PRIV:function(u){var c;for(c=0;c>>2;G*=4,G+=B[7]&3,I.timeStamp=G,S.pts===void 0&&S.dts===void 0&&(S.pts=I.timeStamp,S.dts=I.timeStamp),this.trigger("timestamp",I)}S.frames.push(I),E+=10,E+=w}while(E>>4>1&&(T+=m[T]+1),g.pid===0)g.type="pat",u(m.subarray(T),g),this.trigger("data",g);else if(g.pid===this.pmtPid)for(g.type="pmt",u(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=xt.H264_STREAM_TYPE:T.pid===this.programMapTable.audio?T.streamType=xt.ADTS_STREAM_TYPE:T.streamType=this.programMapTable["timed-metadata"][T.pid],T.type="pes",T.data=m.subarray(g),this.trigger("data",T)}},Qs.prototype=new yo,Qs.STREAM_TYPES={h264:27,adts:15},xn=function(){var u=this,c=!1,f={data:[],size:0},h={data:[],size:0},m={data:[],size:0},g,T=function(E,w){var I;const R=E[0]<<16|E[1]<<8|E[2];w.data=new Uint8Array,R===1&&(w.packetLength=6+(E[4]<<8|E[5]),w.dataAlignmentIndicator=(E[6]&4)!==0,I=E[7],I&192&&(w.pts=(E[9]&14)<<27|(E[10]&255)<<20|(E[11]&254)<<12|(E[12]&255)<<5|(E[13]&254)>>>3,w.pts*=4,w.pts+=(E[13]&6)>>>1,w.dts=w.pts,I&64&&(w.dts=(E[14]&14)<<27|(E[15]&255)<<20|(E[16]&254)<<12|(E[17]&255)<<5|(E[18]&254)>>>3,w.dts*=4,w.dts+=(E[18]&6)>>>1)),w.data=E.subarray(9+E[8]))},S=function(E,w,I){var R=new Uint8Array(E.size),j={type:w},B=0,G=0,K=!1,Le;if(!(!E.data.length||E.size<9)){for(j.trackId=E.data[0].pid,B=0;B>5,E=((c[m+6]&3)+1)*1024,w=E*ZT/_c[(c[m+2]&60)>>>2],c.byteLength-m>>6&3)+1,channelcount:(c[m+2]&1)<<2|(c[m+3]&192)>>>6,samplerate:_c[(c[m+2]&60)>>>2],samplingfrequencyindex:(c[m+2]&60)>>>2,samplesize:16,data:c.subarray(m+7+T,m+g)}),f++,m+=g}typeof I=="number"&&(this.skipWarn_(I,m),I=null),c=c.subarray(m)}},this.flush=function(){f=0,this.trigger("done")},this.reset=function(){c=void 0,this.trigger("reset")},this.endTimeline=function(){c=void 0,this.trigger("endedtimeline")}},En.prototype=new JT;var eb=En,vc;vc=function(u){var c=u.byteLength,f=0,h=0;this.length=function(){return 8*c},this.bitsAvailable=function(){return 8*c+h},this.loadWord=function(){var m=u.byteLength-c,g=new Uint8Array(4),T=Math.min(4,c);if(T===0)throw new Error("no bytes available");g.set(u.subarray(m,m+T)),f=new DataView(g.buffer).getUint32(0),h=T*8,c-=T},this.skipBits=function(m){var g;h>m?(f<<=m,h-=m):(m-=h,g=Math.floor(m/8),m-=g*8,c-=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:c>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 tb=vc,Tc=t,ib=tb,Cn,Js,bc;Js=function(){var u=0,c,f;Js.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;u3&&this.trigger("data",f.subarray(u+3)),f=null,u=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}},Js.prototype=new Tc,bc={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},Cn=function(){var u=new Js,c,f,h,m,g,T,S;Cn.prototype.init.call(this),c=this,this.push=function(E){E.type==="video"&&(f=E.trackId,h=E.pts,m=E.dts,u.push(E))},u.on("data",function(E){var w={trackId:f,pts:h,dts:m,data:E,nalUnitTypeCode:E[0]&31};switch(w.nalUnitTypeCode){case 5:w.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:w.nalUnitType="sei_rbsp",w.escapedRBSP=g(E.subarray(1));break;case 7:w.nalUnitType="seq_parameter_set_rbsp",w.escapedRBSP=g(E.subarray(1)),w.config=T(w.escapedRBSP);break;case 8:w.nalUnitType="pic_parameter_set_rbsp";break;case 9:w.nalUnitType="access_unit_delimiter_rbsp";break}c.trigger("data",w)}),u.on("done",function(){c.trigger("done")}),u.on("partialdone",function(){c.trigger("partialdone")}),u.on("reset",function(){c.trigger("reset")}),u.on("endedtimeline",function(){c.trigger("endedtimeline")}),this.flush=function(){u.flush()},this.partialFlush=function(){u.partialFlush()},this.reset=function(){u.reset()},this.endTimeline=function(){u.endTimeline()},S=function(E,w){var I=8,R=8,j,B;for(j=0;j>4;return f=f>=0?f:0,m?f+20:f+10},xc=function(u,c){return u.length-c<10||u[c]!==73||u[c+1]!==68||u[c+2]!==51?c:(c+=Sc(u,c),xc(u,c))},nb=function(u){var c=xc(u,0);return u.length>=c+2&&(u[c]&255)===255&&(u[c+1]&240)===240&&(u[c+1]&22)===16},Ec=function(u){return u[0]<<21|u[1]<<14|u[2]<<7|u[3]},ab=function(u,c,f){var h,m="";for(h=c;h>5,h=u[c+4]<<3,m=u[c+3]&6144;return m|h|f},lb=function(u,c){return u[c]===73&&u[c+1]===68&&u[c+2]===51?"timed-metadata":u[c]&!0&&(u[c+1]&240)===240?"audio":null},cb=function(u){for(var c=0;c+5>>2]}return null},db=function(u){var c,f,h,m;c=10,u[5]&64&&(c+=4,c+=Ec(u.subarray(10,14)));do{if(f=Ec(u.subarray(c+4,c+8)),f<1)return null;if(m=String.fromCharCode(u[c],u[c+1],u[c+2],u[c+3]),m==="PRIV"){h=u.subarray(c+10,c+f+10);for(var g=0;g>>2;return E*=4,E+=S[7]&3,E}break}}c+=10,c+=f}while(c=3;){if(u[m]===73&&u[m+1]===68&&u[m+2]===51){if(u.length-m<10||(h=Cc.parseId3TagSize(u,m),m+h>u.length))break;T={type:"timed-metadata",data:u.subarray(m,m+h)},this.trigger("data",T),m+=h;continue}else if((u[m]&255)===255&&(u[m+1]&240)===240){if(u.length-m<7||(h=Cc.parseAdtsSize(u,m),m+h>u.length))break;S={type:"audio",data:u.subarray(m,m+h),pts:c,dts:c},this.trigger("data",S),m+=h;continue}m++}g=u.length-m,g>0?u=u.subarray(m):u=new Uint8Array},this.reset=function(){u=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){u=new Uint8Array,this.trigger("endedtimeline")}},wn.prototype=new hb;var fb=wn,pb=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],mb=pb,gb=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],yb=gb,An=t,Zs=uT,er=yT,Dn=wT,Et=PT,Gt=QT,kn=fe,wc=eb,_b=sb.H264Stream,vb=fb,Tb=bo.isLikelyAacData,bb=fe.ONE_SECOND_IN_TS,So=mb,xo=yb,tr,Qi,In,wi,Sb=function(u,c){c.stream=u,this.trigger("log",c)},Ac=function(u,c){for(var f=Object.keys(c),h=0;h=-w&&R<=E&&(!j||I>R)&&(j=G,I=R)));return j?j.gop:null},this.alignGopsAtStart_=function(S){var E,w,I,R,j,B,G,K;for(j=S.byteLength,B=S.nalCount,G=S.duration,E=w=0;EI.pts){E++;continue}w++,j-=R.byteLength,B-=R.nalCount,G-=R.duration}return w===0?S:w===S.length?null:(K=S.slice(w),K.byteLength=j,K.duration=G,K.nalCount=B,K.pts=K[0].pts,K.dts=K[0].dts,K)},this.alignGopsAtEnd_=function(S){var E,w,I,R,j,B;for(E=m.length-1,w=S.length-1,j=null,B=!1;E>=0&&w>=0;){if(I=m[E],R=S[w],I.pts===R.pts){B=!0;break}if(I.pts>R.pts){E--;continue}E===m.length-1&&(j=w),w--}if(!B&&j===null)return null;var G;if(B?G=w:G=j,G===0)return S;var K=S.slice(G),Le=K.reduce(function(pt,Di){return pt.byteLength+=Di.byteLength,pt.duration+=Di.duration,pt.nalCount+=Di.nalCount,pt},{byteLength:0,duration:0,nalCount:0});return K.byteLength=Le.byteLength,K.duration=Le.duration,K.nalCount=Le.nalCount,K.pts=K[0].pts,K.dts=K[0].dts,K},this.alignGopsWith=function(S){m=S}},tr.prototype=new An,wi=function(u,c){this.numberOfTracks=0,this.metadataStream=c,u=u||{},typeof u.remux<"u"?this.remuxTracks=!!u.remux:this.remuxTracks=!0,typeof u.keepOriginalTimestamps=="boolean"?this.keepOriginalTimestamps=u.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,wi.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))}},wi.prototype=new An,wi.prototype.flush=function(u){var c=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,xo.forEach(function(E){f.info[E]=this.videoTrack[E]},this)):this.audioTrack&&(T=this.audioTrack.timelineStartInfo.pts,So.forEach(function(E){f.info[E]=this.audioTrack[E]},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=Zs.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)},wi.prototype.setRemux=function(u){this.remuxTracks=u},In=function(u){var c=this,f=!0,h,m;In.prototype.init.call(this),u=u||{},this.baseMediaDecodeTime=u.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var g={};this.transmuxPipeline_=g,g.type="aac",g.metadataStream=new Gt.MetadataStream,g.aacStream=new vb,g.audioTimestampRolloverStream=new Gt.TimestampRolloverStream("audio"),g.timedMetadataTimestampRolloverStream=new Gt.TimestampRolloverStream("timed-metadata"),g.adtsStream=new wc,g.coalesceStream=new wi(u,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:c.baseMediaDecodeTime},codec:"adts",type:"audio"},g.coalesceStream.numberOfTracks++,g.audioSegmentStream=new Qi(m,u),g.audioSegmentStream.on("log",c.getLogTrigger_("audioSegmentStream")),g.audioSegmentStream.on("timingInfo",c.trigger.bind(c,"audioTimingInfo")),g.adtsStream.pipe(g.audioSegmentStream).pipe(g.coalesceStream),c.trigger("trackinfo",{hasAudio:!!m,hasVideo:!!h}))}),g.coalesceStream.on("data",this.trigger.bind(this,"data")),g.coalesceStream.on("done",this.trigger.bind(this,"done")),Ac(this,g)},this.setupTsPipeline=function(){var g={};this.transmuxPipeline_=g,g.type="ts",g.metadataStream=new Gt.MetadataStream,g.packetStream=new Gt.TransportPacketStream,g.parseStream=new Gt.TransportParseStream,g.elementaryStream=new Gt.ElementaryStream,g.timestampRolloverStream=new Gt.TimestampRolloverStream,g.adtsStream=new wc,g.h264Stream=new _b,g.captionStream=new Gt.CaptionStream(u),g.coalesceStream=new wi(u,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=c.baseMediaDecodeTime):!m&&T.tracks[S].type==="audio"&&(m=T.tracks[S],m.timelineStartInfo.baseMediaDecodeTime=c.baseMediaDecodeTime);h&&!g.videoSegmentStream&&(g.coalesceStream.numberOfTracks++,g.videoSegmentStream=new tr(h,u),g.videoSegmentStream.on("log",c.getLogTrigger_("videoSegmentStream")),g.videoSegmentStream.on("timelineStartInfo",function(E){m&&!u.keepOriginalTimestamps&&(m.timelineStartInfo=E,g.audioSegmentStream.setEarliestDts(E.dts-c.baseMediaDecodeTime))}),g.videoSegmentStream.on("processedGopsInfo",c.trigger.bind(c,"gopInfo")),g.videoSegmentStream.on("segmentTimingInfo",c.trigger.bind(c,"videoSegmentTimingInfo")),g.videoSegmentStream.on("baseMediaDecodeTime",function(E){m&&g.audioSegmentStream.setVideoBaseMediaDecodeTime(E)}),g.videoSegmentStream.on("timingInfo",c.trigger.bind(c,"videoTimingInfo")),g.h264Stream.pipe(g.videoSegmentStream).pipe(g.coalesceStream)),m&&!g.audioSegmentStream&&(g.coalesceStream.numberOfTracks++,g.audioSegmentStream=new Qi(m,u),g.audioSegmentStream.on("log",c.getLogTrigger_("audioSegmentStream")),g.audioSegmentStream.on("timingInfo",c.trigger.bind(c,"audioTimingInfo")),g.audioSegmentStream.on("segmentTimingInfo",c.trigger.bind(c,"audioSegmentTimingInfo")),g.adtsStream.pipe(g.audioSegmentStream).pipe(g.coalesceStream)),c.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,c.trigger("id3Frame",T)}),g.coalesceStream.on("caption",this.trigger.bind(this,"caption")),g.coalesceStream.on("done",this.trigger.bind(this,"done")),Ac(this,g)},this.setBaseMediaDecodeTime=function(g){var T=this.transmuxPipeline_;u.keepOriginalTimestamps||(this.baseMediaDecodeTime=g),m&&(m.timelineStartInfo.dts=void 0,m.timelineStartInfo.pts=void 0,Et.clearDtsInfo(m),T.audioTimestampRolloverStream&&T.audioTimestampRolloverStream.discontinuity()),h&&(T.videoSegmentStream&&(T.videoSegmentStream.gopCache_=[]),h.timelineStartInfo.dts=void 0,h.timelineStartInfo.pts=void 0,Et.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_;u.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=Tb(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()}},In.prototype=new An;var xb={Transmuxer:In,VideoSegmentStream:tr,AudioSegmentStream:Qi,AUDIO_PROPERTIES:So,VIDEO_PROPERTIES:xo,generateSegmentTimingInfo:Eo},Eb=function(u){return u>>>0},Cb=function(u){return("00"+u.toString(16)).slice(-2)},Pn={toUnsigned:Eb,toHexString:Cb},wb=function(u){var c="";return c+=String.fromCharCode(u[0]),c+=String.fromCharCode(u[1]),c+=String.fromCharCode(u[2]),c+=String.fromCharCode(u[3]),c},kc=wb,Ab=Pn.toUnsigned,Db=kc,Ic=function(u,c){var f=[],h,m,g,T,S;if(!c.length)return null;for(h=0;h1?h+m:u.byteLength,g===c[0]&&(c.length===1?f.push(u.subarray(h+8,T)):(S=Ic(u.subarray(h+8,T),c.slice(1)),S.length&&(f=f.concat(S)))),h=T;return f},Pc=Ic,kb=Pn.toUnsigned,Ib=n.getUint64,Pb=function(u){var c={version:u[0],flags:new Uint8Array(u.subarray(1,4))};return c.version===1?c.baseMediaDecodeTime=Ib(u.subarray(4)):c.baseMediaDecodeTime=kb(u[4]<<24|u[5]<<16|u[6]<<8|u[7]),c},Lc=Pb,Lb=function(u){return{isLeading:(u[0]&12)>>>2,dependsOn:u[0]&3,isDependedOn:(u[1]&192)>>>6,hasRedundancy:(u[1]&48)>>>4,paddingValue:(u[1]&14)>>>1,isNonSyncSample:u[1]&1,degradationPriority:u[2]<<8|u[3]}},Ob=Lb,Oc=Ob,Rb=function(u){var c={version:u[0],flags:new Uint8Array(u.subarray(1,4)),samples:[]},f=new DataView(u.buffer,u.byteOffset,u.byteLength),h=c.flags[2]&1,m=c.flags[2]&4,g=c.flags[1]&1,T=c.flags[1]&2,S=c.flags[1]&4,E=c.flags[1]&8,w=f.getUint32(4),I=8,R;for(h&&(c.dataOffset=f.getInt32(I),I+=4),m&&w&&(R={flags:Oc(u.subarray(I,I+4))},I+=4,g&&(R.duration=f.getUint32(I),I+=4),T&&(R.size=f.getUint32(I),I+=4),E&&(c.version===1?R.compositionTimeOffset=f.getInt32(I):R.compositionTimeOffset=f.getUint32(I),I+=4),c.samples.push(R),w--);w--;)R={},g&&(R.duration=f.getUint32(I),I+=4),T&&(R.size=f.getUint32(I),I+=4),S&&(R.flags=Oc(u.subarray(I,I+4)),I+=4),E&&(c.version===1?R.compositionTimeOffset=f.getInt32(I):R.compositionTimeOffset=f.getUint32(I),I+=4),c.samples.push(R);return c},Rc=Rb,Mb=function(u){var c=new DataView(u.buffer,u.byteOffset,u.byteLength),f={version:u[0],flags:new Uint8Array(u.subarray(1,4)),trackId:c.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,E=f.flags[0]&65536,w=f.flags[0]&131072,I;return I=8,h&&(I+=4,f.baseDataOffset=c.getUint32(12),I+=4),m&&(f.sampleDescriptionIndex=c.getUint32(I),I+=4),g&&(f.defaultSampleDuration=c.getUint32(I),I+=4),T&&(f.defaultSampleSize=c.getUint32(I),I+=4),S&&(f.defaultSampleFlags=c.getUint32(I)),E&&(f.durationIsEmpty=!0),!h&&w&&(f.baseDataOffsetIsMoof=!0),f},Mc=Mb,ir;typeof window<"u"?ir=window:typeof s<"u"?ir=s:typeof self<"u"?ir=self:ir={};var Nc=ir,Nb=dc.discardEmulationPreventionBytes,Bb=hc.CaptionStream,sr=Pc,Ub=Lc,Fb=Rc,$b=Mc,Bc=Nc,jb=function(u,c){for(var f=u,h=0;h0?Ub(j[0]).baseMediaDecodeTime:0,G=sr(E,["trun"]),K,Le;c===R&&G.length>0&&(K=Vb(G,B,I),Le=qb(S,K,R),m[R]||(m[R]={seiNals:[],logs:[]}),m[R].seiNals=m[R].seiNals.concat(Le.seiNals),m[R].logs=m[R].logs.concat(Le.logs))}),m},zb=function(u,c,f){var h;if(c===null)return null;h=Hb(u,c);var m=h[c]||{};return{seiNals:m.seiNals,logs:m.logs,timescale:f}},Gb=function(){var u=!1,c,f,h,m,g,T;this.isInitialized=function(){return u},this.init=function(S){c=new Bb,u=!0,T=S?S.isPartial:!1,c.on("data",function(E){E.startTime=E.startPts/m,E.endTime=E.endPts/m,g.captions.push(E),g.captionStreams[E.stream]=!0}),c.on("log",function(E){g.logs.push(E)})},this.isNewInit=function(S,E){return S&&S.length===0||E&&typeof E=="object"&&Object.keys(E).length===0?!1:h!==S[0]||m!==E[h]},this.parse=function(S,E,w){var I;if(this.isInitialized()){if(!E||!w)return null;if(this.isNewInit(E,w))h=E[0],m=w[h];else if(h===null||!m)return f.push(S),null}else return null;for(;f.length>0;){var R=f.shift();this.parse(R,E,w)}return I=zb(S,h,m),I&&I.logs&&(g.logs=g.logs.concat(I.logs)),I===null||!I.seiNals?g.logs.length?{logs:g.logs,captions:[],captionStreams:[]}:null:(this.pushNals(I.seiNals),this.flushStream(),g)},this.pushNals=function(S){if(!this.isInitialized()||!S||S.length===0)return null;S.forEach(function(E){c.push(E)})},this.flushStream=function(){if(!this.isInitialized())return null;T?c.partialFlush():c.flush()},this.clearParsedCaptions=function(){g.captions=[],g.captionStreams={},g.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;c.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()},Wb=Gb,Kb=function(u){for(var c=0,f=String.fromCharCode(u[c]),h="";f!=="\0";)h+=f,c++,f=String.fromCharCode(u[c]);return h+=f,h},Xb={uint8ToCString:Kb},Ln=Xb.uint8ToCString,Yb=n.getUint64,Qb=function(u){var c=4,f=u[0],h,m,g,T,S,E,w,I;if(f===0){h=Ln(u.subarray(c)),c+=h.length,m=Ln(u.subarray(c)),c+=m.length;var R=new DataView(u.buffer);g=R.getUint32(c),c+=4,S=R.getUint32(c),c+=4,E=R.getUint32(c),c+=4,w=R.getUint32(c),c+=4}else if(f===1){var R=new DataView(u.buffer);g=R.getUint32(c),c+=4,T=Yb(u.subarray(c)),c+=8,E=R.getUint32(c),c+=4,w=R.getUint32(c),c+=4,h=Ln(u.subarray(c)),c+=h.length,m=Ln(u.subarray(c)),c+=m.length}I=new Uint8Array(u.subarray(c,u.byteLength));var j={scheme_id_uri:h,value:m,timescale:g||1,presentation_time:T,presentation_time_delta:S,event_duration:E,id:w,message_data:I};return Zb(f,j)?j:void 0},Jb=function(u,c,f,h){return u||u===0?u/c:h+f/c},Zb=function(u,c){var f=c.scheme_id_uri!=="\0",h=u===0&&Uc(c.presentation_time_delta)&&f,m=u===1&&Uc(c.presentation_time)&&f;return!(u>1)&&h||m},Uc=function(u){return u!==void 0||u!==null},e2={parseEmsgBox:Qb,scaleTime:Jb},On=Pn.toUnsigned,rr=Pn.toHexString,Ce=Pc,Ji=kc,Co=e2,t2=Mc,i2=Rc,s2=Lc,r2=n.getUint64,Fc,$c,jc,qc,Vc,wo,Hc,Ao=Nc,n2=gc.parseId3Frames;Fc=function(u){var c={},f=Ce(u,["moov","trak"]);return f.reduce(function(h,m){var g,T,S,E,w;return g=Ce(m,["tkhd"])[0],!g||(T=g[0],S=T===0?12:20,E=On(g[S]<<24|g[S+1]<<16|g[S+2]<<8|g[S+3]),w=Ce(m,["mdia","mdhd"])[0],!w)?null:(T=w[0],S=T===0?12:20,h[E]=On(w[S]<<24|w[S+1]<<16|w[S+2]<<8|w[S+3]),h)},c)},$c=function(u,c){var f;f=Ce(c,["moof","traf"]);var h=f.reduce(function(m,g){var T=Ce(g,["tfhd"])[0],S=On(T[4]<<24|T[5]<<16|T[6]<<8|T[7]),E=u[S]||9e4,w=Ce(g,["tfdt"])[0],I=new DataView(w.buffer,w.byteOffset,w.byteLength),R;w[0]===1?R=r2(w.subarray(4,12)):R=I.getUint32(4);let j;return typeof R=="bigint"?j=R/Ao.BigInt(E):typeof R=="number"&&!isNaN(R)&&(j=R/E),j11?(m.codec+=".",m.codec+=rr(B[9]),m.codec+=rr(B[10]),m.codec+=rr(B[11])):m.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(m.codec)?(B=j.subarray(28),G=Ji(B.subarray(4,8)),G==="esds"&&B.length>20&&B[19]!==0?(m.codec+="."+rr(B[19]),m.codec+="."+rr(B[20]>>>2&63).replace(/^0/,"")):m.codec="mp4a.40.2"):m.codec=m.codec.toLowerCase())}var K=Ce(h,["mdia","mdhd"])[0];K&&(m.timescale=wo(K)),f.push(m)}),f},Hc=function(u,c=0){var f=Ce(u,["emsg"]);return f.map(h=>{var m=Co.parseEmsgBox(new Uint8Array(h)),g=n2(m.message_data);return{cueTime:Co.scaleTime(m.presentation_time,m.timescale,m.presentation_time_delta,c),duration:Co.scaleTime(m.event_duration,m.timescale),frames:g}})};var Do={findBox:Ce,parseType:Ji,timescale:Fc,startTime:$c,compositionStartTime:jc,videoTrackIds:qc,tracks:Vc,getTimescaleFromMediaHeader:wo,getEmsgID3:Hc},ko=_n,zc=function(u){var c=u[1]&31;return c<<=8,c|=u[2],c},Rn=function(u){return!!(u[1]&64)},Mn=function(u){var c=0;return(u[3]&48)>>>4>1&&(c+=u[4]+1),c},a2=function(u,c){var f=zc(u);return f===0?"pat":f===c?"pmt":c?"pes":null},o2=function(u){var c=Rn(u),f=4+Mn(u);return c&&(f+=u[f]+1),(u[f+10]&31)<<8|u[f+11]},u2=function(u){var c={},f=Rn(u),h=4+Mn(u);if(f&&(h+=u[h]+1),!!(u[h+5]&1)){var m,g,T;m=(u[h+1]&15)<<8|u[h+2],g=3+m-4,T=(u[h+10]&15)<<8|u[h+11];for(var S=12+T;S=u.byteLength)return null;var h=null,m;return m=u[f+7],m&192&&(h={},h.pts=(u[f+9]&14)<<27|(u[f+10]&255)<<20|(u[f+11]&254)<<12|(u[f+12]&255)<<5|(u[f+13]&254)>>>3,h.pts*=4,h.pts+=(u[f+13]&6)>>>1,h.dts=h.pts,m&64&&(h.dts=(u[f+14]&14)<<27|(u[f+15]&255)<<20|(u[f+16]&254)<<12|(u[f+17]&255)<<5|(u[f+18]&254)>>>3,h.dts*=4,h.dts+=(u[f+18]&6)>>>1)),h},Io=function(u){switch(u){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}},d2=function(u){for(var c=4+Mn(u),f=u.subarray(c),h=0,m=0,g=!1,T;m3&&(T=Io(f[m+3]&31),T==="slice_layer_without_partitioning_rbsp_idr"&&(g=!0)),g},h2={parseType:a2,parsePat:o2,parsePmt:u2,parsePayloadUnitStartIndicator:Rn,parsePesType:l2,parsePesTime:c2,videoPacketContainsKeyFrame:d2},Gc=_n,Zi=pc.handleRollover,ae={};ae.ts=h2,ae.aac=bo;var Ai=fe.ONE_SECOND_IN_TS,Ge=188,kt=71,f2=function(u,c){for(var f=0,h=Ge,m,g;h=0;){if(u[h]===kt&&(u[m]===kt||m===u.byteLength)){switch(g=u.subarray(h,m),T=ae.ts.parseType(g,c.pid),T){case"pes":S=ae.ts.parsePesType(g,c.table),E=ae.ts.parsePayloadUnitStartIndicator(g),S==="audio"&&E&&(w=ae.ts.parsePesTime(g),w&&(w.type="audio",f.audio.push(w),I=!0));break}if(I)break;h-=Ge,m-=Ge;continue}h--,m--}},p2=function(u,c,f){for(var h=0,m=Ge,g,T,S,E,w,I,R,j,B=!1,G={data:[],size:0};m=0;){if(u[h]===kt&&u[m]===kt){switch(g=u.subarray(h,m),T=ae.ts.parseType(g,c.pid),T){case"pes":S=ae.ts.parsePesType(g,c.table),E=ae.ts.parsePayloadUnitStartIndicator(g),S==="video"&&E&&(w=ae.ts.parsePesTime(g),w&&(w.type="video",f.video.push(w),B=!0));break}if(B)break;h-=Ge,m-=Ge;continue}h--,m--}},m2=function(u,c){if(u.audio&&u.audio.length){var f=c;(typeof f>"u"||isNaN(f))&&(f=u.audio[0].dts),u.audio.forEach(function(g){g.dts=Zi(g.dts,f),g.pts=Zi(g.pts,f),g.dtsTime=g.dts/Ai,g.ptsTime=g.pts/Ai})}if(u.video&&u.video.length){var h=c;if((typeof h>"u"||isNaN(h))&&(h=u.video[0].dts),u.video.forEach(function(g){g.dts=Zi(g.dts,h),g.pts=Zi(g.pts,h),g.dtsTime=g.dts/Ai,g.ptsTime=g.pts/Ai}),u.firstKeyFrame){var m=u.firstKeyFrame;m.dts=Zi(m.dts,h),m.pts=Zi(m.pts,h),m.dtsTime=m.dts/Ai,m.ptsTime=m.pts/Ai}}},g2=function(u){for(var c=!1,f=0,h=null,m=null,g=0,T=0,S;u.length-T>=3;){var E=ae.aac.parseType(u,T);switch(E){case"timed-metadata":if(u.length-T<10){c=!0;break}if(g=ae.aac.parseId3TagSize(u,T),g>u.length){c=!0;break}m===null&&(S=u.subarray(T,T+g),m=ae.aac.parseAacTimestamp(S)),T+=g;break;case"audio":if(u.length-T<7){c=!0;break}if(g=ae.aac.parseAdtsSize(u,T),g>u.length){c=!0;break}h===null&&(S=u.subarray(T,T+g),h=ae.aac.parseSampleRate(S)),f++,T+=g;break;default:T++;break}if(c)return null}if(h===null||m===null)return null;var w=Ai/h,I={audio:[{type:"audio",dts:m,pts:m},{type:"audio",dts:m+f*1024*w,pts:m+f*1024*w}]};return I},y2=function(u){var c={pid:null,table:null},f={};f2(u,c);for(var h in c.table)if(c.table.hasOwnProperty(h)){var m=c.table[h];switch(m){case Gc.H264_STREAM_TYPE:f.video=[],p2(u,c,f),f.video.length===0&&delete f.video;break;case Gc.ADTS_STREAM_TYPE:f.audio=[],Wc(u,c,f),f.audio.length===0&&delete f.audio;break}}return f},_2=function(u,c){var f=ae.aac.isLikelyAacData(u),h;return f?h=g2(u):h=y2(u),!h||!h.audio&&!h.video?null:(m2(h,c),h)},v2={inspect:_2,parseAudioPes_:Wc};const T2=function(u,c){c.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,u.postMessage({action:"data",segment:f,byteOffset:m.byteOffset,byteLength:m.byteLength},[f.data])}),c.on("done",function(f){u.postMessage({action:"done"})}),c.on("gopInfo",function(f){u.postMessage({action:"gopInfo",gopInfo:f})}),c.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)),u.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:h})}),c.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)),u.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:h})}),c.on("id3Frame",function(f){u.postMessage({action:"id3Frame",id3Frame:f})}),c.on("caption",function(f){u.postMessage({action:"caption",caption:f})}),c.on("trackinfo",function(f){u.postMessage({action:"trackinfo",trackInfo:f})}),c.on("audioTimingInfo",function(f){u.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:fe.videoTsToSeconds(f.start),end:fe.videoTsToSeconds(f.end)}})}),c.on("videoTimingInfo",function(f){u.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:fe.videoTsToSeconds(f.start),end:fe.videoTsToSeconds(f.end)}})}),c.on("log",function(f){u.postMessage({action:"log",log:f})})};class Kc{constructor(c,f){this.options=f||{},this.self=c,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new xb.Transmuxer(this.options),T2(this.self,this.transmuxer)}pushMp4Captions(c){this.captionParser||(this.captionParser=new Wb,this.captionParser.init());const f=new Uint8Array(c.data,c.byteOffset,c.byteLength),h=this.captionParser.parse(f,c.trackIds,c.timescales);this.self.postMessage({action:"mp4Captions",captions:h&&h.captions||[],logs:h&&h.logs||[],data:f.buffer},[f.buffer])}probeMp4StartTime({timescales:c,data:f}){const h=Do.startTime(c,f);this.self.postMessage({action:"probeMp4StartTime",startTime:h,data:f},[f.buffer])}probeMp4Tracks({data:c}){const f=Do.tracks(c);this.self.postMessage({action:"probeMp4Tracks",tracks:f,data:c},[c.buffer])}probeEmsgID3({data:c,offset:f}){const h=Do.getEmsgID3(c,f);this.self.postMessage({action:"probeEmsgID3",id3Frames:h,emsgData:c},[c.buffer])}probeTs({data:c,baseStartTime:f}){const h=typeof f=="number"&&!isNaN(f)?f*fe.ONE_SECOND_IN_TS:void 0,m=v2.inspect(c,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:c},[c.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(c){const f=new Uint8Array(c.data,c.byteOffset,c.byteLength);this.transmuxer.push(f)}reset(){this.transmuxer.reset()}setTimestampOffset(c){const f=c.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(fe.secondsToVideoTs(f)))}setAudioAppendStart(c){this.transmuxer.setAudioAppendStart(Math.ceil(fe.secondsToVideoTs(c.appendStart)))}setRemux(c){this.transmuxer.setRemux(c.remux)}flush(c){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(c){this.transmuxer.alignGopsWith(c.gopsToAlignWith.slice())}}self.onmessage=function(u){if(u.data.action==="init"&&u.data.options){this.messageHandlers=new Kc(self,u.data.options);return}this.messageHandlers||(this.messageHandlers=new Kc(self)),u.data&&u.data.action&&u.data.action!=="init"&&this.messageHandlers[u.data.action]&&this.messageHandlers[u.data.action](u.data)}}));var uA=yg(oA);const lA=(s,e,t)=>{const{type:i,initSegment:r,captions:n,captionStreams:a,metadata:o,videoFrameDtsTime:l,videoFramePtsTime:d}=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 l<"u"&&(y.videoFrameDtsTime=l),typeof d<"u"&&(y.videoFramePtsTime=d),t(y)},cA=({transmuxedData:s,callback:e})=>{s.buffer=[],e(s)},dA=(s,e)=>{e.gopInfo=s.data.gopInfo},Tg=s=>{const{transmuxer:e,bytes:t,audioAppendStart:i,gopsToAlignWith:r,remux:n,onData:a,onTrackInfo:o,onAudioTimingInfo:l,onVideoTimingInfo:d,onVideoSegmentTimingInfo:p,onAudioSegmentTimingInfo:y,onId3:_,onCaptions:b,onDone:v,onEndedTimeline:x,onTransmuxerLog:A,isEndOfTimeline:D}=s,k={buffer:[]};let M=D;const O=P=>{e.currentTransmux===s&&(P.data.action==="data"&&lA(P,k,a),P.data.action==="trackinfo"&&o(P.data.trackInfo),P.data.action==="gopInfo"&&dA(P,k),P.data.action==="audioTimingInfo"&&l(P.data.audioTimingInfo),P.data.action==="videoTimingInfo"&&d(P.data.videoTimingInfo),P.data.action==="videoSegmentTimingInfo"&&p(P.data.videoSegmentTimingInfo),P.data.action==="audioSegmentTimingInfo"&&y(P.data.audioSegmentTimingInfo),P.data.action==="id3Frame"&&_([P.data.id3Frame],P.data.id3Frame.dispatchType),P.data.action==="caption"&&b(P.data.caption),P.data.action==="endedtimeline"&&(M=!1,x()),P.data.action==="log"&&A(P.data.log),P.data.type==="transmuxed"&&(M||(e.onmessage=null,cA({transmuxedData:k,callback:v}),bg(e))))};if(e.onmessage=O,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 P=t instanceof ArrayBuffer?t:t.buffer,U=t instanceof ArrayBuffer?0:t.byteOffset;e.postMessage({action:"push",data:P,byteOffset:U,byteLength:t.byteLength},[P])}D&&e.postMessage({action:"endTimeline"}),e.postMessage({action:"flush"})},bg=s=>{s.currentTransmux=null,s.transmuxQueue.length&&(s.currentTransmux=s.transmuxQueue.shift(),typeof s.currentTransmux=="function"?s.currentTransmux():Tg(s.currentTransmux))},Ah=(s,e)=>{s.postMessage({action:e}),bg(s)},Sg=(s,e)=>{if(!e.currentTransmux){e.currentTransmux=s,Ah(e,s);return}e.transmuxQueue.push(Ah.bind(null,e,s))},hA=s=>{Sg("reset",s)},fA=s=>{Sg("endTimeline",s)},xg=s=>{if(!s.transmuxer.currentTransmux){s.transmuxer.currentTransmux=s,Tg(s);return}s.transmuxer.transmuxQueue.push(s)},pA=s=>{const e=new uA;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 au={reset:hA,endTimeline:fA,transmux:xg,createTransmuxer:pA};const Lr=function(s){const e=s.transmuxer,t=s.endAction||s.action,i=s.callback,r=_t({},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)},Nt={FAILURE:2,TIMEOUT:-101,ABORTED:-102},Vu=s=>{s.forEach(e=>{e.abort()})},mA=s=>({bandwidth:s.bandwidth,bytesReceived:s.bytesReceived||0,roundTripTime:s.roundTripTime||0}),gA=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},Zl=(s,e)=>e.timedout?{status:e.status,message:"HLS request timed-out at URL: "+e.uri,code:Nt.TIMEOUT,xhr:e}:e.aborted?{status:e.status,message:"HLS request aborted at URL: "+e.uri,code:Nt.ABORTED,xhr:e}:s?{status:e.status,message:"HLS request errored at URL: "+e.uri,code:Nt.FAILURE,xhr:e}:e.responseType==="arraybuffer"&&e.response.byteLength===0?{status:e.status,message:"Empty HLS response at URL: "+e.uri,code:Nt.FAILURE,xhr:e}:null,Dh=(s,e,t)=>(i,r)=>{const n=r.response,a=Zl(i,r);if(a)return t(a,s);if(n.byteLength!==16)return t({status:r.status,message:"Invalid HLS key at URL: "+r.uri,code:Nt.FAILURE,xhr:r},s);const o=new DataView(n),l=new Uint32Array([o.getUint32(0),o.getUint32(4),o.getUint32(8),o.getUint32(12)]);for(let d=0;d{const t=_l(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:Nt.FAILURE,metadata:{errorType:L.Error.UnsupportedMediaInitialization,mediaType:r}})}Lr({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))})},yA=({segment:s,finishProcessingFn:e})=>(t,i)=>{const r=Zl(t,i);if(r)return e(r,s);const n=new Uint8Array(i.response);if(s.map.key)return s.map.encryptedBytes=n,e(null,s);s.map.bytes=n,Eg(s,function(a){if(a)return a.xhr=i,a.status=i.status,e(a,s);e(null,s)})},_A=({segment:s,finishProcessingFn:e,responseType:t})=>(i,r)=>{const n=Zl(i,r);if(n)return e(n,s);const a=t==="arraybuffer"||!r.responseText?r.response:nA(r.responseText.substring(s.lastReachedChar||0));return s.stats=mA(r),s.key?s.encryptedBytes=new Uint8Array(a):s.bytes=new Uint8Array(a),e(null,s)},vA=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:p,doneFn:y,onTransmuxerLog:_})=>{const b=s.map&&s.map.tracks||{},v=!!(b.audio&&b.video);let x=i.bind(null,s,"audio","start");const A=i.bind(null,s,"audio","end");let D=i.bind(null,s,"video","start");const k=i.bind(null,s,"video","end"),M=()=>xg({bytes:e,transmuxer:s.transmuxer,audioAppendStart:s.audioAppendStart,gopsToAlignWith:s.gopsToAlignWith,remux:v,onData:O=>{O.type=O.type==="combined"?"video":O.type,p(s,O)},onTrackInfo:O=>{t&&(v&&(O.isMuxed=!0),t(s,O))},onAudioTimingInfo:O=>{x&&typeof O.start<"u"&&(x(O.start),x=null),A&&typeof O.end<"u"&&A(O.end)},onVideoTimingInfo:O=>{D&&typeof O.start<"u"&&(D(O.start),D=null),k&&typeof O.end<"u"&&k(O.end)},onVideoSegmentTimingInfo:O=>{r(O)},onAudioSegmentTimingInfo:O=>{n(O)},onId3:(O,P)=>{a(s,O,P)},onCaptions:O=>{o(s,[O])},isEndOfTimeline:l,onEndedTimeline:()=>{d()},onTransmuxerLog:_,onDone:O=>{y&&(O.type=O.type==="combined"?"video":O.type,y(null,s,O))}});Lr({action:"probeTs",transmuxer:s.transmuxer,data:e,baseStartTime:s.baseStartTime,callback:O=>{s.bytes=e=O.data;const P=O.result;P&&(t(s,{hasAudio:P.hasAudio,hasVideo:P.hasVideo,isMuxed:v}),t=null),M()}})},Cg=({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:p,doneFn:y,onTransmuxerLog:_})=>{let b=new Uint8Array(e);if(GE(b)){s.isFmp4=!0;const{tracks:v}=s.map,x={isFmp4:!0,hasVideo:!!v.video,hasAudio:!!v.audio};v.audio&&v.audio.codec&&v.audio.codec!=="enca"&&(x.audioCodec=v.audio.codec),v.video&&v.video.codec&&v.video.codec!=="encv"&&(x.videoCodec=v.video.codec),v.video&&v.audio&&(x.isMuxed=!0),t(s,x);const A=(D,k)=>{p(s,{data:b,type:x.hasAudio&&!x.isMuxed?"audio":"video"}),k&&k.length&&a(s,k),D&&D.length&&o(s,D),y(null,s,{})};Lr({action:"probeMp4StartTime",timescales:s.map.timescales,data:b,transmuxer:s.transmuxer,callback:({data:D,startTime:k})=>{e=D.buffer,s.bytes=b=D,x.hasAudio&&!x.isMuxed&&i(s,"audio","start",k),x.hasVideo&&i(s,"video","start",k),Lr({action:"probeEmsgID3",data:b,transmuxer:s.transmuxer,offset:k,callback:({emsgData:M,id3Frames:O})=>{if(e=M.buffer,s.bytes=b=M,!v.video||!M.byteLength||!s.transmuxer){A(void 0,O);return}Lr({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:s.transmuxer,data:b,timescales:s.map.timescales,trackIds:[v.video.id],callback:P=>{e=P.data.buffer,s.bytes=b=P.data,P.logs.forEach(function(U){_(re(U,{stream:"mp4CaptionParser"}))}),A(P.captions,O)}})}})}});return}if(!s.transmuxer){y(null,s,{});return}if(typeof s.container>"u"&&(s.container=_l(b)),s.container!=="ts"&&s.container!=="aac"){t(s,{hasAudio:!1,hasVideo:!1}),y(null,s,{});return}vA({segment:s,bytes:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:p,doneFn:y,onTransmuxerLog:_})},wg=function({id:s,key:e,encryptedBytes:t,decryptionWorker:i},r){const n=o=>{if(o.data.source===s){i.removeEventListener("message",n);const l=o.data.decrypted;r(new Uint8Array(l.bytes,l.byteOffset,l.byteLength))}};i.addEventListener("message",n);let a;e.bytes.slice?a=e.bytes.slice():a=new Uint32Array(Array.prototype.slice.call(e.bytes)),i.postMessage(dg({source:s,encrypted:t,key:a,iv:e.iv}),[t.buffer,a.buffer])},TA=({decryptionWorker:s,segment:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:p,doneFn:y,onTransmuxerLog:_})=>{wg({id:e.requestId,key:e.key,encryptedBytes:e.encryptedBytes,decryptionWorker:s},b=>{e.bytes=b,Cg({segment:e,bytes:e.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:p,doneFn:y,onTransmuxerLog:_})})},bA=({activeXhrs:s,decryptionWorker:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:p,doneFn:y,onTransmuxerLog:_})=>{let b=0,v=!1;return(x,A)=>{if(!v){if(x)return v=!0,Vu(s),y(x,A);if(b+=1,b===s.length){const D=function(){if(A.encryptedBytes)return TA({decryptionWorker:e,segment:A,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:p,doneFn:y,onTransmuxerLog:_});Cg({segment:A,bytes:A.bytes,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:p,doneFn:y,onTransmuxerLog:_})};if(A.endOfAllRequests=Date.now(),A.map&&A.map.encryptedBytes&&!A.map.bytes)return wg({decryptionWorker:e,id:A.requestId+"-init",encryptedBytes:A.map.encryptedBytes,key:A.map.key},k=>{A.map.bytes=k,Eg(A,M=>{if(M)return Vu(s),y(M,A);D()})});D()}}}},SA=({loadendState:s,abortFn:e})=>t=>{t.target.aborted&&e&&!s.calledAbortFn&&(e(),s.calledAbortFn=!0)},xA=({segment:s,progressFn:e,trackInfoFn:t,timingInfoFn:i,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:p})=>y=>{if(!y.target.aborted)return s.stats=re(s.stats,gA(y)),!s.stats.firstBytesReceivedAt&&s.stats.bytesReceived&&(s.stats.firstBytesReceivedAt=Date.now()),e(y,s)},EA=({xhr:s,xhrOptions:e,decryptionWorker:t,segment:i,abortFn:r,progressFn:n,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:l,audioSegmentTimingInfoFn:d,id3Fn:p,captionsFn:y,isEndOfTimeline:_,endedTimelineFn:b,dataFn:v,doneFn:x,onTransmuxerLog:A})=>{const D=[],k=bA({activeXhrs:D,decryptionWorker:t,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:l,audioSegmentTimingInfoFn:d,id3Fn:p,captionsFn:y,isEndOfTimeline:_,endedTimelineFn:b,dataFn:v,doneFn:x,onTransmuxerLog:A});if(i.key&&!i.key.bytes){const V=[i.key];i.map&&!i.map.bytes&&i.map.key&&i.map.key.resolvedUri===i.key.resolvedUri&&V.push(i.map.key);const J=re(e,{uri:i.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),W=Dh(i,V,k),ue=s(J,W);D.push(ue)}if(i.map&&!i.map.bytes){if(i.map.key&&(!i.key||i.key.resolvedUri!==i.map.key.resolvedUri)){const te=re(e,{uri:i.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),he=Dh(i,[i.map.key],k),H=s(te,he);D.push(H)}const J=re(e,{uri:i.map.resolvedUri,responseType:"arraybuffer",headers:ju(i.map),requestType:"segment-media-initialization"}),W=yA({segment:i,finishProcessingFn:k}),ue=s(J,W);D.push(ue)}const M=re(e,{uri:i.part&&i.part.resolvedUri||i.resolvedUri,responseType:"arraybuffer",headers:ju(i),requestType:"segment"}),O=_A({segment:i,finishProcessingFn:k,responseType:M.responseType}),P=s(M,O);P.addEventListener("progress",xA({segment:i,progressFn:n,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:l,audioSegmentTimingInfoFn:d,id3Fn:p,captionsFn:y,isEndOfTimeline:_,endedTimelineFn:b,dataFn:v})),D.push(P);const U={};return D.forEach(V=>{V.addEventListener("loadend",SA({loadendState:U,abortFn:r}))}),()=>Vu(D)},CA=St("CodecUtils"),wA=function(s){const e=s.attributes||{};if(e.CODECS)return It(e.CODECS)},Ag=(s,e)=>{const t=e.attributes||{};return s&&s.mediaGroups&&s.mediaGroups.AUDIO&&t.AUDIO&&s.mediaGroups.AUDIO[t.AUDIO]},AA=(s,e)=>{if(!Ag(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},xa=function(s){const e={};return s.forEach(({mediaType:t,type:i,details:r})=>{e[t]=e[t]||[],e[t].push($f(`${i}${r}`))}),Object.keys(e).forEach(function(t){if(e[t].length>1){CA(`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},kh=function(s){let e=0;return s.audio&&e++,s.video&&e++,e},Or=function(s,e){const t=e.attributes||{},i=xa(wA(e)||[]);if(Ag(s,e)&&!i.audio&&!AA(s,e)){const r=xa(GS(s,t.AUDIO)||[]);r.audio&&(i.audio=r.audio)}return i},Vn=St("PlaylistSelector"),Ih=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||""})},Ea=function(s,e){if(!s)return"";const t=C.getComputedStyle(s);return t?t[e]:""},bs=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})},ec=function(s,e){let t,i;return s.attributes.BANDWIDTH&&(t=s.attributes.BANDWIDTH),t=t||C.Number.MAX_VALUE,e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||C.Number.MAX_VALUE,t-i},DA=function(s,e){let t,i;return s.attributes.RESOLUTION&&s.attributes.RESOLUTION.width&&(t=s.attributes.RESOLUTION.width),t=t||C.Number.MAX_VALUE,e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||C.Number.MAX_VALUE,t===i&&s.attributes.BANDWIDTH&&e.attributes.BANDWIDTH?s.attributes.BANDWIDTH-e.attributes.BANDWIDTH:t-i};let Dg=function(s,e,t,i,r,n){if(!s)return;const a={bandwidth:e,width:t,height:i,limitRenditionByPlayerDimensions:r};let o=s.playlists;st.isAudioOnly(s)&&(o=n.getAudioTrackPlaylists_(),a.audioOnly=!0);let l=o.map(P=>{let U;const V=P.attributes&&P.attributes.RESOLUTION&&P.attributes.RESOLUTION.width,J=P.attributes&&P.attributes.RESOLUTION&&P.attributes.RESOLUTION.height;return U=P.attributes&&P.attributes.BANDWIDTH,U=U||C.Number.MAX_VALUE,{bandwidth:U,width:V,height:J,playlist:P}});bs(l,(P,U)=>P.bandwidth-U.bandwidth),l=l.filter(P=>!st.isIncompatible(P.playlist));let d=l.filter(P=>st.isEnabled(P.playlist));d.length||(d=l.filter(P=>!st.isDisabled(P.playlist)));const p=d.filter(P=>P.bandwidth*Ne.BANDWIDTH_VARIANCEP.bandwidth===y.bandwidth)[0];if(r===!1){const P=_||d[0]||l[0];if(P&&P.playlist){let U="sortedPlaylistReps";return _&&(U="bandwidthBestRep"),d[0]&&(U="enabledPlaylistReps"),Vn(`choosing ${Ih(P)} using ${U} with options`,a),P.playlist}return Vn("could not choose a playlist with options",a),null}const b=p.filter(P=>P.width&&P.height);bs(b,(P,U)=>P.width-U.width);const v=b.filter(P=>P.width===t&&P.height===i);y=v[v.length-1];const x=v.filter(P=>P.bandwidth===y.bandwidth)[0];let A,D,k;x||(A=b.filter(P=>P.width>t||P.height>i),D=A.filter(P=>P.width===A[0].width&&P.height===A[0].height),y=D[D.length-1],k=D.filter(P=>P.bandwidth===y.bandwidth)[0]);let M;if(n.leastPixelDiffSelector){const P=b.map(U=>(U.pixelDiff=Math.abs(U.width-t)+Math.abs(U.height-i),U));bs(P,(U,V)=>U.pixelDiff===V.pixelDiff?V.bandwidth-U.bandwidth:U.pixelDiff-V.pixelDiff),M=P[0]}const O=M||k||x||_||d[0]||l[0];if(O&&O.playlist){let P="sortedPlaylistReps";return M?P="leastPixelDiffRep":k?P="resolutionPlusOneRep":x?P="resolutionBestRep":_?P="bandwidthBestRep":d[0]&&(P="enabledPlaylistReps"),Vn(`choosing ${Ih(O)} using ${P} with options`,a),O.playlist}return Vn("could not choose a playlist with options",a),null};const Ph=function(){let s=this.useDevicePixelRatio&&C.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(s=this.customPixelRatio),Dg(this.playlists.main,this.systemBandwidth,parseInt(Ea(this.tech_.el(),"width"),10)*s,parseInt(Ea(this.tech_.el(),"height"),10)*s,this.limitRenditionByPlayerDimensions,this.playlistController_)},kA=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&&C.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),Dg(this.playlists.main,e,parseInt(Ea(this.tech_.el(),"width"),10)*i,parseInt(Ea(this.tech_.el(),"height"),10)*i,this.limitRenditionByPlayerDimensions,this.playlistController_)}},IA=function(s){const{main:e,currentTime:t,bandwidth:i,duration:r,segmentDuration:n,timeUntilRebuffer:a,currentTimeline:o,syncController:l}=s,d=e.playlists.filter(v=>!st.isIncompatible(v));let p=d.filter(st.isEnabled);p.length||(p=d.filter(v=>!st.isDisabled(v)));const _=p.filter(st.hasAttribute.bind(null,"BANDWIDTH")).map(v=>{const A=l.getSyncPoint(v,r,o,t)?1:2,k=st.estimateSegmentRequestTime(n,i,v)*A-a;return{playlist:v,rebufferingImpact:k}}),b=_.filter(v=>v.rebufferingImpact<=0);return bs(b,(v,x)=>ec(x.playlist,v.playlist)),b.length?b[0]:(bs(_,(v,x)=>v.rebufferingImpact-x.rebufferingImpact),_[0]||null)},PA=function(){const s=this.playlists.main.playlists.filter(st.isEnabled);return bs(s,(t,i)=>ec(t,i)),s.filter(t=>!!Or(this.playlists.main,t).video)[0]||null},LA=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 kg(s){try{return new URL(s).pathname.split("/").slice(-2).join("/")}catch{return""}}const OA=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,l=!1;const d=n[i];d&&(a=d.label,o=d.language,l=d.default),s[t]=e.addRemoteTextTrack({kind:"captions",id:i,default:l,label:a,language:o},!1).track}}},RA=function({inbandTextTracks:s,captionArray:e,timestampOffset:t}){if(!e)return;const i=C.WebKitDataCue||C.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))})},MA=function(s){Object.defineProperties(s.frame,{id:{get(){return L.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),s.value.key}},value:{get(){return L.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),s.value.data}},privateData:{get(){return L.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),s.value.data}}})},NA=({inbandTextTracks:s,metadataArray:e,timestampOffset:t,videoDuration:i})=>{if(!e)return;const r=C.WebKitDataCue||C.VTTCue,n=s.metadataTrack_;if(!n||(e.forEach(p=>{const y=p.cueTime+t;typeof y!="number"||C.isNaN(y)||y<0||!(y<1/0)||!p.frames||!p.frames.length||p.frames.forEach(_=>{const b=new r(y,y,_.value||_.url||_.data||"");b.frame=_,b.value=_,MA(b),n.addCue(b)})}),!n.cues||!n.cues.length))return;const a=n.cues,o=[];for(let p=0;p{const _=p[y.startTime]||[];return _.push(y),p[y.startTime]=_,p},{}),d=Object.keys(l).sort((p,y)=>Number(p)-Number(y));d.forEach((p,y)=>{const _=l[p],b=isFinite(i)?i:p,v=Number(d[y+1])||b;_.forEach(x=>{x.endTime=v})})},BA={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"},UA=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),FA=({inbandTextTracks:s,dateRanges:e})=>{const t=s.metadataTrack_;if(!t)return;const i=C.WebKitDataCue||C.VTTCue;e.forEach(r=>{for(const n of Object.keys(r)){if(UA.has(n))continue;const a=new i(r.startTime,r.endTime,"");a.id=r.id,a.type="com.apple.quicktime.HLS",a.value={key:BA[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()})},Lh=(s,e,t)=>{s.metadataTrack_||(s.metadataTrack_=t.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,L.browser.IS_ANY_SAFARI||(s.metadataTrack_.inBandMetadataTrackDispatchType=e))},xr=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)},$A=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}},jA=(s,e,t)=>{if(typeof e>"u"||e===null||!s.length)return[];const i=Math.ceil((e-t+3)*Ni.ONE_SECOND_IN_TS);let r;for(r=0;ri);r++);return s.slice(r)},qA=(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)},VA=(s,e,t,i)=>{const r=Math.ceil((e-i)*Ni.ONE_SECOND_IN_TS),n=Math.ceil((t-i)*Ni.ONE_SECOND_IN_TS),a=s.slice();let o=s.length;for(;o--&&!(s[o].pts<=n););if(o===-1)return a;let l=o+1;for(;l--&&!(s[l].pts<=r););return l=Math.max(l,0),a.splice(l,o-l+1),a},HA=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]},pr=1,GA=500,Oh=s=>typeof s=="number"&&isFinite(s),Hn=1/60,WA=(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,KA=(s,e,t)=>{let i=e-Ne.BACK_BUFFER_LENGTH;s.length&&(i=Math.max(i,s.start(0)));const r=e-t;return Math.min(r,i)},ns=s=>{const{startOfSegment:e,duration:t,segment:i,part:r,playlist:{mediaSequence:n,id:a,segments:o=[]},mediaIndex:l,partIndex:d,timeline:p}=s,y=o.length-1;let _="mediaIndex/partIndex increment";s.getMediaInfoForTime?_=`getMediaInfoForTime (${s.getMediaInfoForTime})`:s.isSyncRequest&&(_="getSyncSegmentCandidate (isSyncRequest)"),s.independent&&(_+=` with independent ${s.independent}`);const b=typeof d=="number",v=s.segment.uri?"segment":"pre-segment",x=b?Ym({preloadSegment:i})-1:0;return`${v} [${n+l}/${n+y}]`+(b?` part [${d}/${x}]`:"")+` segment start/end [${i.start} => ${i.end}]`+(b?` part start/end [${r.start} => ${r.end}]`:"")+` startOfSegment [${e}] duration [${t}] timeline [${p}] selected by [${_}] playlist [${a}]`},Rh=s=>`${s}TimingInfo`,XA=({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},YA=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=C.BigInt(n)-C.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+Rt:!1,QA=(s,e)=>{if(e!=="hls")return null;const t=YA({audioTimingInfo:s.audioTimingInfo,videoTimingInfo:s.videoTimingInfo});if(!t)return null;const i=s.playlist.targetDuration,r=Nh({segmentDuration:t,maxDuration:i*2}),n=Nh({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};class Hu extends L.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_=St(`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_()}),this.loaderType_==="main"&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()&&this.processCallQueue_()}),this.loaderType_==="audio"&&this.timelineChangeController_.on("timelinechange",()=>{this.hasEnoughInfoToLoad_()&&this.processLoadQueue_(),this.hasEnoughInfoToAppend_()&&this.processCallQueue_()})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return au.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_&&C.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,C.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_&&au.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=Sa(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=hg(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: ${ru(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 l=this.mediaIndex;this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=l}}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_&&(C.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_&&au.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_=VA(this.gopBuffer_,e,t,this.timeMapping_),n++,this.sourceUpdater_.removeVideo(e,t,a));for(const o in this.inbandTextTracks_)xr(e,t,this.inbandTextTracks_[o]);xr(e,t,this.segmentMetadataTrack_),a()}monitorBuffer_(){this.checkBufferTimeout_&&C.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=C.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){this.state==="READY"&&this.fillBuffer_(),this.checkBufferTimeout_&&C.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=C.setTimeout(this.monitorBufferTick_.bind(this),GA)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();e&&(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=ru(e)||0,i=Xl(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=zA(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 _=a[this.mediaIndex],b=typeof this.partIndex=="number"?this.partIndex:-1;o.startOfSegment=_.end?_.end:t,_.parts&&_.parts[b+1]?(o.mediaIndex=this.mediaIndex,o.partIndex=b+1):o.mediaIndex=this.mediaIndex+1}else{let _,b,v;const x=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch:
+For TargetTime: ${x}.
+CurrentTime: ${this.currentTime_()}
+BufferedEnd: ${t}
+Fetch At Buffer: ${this.fetchAtBuffer_}
+`,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){const A=this.getSyncInfoFromMediaSequenceSync_(x);if(!A)return this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null;this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${A.start} --> ${A.end})`),_=A.segmentIndex,b=A.partIndex,v=A.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");const A=st.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:x,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});_=A.segmentIndex,b=A.partIndex,v=A.startTime}o.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${x}`:`currentTime ${x}`,o.mediaIndex=_,o.startOfSegment=v,o.partIndex=b,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${o.mediaIndex} `)}const l=a[o.mediaIndex];let d=l&&typeof o.partIndex=="number"&&l.parts&&l.parts[o.partIndex];if(!l||typeof o.partIndex=="number"&&!d)return null;typeof o.partIndex!="number"&&l.parts&&(o.partIndex=0,d=l.parts[0]);const p=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!i&&d&&!p&&!d.independent)if(o.partIndex===0){const _=a[o.mediaIndex-1],b=_.parts&&_.parts.length&&_.parts[_.parts.length-1];b&&b.independent&&(o.mediaIndex-=1,o.partIndex=_.parts.length-1,o.independent="previous segment")}else l.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:l,getMediaInfoForTime:d}=e,p=i.segments[r],y=typeof o=="number"&&p.parts[o],_={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:d,independent:t},b=typeof l<"u"?l:this.isPendingTimestampOffset_;_.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:p.timeline,currentTimeline:this.currentTimeline_,startOfSegment:n,buffered:this.buffered_(),overrideCheck:b});const v=ru(this.sourceUpdater_.audioBuffered());return typeof v=="number"&&(_.audioAppendStart=v-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(_.gopsToAlignWith=jA(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),_}timestampOffsetForSegment_(e){return XA(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=st.estimateSegmentRequestTime(r,i,this.playlist_,e.bytesReceived),a=_w(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(n<=a)return;const o=IA({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 d=n-a-o.rebufferingImpact;let p=.5;a<=Rt&&(p=1),!(!o.playlist||o.playlist.uri===this.playlist_.uri||d{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:l,captions:d}=n[a],p=this.inbandTextTracks_;this.logger_(`adding cues from ${o} -> ${l} for ${a}`),OA(p,this.vhs_.tech_,a),xr(o,l,p[a]),RA({captionArray:d,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_()?!Mh({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||Mh({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_()){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[Rh(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=Sa(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: "+Bi(n).join(", ")),a.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+Bi(a).join(", "));const o=n.length?n.start(0):0,l=n.length?n.end(n.length-1):0,d=a.length?a.start(0):0,p=a.length?a.end(a.length-1):0;if(l-o<=pr&&p-d<=pr){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${Bi(n).join(", ")}, video buffer: ${Bi(a).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0,metadata:{errorType:L.Error.SegmentExceedsSourceBufferQuota}}),this.trigger("error");return}this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:i}));const _=this.currentTime_()-pr;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${_}`),this.remove(0,_,()=>{this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${pr}s`),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=C.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},pr*1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},r){if(r){if(r.code===Ig){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:L.Error.SegmentAppendError}}),this.trigger("appenderror")}}appendToSourceBuffer_({segmentInfo:e,type:t,initSegment:i,data:r,bytes:n}){if(!n){const a=[r];let o=r.byteLength;i&&(a.unshift(i),o+=i.byteLength),n=LA({bytes:o,segments: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_()){this.loadQueue_.push(()=>{const t=_t({},e,{forceTimestampOffset:!0});_t(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
+${kg(e.uri)}
+${ns(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=EA({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:l,stream:d})=>{this.logger_(`${ns(e)} logged from transmuxer stream ${d} as a ${l}: ${o}`)}})}trimBackBuffer_(e){const t=KA(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){const t=e.segment,i=e.part,r={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},n=e.playlist.segments[e.mediaIndex-1];if(n&&n.timeline===t.timeline&&(n.videoTimingInfo?r.baseStartTime=n.videoTimingInfo.transmuxedDecodeEnd:n.audioTimingInfo&&(r.baseStartTime=n.audioTimingInfo.transmuxedDecodeEnd)),t.key){const a=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);r.key=this.segmentKey(t.key),r.key.iv=a}return t.map&&(r.map=this.initSegmentForMap(t.map)),r}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"||d.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,metadata:{errorType:L.Error.SegmentUnsupportedMediaFormat}}),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=WA(this.loaderType_,this.getCurrentMediaInfo_(),e);return t?(this.error({message:t,playlistExclusionDuration:1/0,metadata:{errorType:L.Error.SegmentSwitchError}}),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_&&this.trigger("appendsdone"),!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=QA(e,this.sourceType_);if(t&&(t.severity==="warn"?L.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 ${ns(e)}`);return}this.logger_(`Appended ${ns(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"} ${ns(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())},JA=["video","audio"],zu=(s,e)=>{const t=e[`${s}Buffer`];return t&&t.updating||e.queuePending[s]},ZA=(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(),Ss("audio",e),Ss("video",e));return}if(s!=="mediaSource"&&!(!e.ready()||e.mediaSource.readyState==="closed"||zu(s,e))){if(i.type!==s){if(t=ZA(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,Ss(s,e);return}}},Lg=(s,e)=>{const t=e[`${s}Buffer`],i=Pg(s);t&&(t.removeEventListener("updateend",e[`on${i}UpdateEnd_`]),t.removeEventListener("error",e[`on${i}Error_`]),e.codecs[s]=null,e[`${s}Buffer`]=null)},Lt=(s,e)=>s&&e&&Array.prototype.indexOf.call(s.sourceBuffers,e)!==-1,lt={appendBuffer:(s,e,t)=>(i,r)=>{const n=r[`${i}Buffer`];if(Lt(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===Ig?"(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(Lt(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`];Lt(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){L.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){L.log.warn("Failed to set media source duration",t)}},abort:()=>(s,e)=>{if(e.mediaSource.readyState!=="open")return;const t=e[`${s}Buffer`];if(Lt(e.mediaSource,t)){e.logger_(`calling abort on ${s}Buffer`);try{t.abort()}catch(i){L.log.warn(`Failed to abort on ${s}Buffer`,i)}}},addSourceBuffer:(s,e)=>t=>{const i=Pg(s),r=Br(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(Lg(s,e),!!Lt(e.mediaSource,t)){e.logger_(`Removing ${s}Buffer with codec ${e.codecs[s]} from mediaSource`);try{e.mediaSource.removeSourceBuffer(t)}catch(i){L.log.warn(`Failed to removeSourceBuffer ${s}Buffer`,i)}}},changeType:s=>(e,t)=>{const i=t[`${e}Buffer`],r=Br(s);if(!Lt(t.mediaSource,i))return;const n=s.substring(0,s.indexOf(".")),a=t.codecs[e];if(a.substring(0,a.indexOf("."))!==n){t.logger_(`changing ${e}Buffer codec from ${t.codecs[e]} to ${s}`);try{i.changeType(r),t.codecs[e]=s}catch(l){L.log.warn(`Failed to changeType on ${e}Buffer`,l)}}}},ct=({type:s,sourceUpdater:e,action:t,doneFn:i,name:r})=>{e.queue.push({type:s,action:t,doneFn:i,name:r}),Ss(s,e)},Bh=(s,e)=>t=>{const i=e[`${s}Buffered`](),r=mw(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_`])}Ss(s,e)};class Og extends L.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>Ss("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=St("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=Bh("video",this),this.onAudioUpdateEnd_=Bh("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){ct({type:"mediaSource",sourceUpdater:this,action:lt.addSourceBuffer(e,t),name:"addSourceBuffer"})}abort(e){ct({type:e,sourceUpdater:this,action:lt.abort(e),name:"abort"})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){L.log.error("removeSourceBuffer is not supported!");return}ct({type:"mediaSource",sourceUpdater:this,action:lt.removeSourceBuffer(e),name:"removeSourceBuffer"})}canRemoveSourceBuffer(){return!L.browser.IS_FIREFOX&&C.MediaSource&&C.MediaSource.prototype&&typeof C.MediaSource.prototype.removeSourceBuffer=="function"}static canChangeType(){return C.SourceBuffer&&C.SourceBuffer.prototype&&typeof C.SourceBuffer.prototype.changeType=="function"}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){if(!this.canChangeType()){L.log.error("changeType is not supported!");return}ct({type:e,sourceUpdater:this,action:lt.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(ct({type:r,sourceUpdater:this,action:lt.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(l=>{this.appendBuffer.apply(this,l)})}}audioBuffered(){return Lt(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:Ve()}videoBuffered(){return Lt(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:Ve()}buffered(){const e=Lt(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=Lt(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():yw(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=Jt){ct({type:"mediaSource",sourceUpdater:this,action:lt.duration(e),name:"duration",doneFn:t})}endOfStream(e=null,t=Jt){typeof e!="string"&&(e=void 0),ct({type:"mediaSource",sourceUpdater:this,action:lt.endOfStream(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=Jt){if(!this.audioBuffered().length||this.audioBuffered().end(0)===0){i();return}ct({type:"audio",sourceUpdater:this,action:lt.remove(e,t),doneFn:i,name:"remove"})}removeVideo(e,t,i=Jt){if(!this.videoBuffered().length||this.videoBuffered().end(0)===0){i();return}ct({type:"video",sourceUpdater:this,action:lt.remove(e,t),doneFn:i,name:"remove"})}updating(){return!!(zu("audio",this)||zu("video",this))}audioTimestampOffset(e){return typeof e<"u"&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(ct({type:"audio",sourceUpdater:this,action:lt.timestampOffset(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return typeof e<"u"&&this.videoBuffer&&this.videoTimestampOffset!==e&&(ct({type:"video",sourceUpdater:this,action:lt.timestampOffset(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&ct({type:"audio",sourceUpdater:this,action:lt.callback(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&ct({type:"video",sourceUpdater:this,action:lt.callback(e),name:"callback"})}dispose(){this.trigger("dispose"),JA.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>Lg(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const Uh=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("")},Fh=new Uint8Array(`
+
+`.split("").map(s=>s.charCodeAt(0)));class tD extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class iD extends Hu{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=Sa(e);let r=this.initSegments_[i];if(t&&!r&&e.bytes){const n=Fh.byteLength+e.bytes.byteLength,a=new Uint8Array(n);a.set(e.bytes),a.set(Fh,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){xr(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===Nt.TIMEOUT&&this.handleTimeout_(),e.code===Nt.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 C.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",metadata:{errorType:L.Error.VttLoadError}}));return}n.requested=!0;try{this.parseVTTCues_(r)}catch(a){this.stopForError({message:a.message,metadata:{errorType:L.Error.VttCueParsingError}});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 C.VTTCue(a.startTime,a.endTime,a.text):a)}),$A(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(){}updateTimingInfoEnd_(){}parseVTTCues_(e){let t,i=!1;if(typeof C.WebVTT!="function")throw new tD;typeof C.TextDecoder=="function"?t=new C.TextDecoder("utf8"):(t=C.WebVTT.StringDecoder(),i=!0);const r=new C.WebVTT.Parser(C,C.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=>{L.log.warn("Error encountered when parsing cues: "+a.message)},e.segment.map){let a=e.segment.map.bytes;i&&(a=Uh(a)),r.parse(a)}let n=e.bytes;i&&(n=Uh(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,l=n/Ni.ONE_SECOND_IN_TS-a+t.mapping;if(e.cues.forEach(d=>{const p=d.endTime-d.startTime,y=n===0?d.startTime+l:this.handleRollover_(d.startTime+l,t.time);d.startTime=Math.max(y,0),d.endTime=Math.max(y+p,0)}),!i.syncInfo){const d=e.cues[0].startTime,p=e.cues[e.cues.length-1].startTime;i.syncInfo={mediaSequence:i.mediaSequence+e.mediaIndex,time:Math.min(d,p-r.duration)}}}handleRollover_(e,t){if(t===null)return e;let i=e*Ni.ONE_SECOND_IN_TS;const r=t*Ni.ONE_SECOND_IN_TS;let n;for(r4294967296;)i+=n;return i/Ni.ONE_SECOND_IN_TS}}const sD=function(s,e){const t=s.cues;for(let i=0;i=r.adStartTime&&e<=r.adEndTime)return r}return null},rD=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 ou{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}updateStorage_(e,t,i){const r=new Map;let n=`
+`,a=i,o=t;this.start_=a,e.forEach((l,d)=>{const p=this.storage_.get(o),y=a,_=y+l.duration,b=!!(p&&p.segmentSyncInfo&&p.segmentSyncInfo.isAppended),v=new $h({start:y,end:_,appended:b,segmentIndex:d});l.syncInfo=v;let x=a;const A=(l.parts||[]).map((D,k)=>{const M=x,O=x+D.duration,P=!!(p&&p.partsSyncInfo&&p.partsSyncInfo[k]&&p.partsSyncInfo[k].isAppended),U=new $h({start:M,end:O,appended:P,segmentIndex:d,partIndex:k});return x=O,n+=`Media Sequence: ${o}.${k} | Range: ${M} --> ${O} | Appended: ${P}
+`,D.syncInfo=U,U});r.set(o,new nD(v,A)),n+=`${kg(l.resolvedUri)} | Media Sequence: ${o} | Range: ${y} --> ${_} | Appended: ${b}
+`,o++,a=_}),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}}const aD=86400,uu=[{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=Nu(e);r=r||0;for(let l=0;l{let n=null,a=null;r=r||0;const o=Nu(e);for(let l=0;l=b)&&(a=b,n={time:_,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:l,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 oD extends L.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={},this.mediaSequenceStorage_={main:new ou,audio:new ou,vtt:new ou},this.logger_=St("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,r,n){if(t!==1/0)return uu.find(({name:l})=>l==="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:l,strategy:d}=o,{segmentIndex:p,time:y}=l;if(p<0)continue;const _=e.segments[p],b=y,v=b+_.duration;if(this.logger_(`Strategy: ${d}. Current time: ${r}. selected segment: ${p}. Time: [${b} -> ${v}]}`),r>=b&&r0&&(r.time*=-1),Math.abs(r.time+Pr({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:r.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,r,n){const a=[];for(let o=0;oaD){L.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,l;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,l=t.end+a.mapping;else if(a)o=t.start+a.mapping,l=t.end+a.mapping;else return!1;return n&&(n.start=o,n.end=l),(!r.start||ol){let d;o<0?d=i.start-Pr({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:n}):d=i.end+Pr({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:n}),this.discontinuities[a]={time:d,accuracy:l}}}}dispose(){this.trigger("dispose"),this.off()}}class uD extends L.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}){return typeof t=="number"&&typeof i=="number"&&(this.lastTimelineChanges_[e]={type:e,from:t,to:i},delete this.pendingTimelineChanges_[e],this.trigger("timelinechange")),this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const lD=_g(vg(function(){var s=function(){function x(){this.listeners={}}var A=x.prototype;return A.on=function(k,M){this.listeners[k]||(this.listeners[k]=[]),this.listeners[k].push(M)},A.off=function(k,M){if(!this.listeners[k])return!1;var O=this.listeners[k].indexOf(M);return this.listeners[k]=this.listeners[k].slice(0),this.listeners[k].splice(O,1),O>-1},A.trigger=function(k){var M=this.listeners[k];if(M)if(arguments.length===2)for(var O=M.length,P=0;P>7)*283)^O]=O;for(P=U=0;!k[P];P^=W||1,U=J[U]||1)for(he=U^U<<1^U<<2^U<<3^U<<4,he=he>>8^he&255^99,k[P]=he,M[he]=P,te=V[ue=V[W=V[P]]],ie=te*16843009^ue*65537^W*257^P*16843008,H=V[he]*257^he*16843008,O=0;O<4;O++)A[O][P]=H=H<<24^H>>>8,D[O][he]=ie=ie<<24^ie>>>8;for(O=0;O<5;O++)A[O]=A[O].slice(0),D[O]=D[O].slice(0);return x};let i=null;class r{constructor(A){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 D,k,M;const O=this._tables[0][4],P=this._tables[1],U=A.length;let V=1;if(U!==4&&U!==6&&U!==8)throw new Error("Invalid aes key size");const J=A.slice(0),W=[];for(this._key=[J,W],D=U;D<4*U+28;D++)M=J[D-1],(D%U===0||U===8&&D%U===4)&&(M=O[M>>>24]<<24^O[M>>16&255]<<16^O[M>>8&255]<<8^O[M&255],D%U===0&&(M=M<<8^M>>>24^V<<24,V=V<<1^(V>>7)*283)),J[D]=J[D-U]^M;for(k=0;D;k++,D--)M=J[k&3?D:D-4],D<=4||k<4?W[k]=M:W[k]=P[0][O[M>>>24]]^P[1][O[M>>16&255]]^P[2][O[M>>8&255]]^P[3][O[M&255]]}decrypt(A,D,k,M,O,P){const U=this._key[1];let V=A^U[0],J=M^U[1],W=k^U[2],ue=D^U[3],te,he,H;const ie=U.length/4-2;let ot,se=4;const Ee=this._tables[1],Ht=Ee[0],bi=Ee[1],Si=Ee[2],xi=Ee[3],Ei=Ee[4];for(ot=0;ot>>24]^bi[J>>16&255]^Si[W>>8&255]^xi[ue&255]^U[se],he=Ht[J>>>24]^bi[W>>16&255]^Si[ue>>8&255]^xi[V&255]^U[se+1],H=Ht[W>>>24]^bi[ue>>16&255]^Si[V>>8&255]^xi[J&255]^U[se+2],ue=Ht[ue>>>24]^bi[V>>16&255]^Si[J>>8&255]^xi[W&255]^U[se+3],se+=4,V=te,J=he,W=H;for(ot=0;ot<4;ot++)O[(3&-ot)+P]=Ei[V>>>24]<<24^Ei[J>>16&255]<<16^Ei[W>>8&255]<<8^Ei[ue&255]^U[se++],te=V,V=J,J=W,W=ue,ue=te}}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(A){this.jobs.push(A),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const a=function(x){return x<<24|(x&65280)<<8|(x&16711680)>>8|x>>>24},o=function(x,A,D){const k=new Int32Array(x.buffer,x.byteOffset,x.byteLength>>2),M=new r(Array.prototype.slice.call(A)),O=new Uint8Array(x.byteLength),P=new Int32Array(O.buffer);let U,V,J,W,ue,te,he,H,ie;for(U=D[0],V=D[1],J=D[2],W=D[3],ie=0;ie{const k=x[D];_(k)?A[D]={bytes:k.buffer,byteOffset:k.byteOffset,byteLength:k.byteLength}:A[D]=k}),A};self.onmessage=function(x){const A=x.data,D=new Uint8Array(A.encrypted.bytes,A.encrypted.byteOffset,A.encrypted.byteLength),k=new Uint32Array(A.key.bytes,A.key.byteOffset,A.key.byteLength/4),M=new Uint32Array(A.iv.bytes,A.iv.byteOffset,A.iv.byteLength/4);new l(D,k,M,function(O,P){self.postMessage(v({source:A.source,decrypted:P}),[P.buffer])})}}));var cD=yg(lD);const dD=s=>{let e=s.default?"main":"alternative";return s.characteristics&&s.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},Rg=(s,e)=>{s.abort(),s.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},Gu=(s,e)=>{e.activePlaylistLoader=s,s.load()},hD=(s,e)=>()=>{const{segmentLoaders:{[s]:t,main:i},mediaTypes:{[s]:r}}=e,n=r.activeTrack(),a=r.getActiveGroup(),o=r.activePlaylistLoader,l=r.lastGroup_;if(!(a&&l&&a.id===l.id)&&(r.lastGroup_=a,r.lastTrack_=n,Rg(t,r),!(!a||a.isMainPlaylist))){if(!a.playlistLoader){o&&i.resetEverything();return}t.resyncLoader(),Gu(a.playlistLoader,r)}},fD=(s,e)=>()=>{const{segmentLoaders:{[s]:t},mediaTypes:{[s]:i}}=e;i.lastGroup_=null,t.abort(),t.pause()},pD=(s,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[s]:i,main:r},mediaTypes:{[s]:n}}=e,a=n.activeTrack(),o=n.getActiveGroup(),l=n.activePlaylistLoader,d=n.lastTrack_;if(!(d&&a&&d.id===a.id)&&(n.lastGroup_=o,n.lastTrack_=a,Rg(i,n),!!o)){if(o.isMainPlaylist){if(!a||!d||a.id===d.id)return;const p=e.vhs.playlistController_,y=p.selectPlaylist();if(p.media()===y)return;n.logger_(`track change. Switching main audio from ${d.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(l===o.playlistLoader){Gu(o.playlistLoader,n);return}i.track&&i.track(a),i.resetEverything(),Gu(o.playlistLoader,n)}},Ca={AUDIO:(s,e)=>()=>{const{mediaTypes:{[s]:t},excludePlaylist:i}=e,r=t.activeTrack(),n=t.activeGroup(),a=(n.filter(l=>l.default)[0]||n[0]).id,o=t.tracks[a];if(r===o){i({error:{message:"Problem encountered loading the default audio track."}});return}L.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const l in t.tracks)t.tracks[l].enabled=t.tracks[l]===o;t.onTrackChanged()},SUBTITLES:(s,e)=>()=>{const{mediaTypes:{[s]:t}}=e;L.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const i=t.activeTrack();i&&(i.mode="disabled"),t.onTrackChanged()}},jh={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",Ca[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",Ca[s](s,t))}},mD={AUDIO:(s,e)=>{const{vhs:t,sourceType:i,segmentLoaders:{[s]:r},requestOptions:n,main:{mediaGroups:a},mediaTypes:{[s]:{groups:o,tracks:l,logger_:d}},mainPlaylistLoader:p}=e,y=ln(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 _ in a[s]){o[_]||(o[_]=[]);for(const b in a[s][_]){let v=a[s][_][b],x;if(y?(d(`AUDIO group '${_}' label '${b}' is a main playlist`),v.isMainPlaylist=!0,x=null):i==="vhs-json"&&v.playlists?x=new fs(v.playlists[0],t,n):v.resolvedUri?x=new fs(v.resolvedUri,t,n):v.playlists&&i==="dash"?x=new qu(v.playlists[0],t,n,p):x=null,v=re({id:b,playlistLoader:x},v),jh[s](s,v.playlistLoader,e),o[_].push(v),typeof l[b]>"u"){const A=new L.AudioTrack({id:b,kind:dD(v),enabled:!1,language:v.language,default:v.default,label:b});l[b]=A}}}r.on("error",Ca[s](s,e))},SUBTITLES:(s,e)=>{const{tech:t,vhs:i,sourceType:r,segmentLoaders:{[s]:n},requestOptions:a,main:{mediaGroups:o},mediaTypes:{[s]:{groups:l,tracks:d}},mainPlaylistLoader:p}=e;for(const y in o[s]){l[y]||(l[y]=[]);for(const _ in o[s][y]){if(!i.options_.useForcedSubtitles&&o[s][y][_].forced)continue;let b=o[s][y][_],v;if(r==="hls")v=new fs(b.resolvedUri,i,a);else if(r==="dash"){if(!b.playlists.filter(A=>A.excludeUntil!==1/0).length)return;v=new qu(b.playlists[0],i,a,p)}else r==="vhs-json"&&(v=new fs(b.playlists?b.playlists[0]:b.resolvedUri,i,a));if(b=re({id:_,playlistLoader:v},b),jh[s](s,b.playlistLoader,e),l[y].push(b),typeof d[_]>"u"){const x=t.addRemoteTextTrack({id:_,kind:"subtitles",default:b.default&&b.autoselect,language:b.language,label:_},!1).track;d[_]=x}}}n.on("error",Ca[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 l=i[s][a][o];if(!/^(?:CC|SERVICE)/.test(l.instreamId))continue;const d=t.options_.vhs&&t.options_.vhs.captionServices||{};let p={label:o,language:l.language,instreamId:l.instreamId,default:l.default&&l.autoselect};if(d[p.instreamId]&&(p=re(p,d[p.instreamId])),p.default===void 0&&delete p.default,r[a].push(re({id:o},l)),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}}}}},Mg=(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&&ln(e.main))for(let l=0;l"u"?a:t===null||!a?null:a.filter(l=>l.id===t.id)[0]||null},yD={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}},_D=(s,{mediaTypes:e})=>()=>{const t=e[s].activeTrack();return t?e[s].activeGroup(t):null},vD=s=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(d=>{mD[d](d,s)});const{mediaTypes:e,mainPlaylistLoader:t,tech:i,vhs:r,segmentLoaders:{["AUDIO"]:n,main:a}}=s;["AUDIO","SUBTITLES"].forEach(d=>{e[d].activeGroup=gD(d,s),e[d].activeTrack=yD[d](d,s),e[d].onGroupChanged=hD(d,s),e[d].onGroupChanging=fD(d,s),e[d].onTrackChanged=pD(d,s),e[d].getActiveGroup=_D(d,s)});const o=e.AUDIO.activeGroup();if(o){const d=(o.filter(y=>y.default)[0]||o[0]).id;e.AUDIO.tracks[d].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(d=>e[d].onGroupChanged())}),t.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(d=>e[d].onGroupChanging())});const l=()=>{e.AUDIO.onTrackChanged(),i.trigger({type:"usage",name:"vhs-audio-change"})};i.audioTracks().addEventListener("change",l),i.remoteTextTracks().addEventListener("change",e.SUBTITLES.onTrackChanged),r.on("dispose",()=>{i.audioTracks().removeEventListener("change",l),i.remoteTextTracks().removeEventListener("change",e.SUBTITLES.onTrackChanged)}),i.clearTracks("audio");for(const d in e.AUDIO.tracks)i.audioTracks().addTrack(e.AUDIO.tracks[d])},TD=()=>{const s={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{s[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:Jt,activeTrack:Jt,getActiveGroup:Jt,onGroupChanged:Jt,onTrackChanged:Jt,lastTrack_:null,logger_:St(`MediaGroups[${e}]`)}}),s};class qh{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_=it(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 bD extends L.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new qh,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_=St("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=it(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}this.request_=this.xhr_({uri:i,requestType:"content-steering-manifest"},(r,n)=>{if(r){if(n.status===410){this.logger_(`manifest request 410 ${r}.`),this.logger_(`There will be no more content steering requests to ${i} this session.`),this.excludedSteeringManifestURLs.add(i);return}if(n.status===429){const o=n.responseHeaders["retry-after"];this.logger_(`manifest request 429 ${r}.`),this.logger_(`content steering will retry in ${o} seconds.`),this.startTTLTimeout_(parseInt(o,10));return}this.logger_(`manifest failed to load ${r}.`),this.startTTLTimeout_();return}const a=JSON.parse(this.request_.responseText);this.assignSteeringProperties_(a),this.startTTLTimeout_()})}setProxyServerUrl_(e){const t=new C.URL(e),i=new C.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(C.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new C.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_=C.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){C.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 qh}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&&(it(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}}const SD=10;let Wt;const xD=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],ED=function(s){return this.audioSegmentLoader_[s]+this.mainSegmentLoader_[s]},CD=function({currentPlaylist:s,buffered:e,currentTime:t,nextPlaylist:i,bufferLowWaterLine:r,bufferHighWaterLine:n,duration:a,bufferBasedABR:o,log:l}){if(!i)return L.log.warn("We received no playlist to switch to. Please check your stream."),!1;const d=`allowing switch ${s&&s.id||"null"} -> ${i.id}`;if(!s)return l(`${d} as current playlist is not set`),!0;if(i.id===s.id)return!1;const p=!!hs(e,t).length;if(!s.endList)return!p&&typeof s.partTargetDuration=="number"?(l(`not ${d} as current playlist is live llhls, but currentTime isn't in buffered.`),!1):(l(`${d} as current playlist is live`),!0);const y=Xl(e,t),_=o?Ne.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:Ne.MAX_BUFFER_LOW_WATER_LINE;if(a<_)return l(`${d} as duration < max low water line (${a} < ${_})`),!0;const b=i.attributes.BANDWIDTH,v=s.attributes.BANDWIDTH;if(bv)&&y>=r){let x=`${d} as forwardBuffer >= bufferLowWaterLine (${y} >= ${r})`;return o&&(x+=` and next bandwidth > current bandwidth (${b} > ${v})`),l(x),!0}return l(`not ${d} as no switching criteria met`),!1};class wD extends L.EventTarget{constructor(e){super();const{src:t,withCredentials:i,tech:r,bandwidth:n,externVhs:a,useCueTags:o,playlistExclusionDuration:l,enableLowInitialPlaylist:d,sourceType:p,cacheEncryptionKeys:y,bufferBasedABR:_,leastPixelDiffSelector:b,captionServices:v}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:x}=e;(x===null||typeof x>"u")&&(x=1/0),Wt=a,this.bufferBasedABR=!!_,this.leastPixelDiffSelector=!!b,this.withCredentials=i,this.tech_=r,this.vhs_=r.vhs,this.sourceType_=p,this.useCueTags_=o,this.playlistExclusionDuration=l,this.maxPlaylistRetries=x,this.enableLowInitialPlaylist=d,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:x,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=TD(),this.mediaSource=new C.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 oD(e),this.segmentMetadataTrack_=r.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.decrypter_=new cD,this.sourceUpdater_=new Og(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new uD,this.keyStatusMap_=new Map;const A={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:v,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 qu(t,this.vhs_,re(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new fs(t,this.vhs_,re(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new Hu(re(A,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new Hu(re(A,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new iD(re(A,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((M,O)=>{function P(){r.off("vttjserror",U),M()}function U(){r.off("vttjsloaded",P),O()}r.one("vttjsloaded",P),r.one("vttjserror",U),r.addWebVttScript_()})}),e);const D=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new bD(this.vhs_.xhr,D),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_())),xD.forEach(M=>{this[M+"_"]=ED.bind(this,M)}),this.logger_=St("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 k=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(k,()=>{const M=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-M,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);n&&n!==a&&(this.logger_(`switch media ${n} -> ${a} from ${t}`),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_=C.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(C.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 l in o)if(o[l].default){n={label:l};break}}if(!n)return t;const a=[];for(const o in i)if(i[o][n.label]){const l=i[o][n.label];if(l.playlists&&l.playlists.length)a.push.apply(a,l.playlists);else if(l.uri)a.push(l);else if(e.playlists.length)for(let d=0;d{const e=this.mainPlaylistLoader_.media(),t=e.targetDuration*1.5*1e3;Bu(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,e.endList&&this.tech_.preload()!=="none"&&(this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.mainSegmentLoader_.load()),vD({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(),e),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 e=this.mainPlaylistLoader_.media();if(!e){this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_();let t;if(this.enableLowInitialPlaylist&&(t=this.selectInitialPlaylist()),t||(t=this.selectPlaylist()),!t||!this.shouldSwitchToMedia_(t)||(this.initialMedia_=t,this.switchMedia_(this.initialMedia_,"initial"),!(this.sourceType_==="vhs-json"&&this.initialMedia_.segments)))return;e=this.initialMedia_}this.handleUpdatedMediaPlaylist(e)}),this.mainPlaylistLoader_.on("error",()=>{const e=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:e.playlist,error:e})}),this.mainPlaylistLoader_.on("mediachanging",()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()}),this.mainPlaylistLoader_.on("mediachange",()=>{const e=this.mainPlaylistLoader_.media(),t=e.targetDuration*1.5*1e3;Bu(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,this.sourceType_==="dash"&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})}),this.mainPlaylistLoader_.on("playlistunchanged",()=>{const e=this.mainPlaylistLoader_.media();if(e.lastExcludeReason_==="playlist-unchanged")return;this.stuckAtPlaylistEnd_(e)&&(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"})})}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"}),Wt.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 CD({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 t=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:t.playlist,error:t})}),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.mainSegmentLoader_.on("earlyabort",t=>{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:SD}))});const e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const t=this.getCodecsOrExclude_();t&&this.sourceUpdater_.addOrChangeSourceBuffers(t)};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()})}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.tech_.setCurrentTime(this.tech_.currentTime())})}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=Wt.Playlist.playlistEnd(e,i),n=this.tech_.currentTime(),a=this.tech_.buffered();if(!a.length)return r-n<=Mt;const o=a.end(a.length-1);return o-n<=Mt&&r-o<=Mt}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(no),a=n.length===1&&n[0]===e;if(r.length===1&&i!==1/0)return L.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 v=this.pathwayAttribute_(e),x=this.contentSteeringController_.steeringManifest.ttl*1e3;this.contentSteeringController_.excludePathway(v),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(v)},x);return}let b=!1;r.forEach(v=>{if(v===e)return;const x=v.excludeUntil;typeof x<"u"&&x!==1/0&&(b=!0,delete v.excludeUntil)}),b&&(L.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 l=this.selectPlaylist();if(!l){this.error="Playback cannot continue. No available working or supported playlists.",this.trigger("error");return}const d=t.internal?this.logger_:L.log.warn,p=t.message?" "+t.message:"";d(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${p} Switching to playlist ${l.id}.`),l.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),l.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);const y=l.targetDuration/2*1e3||5*1e3,_=typeof l.lastRequest=="number"&&Date.now()-l.lastRequest<=y;return this.switchMedia_(l,"exclude",a||_)}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=hs(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:Wt.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=Wt.Playlist.seekable(t,i,Wt.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=Wt.Playlist.seekable(t,i,Wt.Playlist.liveEdgeDelay(r,t)),e.length===0)))return;let a,o;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=Or(this.main(),t),r={},n=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(r.video=i.video||e.main.videoCodec||KS),e.main.isMuxed&&(r.video+=`,${i.audio||e.main.audioCodec||wd}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||n)&&(r.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||wd,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=(d,p)=>d?Yn(p):Ho(p),o={};let l;if(["video","audio"].forEach(function(d){if(r.hasOwnProperty(d)&&!a(e[d].isFmp4,r[d])){const p=e[d].isFmp4?"browser":"muxer";o[p]=o[p]||[],o[p].push(r[d]),d==="audio"&&(l=p)}}),n&&l&&t.attributes.AUDIO){const d=t.attributes.AUDIO;this.main().playlists.forEach(p=>{(p.attributes&&p.attributes.AUDIO)===d&&p!==t&&(p.excludeUntil=1/0)}),this.logger_(`excluding audio group ${d} as ${l} does not support codec(s): "${r.audio}"`)}if(Object.keys(o).length){const d=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:d},playlistExclusionDuration:1/0});return}if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const d=[];if(["video","audio"].forEach(p=>{const y=(It(this.sourceUpdater_.codecs[p]||"")[0]||{}).type,_=(It(r[p]||"")[0]||{}).type;y&&_&&y.toLowerCase()!==_.toLowerCase()&&d.push(`"${this.sourceUpdater_.codecs[p]}" -> "${r[p]}"`)}),d.length){this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${d.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=Or(this.main,r),a=[];n.audio&&!Ho(n.audio)&&!Yn(n.audio)&&a.push(`audio codec ${n.audio}`),n.video&&!Ho(n.video)&&!Yn(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=xa(It(e)),n=kh(r),a=r.video&&It(r.video)[0]||null,o=r.audio&&It(r.audio)[0]||null;Object.keys(i).forEach(l=>{const d=i[l];if(t.indexOf(d.id)!==-1||d.excludeUntil===1/0)return;t.push(d.id);const p=[],y=Or(this.mainPlaylistLoader_.main,d),_=kh(y);if(!(!y.audio&&!y.video)){if(_!==n&&p.push(`codec count "${_}" !== "${n}"`),!this.sourceUpdater_.canChangeType()){const b=y.video&&It(y.video)[0]||null,v=y.audio&&It(y.audio)[0]||null;b&&a&&b.type.toLowerCase()!==a.type.toLowerCase()&&p.push(`video codec "${b.type}" !== "${a.type}"`),v&&o&&v.type.toLowerCase()!==o.type.toLowerCase()&&p.push(`audio codec "${v.type}" !== "${o.type}"`)}p.length&&(d.excludeUntil=1/0,this.logger_(`excluding ${d.id}: ${p.join(" && ")}`))}})}updateAdCues_(e){let t=0;const i=this.seekable();i.length&&(t=i.start(0)),rD(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=Ne.GOAL_BUFFER_LENGTH,i=Ne.GOAL_BUFFER_LENGTH_RATE,r=Math.max(t,Ne.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,r)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=Ne.BUFFER_LOW_WATER_LINE,i=Ne.BUFFER_LOW_WATER_LINE_RATE,r=Math.max(t,Ne.MAX_BUFFER_LOW_WATER_LINE),n=Math.max(t,Ne.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?n:r)}bufferHighWaterLine(){return Ne.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){Lh(this.inbandTextTracks_,"com.apple.streaming",this.tech_),FA({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const r=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();Lh(this.inbandTextTracks_,e,this.tech_),NA({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)),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const e=this.main();(this.contentSteeringController_.didDASHTagChange(e.uri,e.contentSteering)||(()=>{const r=this.contentSteeringController_.getAvailablePathways(),n=[];for(const a of e.playlists){const o=a.attributes.serviceLocation;if(o&&(n.push(o),!r.has(o)))return!0}return!!(!n.length&&r.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],l=this.pathwayAttribute_(o),d=l&&e!==l;o.excludeUntil===1/0&&o.lastExcludeReason_==="content-steering"&&!d&&(delete o.excludeUntil,delete o.lastExcludeReason_,n=!0);const y=!o.excludeUntil&&o.excludeUntil!==1/0;!r.has(o.id)&&d&&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 l=o.activePlaylistLoader.media_;l&&l.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 l=i.get(a);if(!l){t.filter(p=>p.attributes["PATHWAY-ID"]===o["BASE-ID"]).forEach(p=>{this.mainPlaylistLoader_.addClonePathway(o,p)}),this.contentSteeringController_.addAvailablePathway(a);continue}this.equalPathwayClones_(l,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,l=i.lastExcludeReason_===t&&i.excludeUntil===1/0;o?o&&l&&(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,L.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 AD=(s,e,t)=>i=>{const r=s.main.playlists[e],n=Ql(r),a=no(r);return typeof i>"u"?a:(i?delete r.disabled:r.disabled=!0,i!==a&&!n&&(t(r),i?s.trigger("renditionenabled"):s.trigger("renditiondisabled")),i)};class DD{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=Or(r.main(),t),this.playlist=t,this.id=i,this.enabled=AD(e.playlists,t.id,n)}}const kD=function(s){s.representations=()=>{const e=s.playlistController_.main(),t=ln(e)?s.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(i=>!Ql(i)).map((i,r)=>new DD(s,i,i.id)):[]}},Vh=["seeking","seeked","pause","playing","error"];class ID{constructor(e){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.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=St("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),r=()=>this.techWaiting_(),n=()=>this.resetTimeUpdate_(),a=this.playlistController_,o=["main","subtitle","audio"],l={};o.forEach(p=>{l[p]={reset:()=>this.resetSegmentDownloads_(p),updateend:()=>this.checkSegmentDownloads_(p)},a[`${p}SegmentLoader_`].on("appendsdone",l[p].updateend),a[`${p}SegmentLoader_`].on("playlistupdate",l[p].reset),this.tech_.on(["seeked","seeking"],l[p].reset)});const d=p=>{["main","audio"].forEach(y=>{a[`${y}SegmentLoader_`][p]("appended",this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),d("off"))},this.clearSeekingAppendCheck_=()=>d("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),d("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",r),this.tech_.on(Vh,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(Vh,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",l[p].updateend),a[`${p}SegmentLoader_`].off("playlistupdate",l[p].reset),this.tech_.off(["seeked","seeking"],l[p].reset)}),this.checkCurrentTimeTimeout_&&C.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&C.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=C.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=vw(this[`${e}Buffered_`],r);if(this[`${e}Buffered_`]=r,n){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:Bi(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+Mt>=t.end(t.length-1)))return this.techWaiting_();this.consecutiveUpdates>=5&&e===this.lastRecordedTime?(this.consecutiveUpdates++,this.waiting_()):e===this.lastRecordedTime?this.consecutiveUpdates++:(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 v=t.start(0);n=v+(v===t.end(0)?0:Mt)}if(typeof n<"u")return this.logger_(`Trying to seek outside of seekable at time ${i} with seekable range ${Km(t)}. Seeking to ${n}.`),this.tech_.setCurrentTime(n),!0;const a=this.playlistController_.sourceUpdater_,o=this.tech_.buffered(),l=a.audioBuffer?a.audioBuffered():null,d=a.videoBuffer?a.videoBuffered():null,p=this.media(),y=p.partTargetDuration?p.partTargetDuration:(p.targetDuration-Rt)*2,_=[l,d];for(let v=0;v<_.length;v++){if(!_[v])continue;if(Xl(_[v],i) ${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=qn(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)+Mt;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 PD={errorInterval:30,getSource(s){const t=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return s(t)}},Ng=function(s,e){let t=0,i=0;const r=re(PD,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(Te,s,{get(){return L.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),Ne[s]},set(e){if(L.log.warn(`using Vhs.${s} is UNSAFE be sure you know what you are doing`),typeof e!="number"||e<0){L.log.warn(`value of Vhs.${s} must be greater than or equal to 0`);return}Ne[s]=e}})});const Ug="videojs-vhs",Fg=function(s,e){const t=e.media();let i=-1;for(let r=0;r{s.addQualityLevel(t)}),Fg(s,e.playlists)};Te.canPlaySource=function(){return L.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const UD=(s,e,t)=>{if(!s)return s;let i={};e&&e.attributes&&e.attributes.CODECS&&(i=xa(It(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(i.audio=t.attributes.CODECS);const r=Br(i.video),n=Br(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 re(s,a)},FD=(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},[]),$D=({player:s,sourceKeySystems:e,audioMedia:t,mainPlaylists:i})=>{if(!s.eme.initializeMediaKeys)return Promise.resolve();const r=t?i.concat([t]):i,n=FD(r,Object.keys(e)),a=[],o=[];return n.forEach(l=>{o.push(new Promise((d,p)=>{s.tech_.one("keysessioncreated",d)})),a.push(new Promise((d,p)=>{s.eme.initializeMediaKeys({keySystems:l},y=>{if(y){p(y);return}d()})}))}),Promise.race([Promise.all(a),Promise.race(o)])},jD=({player:s,sourceKeySystems:e,media:t,audioMedia:i})=>{const r=UD(e,t,i);return r?(s.currentSource().keySystems=r,r&&!s.eme?(L.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0):!1},$g=()=>{if(!C.localStorage)return null;const s=C.localStorage.getItem(Ug);if(!s)return null;try{return JSON.parse(s)}catch{return null}},qD=s=>{if(!C.localStorage)return!1;let e=$g();e=e?re(e,s):s;try{C.localStorage.setItem(Ug,JSON.stringify(e))}catch{return!1}return e},VD=s=>s.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(s.substring(s.indexOf(",")+1)):s,jg=(s,e)=>{s._requestCallbackSet||(s._requestCallbackSet=new Set),s._requestCallbackSet.add(e)},qg=(s,e)=>{s._responseCallbackSet||(s._responseCallbackSet=new Set),s._responseCallbackSet.add(e)},Vg=(s,e)=>{s._requestCallbackSet&&(s._requestCallbackSet.delete(e),s._requestCallbackSet.size||delete s._requestCallbackSet)},Hg=(s,e)=>{s._responseCallbackSet&&(s._responseCallbackSet.delete(e),s._responseCallbackSet.size||delete s._responseCallbackSet)};Te.supportsNativeHls=function(){if(!$||!$.createElement)return!1;const s=$.createElement("video");return L.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}();Te.supportsNativeDash=function(){return!$||!$.createElement||!L.getTech("Html5").isSupported()?!1:/maybe|probably/i.test($.createElement("video").canPlayType("application/dash+xml"))}();Te.supportsTypeNatively=s=>s==="hls"?Te.supportsNativeHls:s==="dash"?Te.supportsNativeDash:!1;Te.isSupported=function(){return L.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};Te.xhr.onRequest=function(s){jg(Te.xhr,s)};Te.xhr.onResponse=function(s){qg(Te.xhr,s)};Te.xhr.offRequest=function(s){Vg(Te.xhr,s)};Te.xhr.offResponse=function(s){Hg(Te.xhr,s)};const HD=L.getComponent("Component");class zg extends HD{constructor(e,t,i){if(super(t,i.vhs),typeof i.initialBandwidth=="number"&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=St("VhsHandler"),t.options_&&t.options_.playerId){const r=L.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_=re(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=$g();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=Ne.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===Ne.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=VD(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=Te,this.options_.sourceType=qf(t),this.options_.seekTo=n=>{this.tech_.setCurrentTime(n)},this.playlistController_=new wD(this.options_);const i=re({liveRangeSafeTimeDelta:Mt},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new ID(i),this.playlistController_.on("error",()=>{const n=L.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?Te.movingAverageBandwidthSelector(.55):Te.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):r.bind(this),this.playlistController_.selectInitialPlaylist=Te.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=C.navigator.connection||C.navigator.mozConnection||C.navigator.webkitConnection,o=1e7;if(this.options_.useNetworkInformationApi&&a){const l=a.downlink*1e3*1e3;l>=o&&n>=o?n=Math.max(n,l):n=l}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(){L.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:()=>Bi(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:()=>Bi(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&&qD({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{kD(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_=C.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"),$D({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,metadata:{errorType:L.Error.EMEKeySessionCreationError}})})}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=jD({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=L.players[this.tech_.options_.playerId];!e||!e.qualityLevels||this.qualityLevels_||(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{BD(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{Fg(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":Bg,"mux.js":OD,"mpd-parser":RD,"m3u8-parser":MD,"aes-decrypter":ND}}version(){return this.constructor.version()}canChangeType(){return Og.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_&&C.URL.revokeObjectURL&&(C.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 mg({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=>{jg(this.xhr,e)},this.xhr.onResponse=e=>{qg(this.xhr,e)},this.xhr.offRequest=e=>{Vg(this.xhr,e)},this.xhr.offResponse=e=>{Hg(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}}const wa={name:"videojs-http-streaming",VERSION:Bg,canHandleSource(s,e={}){const t=re(L.options,e);return wa.canPlayType(s.type,t)},handleSource(s,e,t={}){const i=re(L.options,t);return e.vhs=new zg(s,e,i),e.vhs.xhr=cg(),e.vhs.setupXhrHooks_(),e.vhs.src(s.src,s.type),e.vhs},canPlayType(s,e){const t=qf(s);if(!t)return"";const i=wa.getOverrideNative(e);return!Te.supportsTypeNatively(t)||i?"maybe":""},getOverrideNative(s={}){const{vhs:e={}}=s,t=!(L.browser.IS_ANY_SAFARI||L.browser.IS_IOS),{overrideNative:i=t}=e;return i}},zD=()=>Yn("avc1.4d400d,mp4a.40.2");zD()&&L.getTech("Html5").registerSourceHandler(wa,0);L.VhsHandler=zg;L.VhsSourceHandler=wa;L.Vhs=Te;L.use||L.registerComponent("Vhs",Te);L.options.vhs=L.options.vhs||{};(!L.getPlugin||!L.getPlugin("reloadSourceOnError"))&&L.registerPlugin("reloadSourceOnError",LD);/*! @name videojs-contrib-eme @version 3.11.2 @license Apache-2.0 */function Aa(){return Aa=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 YD=function(e){var t=String.fromCharCode.apply(null,new Uint16Array(e)),i=new C.DOMParser().parseFromString(t,"application/xml"),r=i.getElementsByTagName("HttpHeaders")[0],n={};if(r)for(var a=r.getElementsByTagName("name"),o=r.getElementsByTagName("value"),l=0;l"u"){i.mediaKeysObject=null,i.pendingSessionData=[];var y,_;p=new Promise(function(b,v){if(i.keySystem=a.keySystem,_=zh(a.keySystem,o.keySystems[a.keySystem]),!_.getCertificate){b(a);return}_.getCertificate(o,function(x,A){if(x){v(x);return}y=A,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=zh(i.keySystem,o.keySystems[i.keySystem]),v=b.getLicense;return ZD({player:t,video:i,initDataType:r,initData:n,options:o,getLicense:i.keySystem?sk(v,d):null,removeSession:l,eventBus:d})})},ic="com.apple.fps.1_0",nk=function(e){var t=e.initData,i=e.id,r=e.cert;typeof i=="string"&&(i=GD(i));var n=0,a=new ArrayBuffer(t.byteLength+4+i.byteLength+4+r.byteLength),o=new DataView(a),l=new Uint8Array(a,n,t.byteLength);l.set(t),n+=t.byteLength,o.setUint32(n,i.byteLength,!0),n+=4;var d=new Uint16Array(a,n,i.length);d.set(i),n+=d.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)},ak=function(e){var t=e.video,i=e.contentId,r=e.initData,n=e.cert,a=e.options,o=e.getLicense,l=e.eventBus;return new Promise(function(d,p){if(!t.webkitKeys)try{t.webkitSetMediaKeys(new C.WebKitMediaKeys(ic))}catch{p("Could not create MediaKeys");return}var y;try{y=t.webkitKeys.createSession("video/mp4",nk({id:i,initData:r,cert:n}))}catch{p("Could not create key session");return}l.trigger("keysessioncreated"),y.contentId=i,y.addEventListener("webkitkeymessage",function(_){o(a,i,_.message,function(b,v){if(l&&l.trigger("licenserequestattempted"),b){p(b);return}y.update(new Uint8Array(v))})}),y.addEventListener("webkitkeyadded",function(){d()}),y.addEventListener("webkitkeyerror",function(){var _=y.error;p("KeySession error: code "+_.code+", systemCode "+_.systemCode)})})},ok=function(e){return function(t,i){var r=ao(t.emeHeaders,e.certificateHeaders);L.xhr({uri:e.certificateUri,responseType:"arraybuffer",headers:r},Us(function(n,a){if(n){i(n);return}i(null,new Uint8Array(a))}))}},uk=function(e,t){return KD(WD(t))},lk=function(e){return function(t,i,r,n){var a=ao({"Content-type":"application/octet-stream"},t.emeHeaders,e.licenseHeaders);L.xhr({uri:e.licenseUri,method:"POST",responseType:"arraybuffer",body:r,headers:a},Us(n,!0))}},ck=function(e){var t=e.video,i=e.initData,r=e.options,n=e.eventBus,a=r.keySystems[ic],o=a.getCertificate||ok(a),l=a.getContentId||uk,d=a.getLicense||lk(a);return new Promise(function(p,y){o(r,function(_,b){if(_){y(_);return}p(b)})}).then(function(p){return ak({video:t,cert:p,initData:i,getLicense:d,options:r,contentId:l(r,i),eventBus:n})})},ps="com.microsoft.playready",dk=function(e,t,i,r){var n=e.keySystems[ps];if(typeof n.getKey=="function"){n.getKey(e,i.destinationURL,i.message.buffer,function(o,l){if(o){r.trigger({message:"Unable to get key: "+o,target:t,type:"mskeyerror"});return}t.update(l)});return}typeof n=="string"?n={url:n}:typeof n=="boolean"&&(n={}),n.url||(n.url=i.destinationURL);var a=function(l,d){if(r&&r.trigger("licenserequestattempted"),l){r.trigger({message:"Unable to request key from url: "+n.url,target:t,type:"mskeyerror"});return}t.update(new Uint8Array(d))};n.getLicense?n.getLicense(e,i.message.buffer,a):Gg(n,i.message.buffer,e,a)},hk=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){dk(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"})})},fk=function(s){var e=s.video,t=s.initData,i=s.options,r=s.eventBus;e.msKeys&&delete e.msKeys;try{e.msSetMediaKeys(new C.MSMediaKeys(ps))}catch(n){throw new Error("Unable to create media keys for PlayReady key system. Error: "+n.message)}hk(e,t,i,r)},pk="3.11.2",mk=function(e,t){for(var i=0;i=0)&&(t[r]=s[r]);return t}function Kh(s,e){if(s==null)return{};var t=xk(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 Ek="1.12.1";const Ck=L.getComponent("player");class wk extends Ck{constructor(e,t,i){t=L.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"))}}L.registerComponent("player",wk);const De=L;De.VERSION={pillarbox:Ek,videojs:L.VERSION,[L.VhsSourceHandler.name]:L.VhsSourceHandler.VERSION,eme:L.getPlugin("eme").VERSION};De.options.enableSmoothSeeking=!0;De.options.fill=!0;De.options.html5={vhs:{useForcedSubtitles:!0}};De.options.liveTracker={trackingThreshold:120,liveTolerance:15};De.options.liveui=!0;De.options.playsinline=!0;De.options.responsive=!0;De.options.trackers={};class Xh{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=ls(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 as={WIDTH_240:"240",WIDTH_320:"320",WIDTH_480:"480",WIDTH_960:"960",WIDTH_1920:"1920"},Gn={JPG:"jpg",WEBP:"webp",PNG:"png"},Ak="https://il.srgssr.ch/images/";class Dk{static scale({url:e,width:t=as.WIDTH_960,format:i=Gn.JPG}={},r=Ak){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 Gn.JPG}static get PNG(){return Gn.PNG}static get WEBP(){return Gn.WEBP}static get WIDTH_240(){return as.WIDTH_240}static get WIDTH_320(){return as.WIDTH_320}static get WIDTH_480(){return as.WIDTH_480}static get WIDTH_960(){return as.WIDTH_960}static get WIDTH_1920(){return as.WIDTH_1920}}const kk={WIDEVINE:"com.widevine.alpha",FAIRPLAY:"com.apple.fps.1_0",PLAYREADY:"com.microsoft.playready"};class zr{static buildKeySystems(e=[]){const t={};return e.forEach(i=>{const r=zr.vendors[i.type];if(zr.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 kk}}const Wn={AKAMAI:"AKAMAI",NONE:"NONE"};class Hi{static aclPath(e){const t=e.pathname;return`${t.substring(0,t.lastIndexOf("/")+1)}*`}static get AKAMAI(){return Wn.AKAMAI}static hasToken(e){return e.some(t=>Hi.isAkamai(t.tokenType))}static isAkamai(e){return Wn.AKAMAI===e}static isNone(e){return Wn.NONE===e}static get NONE(){return Wn.NONE}static tokenize(e,t){const i=new URL(`${e.url}`),r=Hi.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((l,d)=>i.searchParams.set(d,l)),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=Hi.tokenize(r,t);i.push(n)}),Promise.all(i).then(r=>r).catch(r=>Promise.reject(r))}}const Yh="emptied",Qh="ended",Jh="loadeddata",Zh="loadstart",lu="pause",Ik="play",cu="playing",ef="ratechange",tf="seeking",du="timeupdate",sf="waiting";class Ri{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(Yh,this.emptiedListener),this.player.off(Qh,this.endedListener),this.player.off(Zh,this.loadstartListener),this.player.off(Jh,this.loadeddataListener),this.player.off(cu,this.playListener),this.player.off(lu,this.pauseListener),this.player.off(ef,this.rateChangeListener),this.player.off(tf,this.seekingListener),this.player.off(du,this.timeUpdateListener),this.player.off(sf,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=Ri.now()-this.startPlaybackSession|0;return this.elapsedPlaybackTime+e}getEventLabels(e){const t={event_id:e,event_timestamp:Ri.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=[Ik,lu].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(Yh,this.emptiedListener),this.player.on(Qh,this.endedListener),this.player.on(Zh,this.loadstartListener),this.player.on(Jh,this.loadeddataListener),this.player.on(cu,this.playListener),this.player.on(lu,this.pauseListener),this.player.on(ef,this.rateChangeListener),this.player.on(tf,this.seekingListener),this.player.on(du,this.timeUpdateListener),this.player.on(sf,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()===Ri.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=Ri.now()),this.mediaSession===0&&(this.mediaSession=Ri.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"),De.browser.IS_ANY_SAFARI?this.player.one(du,e):this.player.one(cu,e)}}class Pk{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 $e($e($e({},this.analyticsData),this.getMainChapter().analyticsData),e)}getMergedAnalyticsMetadata(e){return $e($e($e({},this.analyticsMetadata),this.getMainChapter().analyticsMetadata),e)}getResourceList(){const{resourceList:e}=this.getMainChapter();return e||[]}}var Qg="Wiedergabe",Jg="Pause",Zg="Erneut abspielen",e0="Dauer",t0="LIVE",i0="Geladen",s0="Status",r0="Vollbild",n0="Stumm schalten",a0="Ton einschalten",o0="Untertitel",u0="Untertitel",l0="Kapitel",c0="Schließen",d0="Beschreibungen",h0="Schrift",f0="Weiß",p0="Schwarz",m0="Rot",g0="Grün",y0="Blau",_0="Gelb",v0="Magenta",T0="Türkis",b0="Hintergrund",S0="Fenster",x0="Durchsichtig",E0="Undurchsichtig",C0="Kein",w0="Erhoben",A0="Gedrückt",D0="Uniform",k0="Zwanglos",I0="Schreibschrift",P0="Zurücksetzen",L0="Fertig",O0="Farbe",R0="Deckkraft",Lk={Play:Qg,Pause:Jg,Replay:Zg,"Current Time":"Aktueller Zeitpunkt",Duration:e0,"Remaining Time":"Verbleibende Zeit","Stream Type":"Streamtyp",LIVE:t0,Loaded:i0,Progress:s0,Fullscreen:r0,"Exit Fullscreen":"Vollbildmodus beenden",Mute:n0,Unmute:a0,"Playback Rate":"Wiedergabegeschwindigkeit",Subtitles:o0,"subtitles off":"Untertitel aus",Captions:u0,"captions off":"Untertitel aus",Chapters:l0,"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:c0,"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:d0,"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:h0,White:f0,Black:p0,Red:m0,Green:g0,Blue:y0,Yellow:_0,Magenta:v0,Cyan:T0,Background:b0,Window:S0,Transparent:x0,"Semi-Transparent":"Halbdurchsichtig",Opaque:E0,"Font Size":"Schriftgröße","Text Edge Style":"Textkantenstil",None:C0,Raised:w0,Depressed:A0,Uniform:D0,"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:k0,Script:I0,"Small Caps":"Small-Caps",Reset:P0,"restore all settings to the default values":"Alle Einstellungen auf die Standardwerte zurücksetzen",Done:L0,"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:O0,Opacity:R0,"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"},Ok=Object.freeze({__proto__:null,Background:b0,Black:p0,Blue:y0,Captions:u0,Casual:k0,Chapters:l0,Close:c0,Color:O0,Cyan:T0,Depressed:A0,Descriptions:d0,Done:L0,Duration:e0,Fullscreen:r0,Green:g0,LIVE:t0,Loaded:i0,Magenta:v0,Mute:n0,None:C0,Opacity:R0,Opaque:E0,Pause:Jg,Play:Qg,Progress:s0,Raised:w0,Red:m0,Replay:Zg,Reset:P0,Script:I0,Subtitles:o0,Text:h0,Transparent:x0,Uniform:D0,Unmute:a0,White:f0,Window:S0,Yellow:_0,default:Lk}),M0="Aus Gründen des Jugendschutzes steht dieser Inhalt nur zwischen 20:00 und 06:00 Uhr zur Verfügung.",N0="Aus Gründen des Jugendschutzes steht dieser Inhalt nur zwischen 23:00 und 05:00 Uhr zur Verfügung.",B0="Die Werbung wurde übersprungen.",U0="Dieser Inhalt ist nicht mehr verfügbar.",F0="Dieser Inhalt ist ausserhalb der Schweiz nicht verfügbar.",$0="Dieser Inhalt ist aus rechtlichen Gründen nicht verfügbar.",j0="Dieser Inhalt ist noch nicht verfügbar. Bitte probieren Sie es später noch einmal.",q0="Dieser Inhalt ist nicht verfügbar.",Rk={AGERATING12:M0,AGERATING18:N0,COMMERCIAL:B0,ENDDATE:U0,GEOBLOCK:F0,LEGAL:$0,STARTDATE:j0,UNKNOWN:q0},Mk=Object.freeze({__proto__:null,AGERATING12:M0,AGERATING18:N0,COMMERCIAL:B0,ENDDATE:U0,GEOBLOCK:F0,LEGAL:$0,STARTDATE:j0,UNKNOWN:q0,default:Rk});De.addLanguage("de",$e($e({},Ok),Mk));var V0="Play",H0="Pause",z0="Replay",G0="Duration",W0="LIVE",K0="Loaded",X0="Progress",Y0="Fullscreen",Q0="Mute",J0="Unmute",Z0="Subtitles",ey="Captions",ty="Chapters",iy="Descriptions",sy="Close",ry="Text",ny="White",ay="Black",oy="Red",uy="Green",ly="Blue",cy="Yellow",dy="Magenta",hy="Cyan",fy="Background",py="Window",my="Transparent",gy="Opaque",yy="None",_y="Raised",vy="Depressed",Ty="Uniform",by="Casual",Sy="Script",xy="Reset",Ey="Done",Cy="Color",wy="Opacity",Nk={"Audio Player":"Audio Player","Video Player":"Video Player",Play:V0,Pause:H0,Replay:z0,"Current Time":"Current Time",Duration:G0,"Remaining Time":"Remaining Time","Stream Type":"Stream Type",LIVE:W0,"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:K0,Progress:X0,"Progress Bar":"Progress Bar","progress bar timing: currentTime={1} duration={2}":"{1} of {2}",Fullscreen:Y0,"Exit Fullscreen":"Exit Fullscreen",Mute:Q0,Unmute:J0,"Playback Rate":"Playback Rate",Subtitles:Z0,"subtitles off":"subtitles off",Captions:ey,"captions off":"captions off",Chapters:ty,Descriptions:iy,"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:sy,"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:ry,White:ny,Black:ay,Red:oy,Green:uy,Blue:ly,Yellow:cy,Magenta:dy,Cyan:hy,Background:fy,Window:py,Transparent:my,"Semi-Transparent":"Semi-Transparent",Opaque:gy,"Font Size":"Font Size","Text Edge Style":"Text Edge Style",None:yy,Raised:_y,Depressed:vy,Uniform:Ty,"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:by,Script:Sy,"Small Caps":"Small Caps",Reset:xy,"restore all settings to the default values":"restore all settings to the default values",Done:Ey,"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:Cy,Opacity:wy,"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"},Bk=Object.freeze({__proto__:null,Background:fy,Black:ay,Blue:ly,Captions:ey,Casual:by,Chapters:ty,Close:sy,Color:Cy,Cyan:hy,Depressed:vy,Descriptions:iy,Done:Ey,Duration:G0,Fullscreen:Y0,Green:uy,LIVE:W0,Loaded:K0,Magenta:dy,Mute:Q0,None:yy,Opacity:wy,Opaque:gy,Pause:H0,Play:V0,Progress:X0,Raised:_y,Red:oy,Replay:z0,Reset:xy,Script:Sy,Subtitles:Z0,Text:ry,Transparent:my,Uniform:Ty,Unmute:J0,White:ny,Window:py,Yellow:cy,default:Nk}),Ay="To protect children this content is only available between 8PM and 6AM.",Dy="To protect children this content is only available between 10PM and 5AM.",ky="This commercial content is not available.",Iy="This content is not available anymore.",Py="This content is not available outside Switzerland.",Ly="This content is not available due to legal restrictions.",Oy="This content is not available yet.",Ry="This content is not available.",Uk={AGERATING12:Ay,AGERATING18:Dy,COMMERCIAL:ky,ENDDATE:Iy,GEOBLOCK:Py,LEGAL:Ly,STARTDATE:Oy,UNKNOWN:Ry},Fk=Object.freeze({__proto__:null,AGERATING12:Ay,AGERATING18:Dy,COMMERCIAL:ky,ENDDATE:Iy,GEOBLOCK:Py,LEGAL:Ly,STARTDATE:Oy,UNKNOWN:Ry,default:Uk});De.addLanguage("en",$e($e({},Bk),Fk));var My="Lecture",Ny="Pause",By="Revoir",Uy="Durée",Fy="EN DIRECT",$y="Chargé",jy="Progression",qy="Plein écran",Vy="Mettre en sourdine",Hy="Activer le son",zy="Sous-titres",Gy="Sous-titres transcrits",Wy="Chapitres",Ky="Descriptions",Xy="Fermer",Yy="Texte",Qy="Blanc",Jy="Noir",Zy="Rouge",e_="Vert",t_="Bleu",i_="Jaune",s_="Magenta",r_="Cyan",n_="Arrière-plan",a_="Fenêtre",o_="Transparent",u_="Opaque",l_="Aucun",c_="Élevé",d_="Enfoncé",h_="Uniforme",f_="Manuscrite",p_="Scripte",m_="Réinitialiser",g_="Terminé",y_="Couleur",__="Opacité",$k={"Audio Player":"Lecteur audio","Video Player":"Lecteur vidéo",Play:My,Pause:Ny,Replay:By,"Current Time":"Temps actuel",Duration:Uy,"Remaining Time":"Temps restant","Stream Type":"Type de flux",LIVE:Fy,"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:$y,Progress:jy,"Progress Bar":"Barre de progression","progress bar timing: currentTime={1} duration={2}":"{1} de {2}",Fullscreen:qy,"Exit Fullscreen":"Fenêtré",Mute:Vy,Unmute:Hy,"Playback Rate":"Vitesse de lecture",Subtitles:zy,"subtitles off":"Sous-titres désactivés",Captions:Gy,"captions off":"Sous-titres transcrits désactivés",Chapters:Wy,Descriptions:Ky,"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:Xy,"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:Yy,White:Qy,Black:Jy,Red:Zy,Green:e_,Blue:t_,Yellow:i_,Magenta:s_,Cyan:r_,Background:n_,Window:a_,Transparent:o_,"Semi-Transparent":"Semi-transparent",Opaque:u_,"Font Size":"Taille des caractères","Text Edge Style":"Style des contours du texte",None:l_,Raised:c_,Depressed:d_,Uniform:h_,"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:f_,Script:p_,"Small Caps":"Petites capitales",Reset:m_,"restore all settings to the default values":"Restaurer tous les paramètres aux valeurs par défaut",Done:g_,"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:y_,Opacity:__,"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"},jk=Object.freeze({__proto__:null,Background:n_,Black:Jy,Blue:t_,Captions:Gy,Casual:f_,Chapters:Wy,Close:Xy,Color:y_,Cyan:r_,Depressed:d_,Descriptions:Ky,Done:g_,Duration:Uy,Fullscreen:qy,Green:e_,LIVE:Fy,Loaded:$y,Magenta:s_,Mute:Vy,None:l_,Opacity:__,Opaque:u_,Pause:Ny,Play:My,Progress:jy,Raised:c_,Red:Zy,Replay:By,Reset:m_,Script:p_,Subtitles:zy,Text:Yy,Transparent:o_,Uniform:h_,Unmute:Hy,White:Qy,Window:a_,Yellow:i_,default:$k}),v_="Pour protéger les enfants, ce contenu est accessible entre 20h et 6h.",T_="Pour protéger les enfants, ce contenu est accessible entre 23h et 5h.",b_="Ce contenu n'est actuellement pas disponible.",S_="Ce contenu n'est plus disponible.",x_="La RTS ne dispose pas des droits de diffusion en dehors de la Suisse.",E_="Pour des raisons juridiques, ce contenu n'est pas disponible.",C_="Ce contenu n'est pas encore disponible. Veuillez réessayer plus tard.",w_="Ce contenu n'est actuellement pas disponible.",qk={AGERATING12:v_,AGERATING18:T_,COMMERCIAL:b_,ENDDATE:S_,GEOBLOCK:x_,LEGAL:E_,STARTDATE:C_,UNKNOWN:w_},Vk=Object.freeze({__proto__:null,AGERATING12:v_,AGERATING18:T_,COMMERCIAL:b_,ENDDATE:S_,GEOBLOCK:x_,LEGAL:E_,STARTDATE:C_,UNKNOWN:w_,default:qk});De.addLanguage("fr",$e($e({},jk),Vk));var A_="Play",D_="Pausa",k_="Replay",I_="Durata",P_="LIVE",L_="Caricato",O_="Stato",R_="Schermo intero",M_="Disattiva l’audio",N_="Attiva l’audio",B_="Sottotitoli",U_="Sottotitoli non udenti",F_="Capitolo",$_="Descrizioni",j_="Chiudi",q_="Testo",V_="Bianco",H_="Nero",z_="Rosso",G_="Verde",W_="Blu",K_="Giallo",X_="Magenta",Y_="Ciano",Q_="Sfondo",J_="Finestra",Z_="Trasparente",ev="Opaco",tv="Nessuno",iv="Uniforme",sv="Reinizializza",rv="Fatto",nv="Colore",av="Opacità",Hk={"Audio Player":"Lettore audio","Video Player":"Lettore video",Play:A_,Pause:D_,Replay:k_,"Current Time":"Orario attuale",Duration:I_,"Remaining Time":"Tempo rimanente","Stream Type":"Tipo di streaming",LIVE:P_,Loaded:L_,Progress:O_,"Progress Bar":"Barra di avanzamento","progress bar timing: currentTime={1} duration={2}":"{1} di {2}",Fullscreen:R_,"Exit Fullscreen":"Chiudi Schermo intero",Mute:M_,Unmute:N_,"Playback Rate":"Velocità di riproduzione",Subtitles:B_,"subtitles off":"Senza sottotitoli",Captions:U_,"captions off":"Senza sottotitoli non udenti",Chapters:F_,Descriptions:$_,"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:j_,"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:q_,White:V_,Black:H_,Red:z_,Green:G_,Blue:W_,Yellow:K_,Magenta:X_,Cyan:Y_,Background:Q_,Window:J_,Transparent:Z_,"Semi-Transparent":"Semi-Trasparente",Opaque:ev,"Font Size":"Dimensione dei caratteri","Text Edge Style":"Stile dei bordi del testo",None:tv,Uniform:iv,"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:sv,"restore all settings to the default values":"Ripristina i valori predefiniti per tutti i parametri",Done:rv,"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:nv,Opacity:av,"Text Background":"Sfondo testo","Caption Area Background":"Sfondo area sottotitoli","Skip forward {1} seconds":"Avanti {1} secondi","Skip backward {1} seconds":"Indietro {1} secondi"},zk=Object.freeze({__proto__:null,Background:Q_,Black:H_,Blue:W_,Captions:U_,Chapters:F_,Close:j_,Color:nv,Cyan:Y_,Descriptions:$_,Done:rv,Duration:I_,Fullscreen:R_,Green:G_,LIVE:P_,Loaded:L_,Magenta:X_,Mute:M_,None:tv,Opacity:av,Opaque:ev,Pause:D_,Play:A_,Progress:O_,Red:z_,Replay:k_,Reset:sv,Subtitles:B_,Text:q_,Transparent:Z_,Uniform:iv,Unmute:N_,White:V_,Window:J_,Yellow:K_,default:Hk}),ov="Per proteggere i bambini, questo media è disponibile solo fra le 20 e le 6.",uv="Per proteggere i bambini, questo media è disponibile solo fra le 23 le 5.",lv="Questo contenuto commerciale non è disponibile.",cv="Questo media non è più disponibile.",dv="Questo media non è disponibile fuori dalla Svizzera.",hv="Il contenuto non è fruibile a causa di restrizioni legali.",fv="Il contenuto non è ancora disponibile. Per cortesia prova più tardi.",pv="Questo media non è disponibile.",Gk={AGERATING12:ov,AGERATING18:uv,COMMERCIAL:lv,ENDDATE:cv,GEOBLOCK:dv,LEGAL:hv,STARTDATE:fv,UNKNOWN:pv},Wk=Object.freeze({__proto__:null,AGERATING12:ov,AGERATING18:uv,COMMERCIAL:lv,ENDDATE:cv,GEOBLOCK:dv,LEGAL:hv,STARTDATE:fv,UNKNOWN:pv,default:Gk});De.addLanguage("it",$e($e({},zk),Wk));var mv="Laschar ir",gv="Pausa",yv="Mussar danovamain",_v="Durada",vv="LIVE",Tv="Chargià",bv="Progress",Sv="Entir visur",xv="Senza tun",Ev="Cun tun",Cv="Suttitels",wv="Suttitels",Av="Chapitels",Dv="Descripziuns",kv="Serrar",Iv="Text",Pv="Alv",Lv="Nair",Ov="Cotschn",Rv="Verd",Mv="Blau",Nv="Mellen",Bv="Magenta",Uv="Cyan",Fv="Fund",$v="Fanestra",jv="Transparent",qv="Betg transparent",Vv="Nagin",Hv="Auzà",zv="Sbassà",Gv="Uniform",Wv="Sumbriva",Kv="Casual",Xv="Script",Yv="Da nov",Qv="Fatg",Jv="Per proteger uffants, è quest cuntegn disponibel mo tranter las 20.00 e las 06.00.",Zv="Per proteger uffants, è quest cuntegn disponibel mo tranter las 23.00 e las 05.00.",eT="Quest medium commerzial n'è betg disponibel.",tT="Quest cuntegn n'è betg pli disponibel.",iT="Quest cuntegn n'è betg disponibel ordaifer la Svizra.",sT="Quest cuntegn n'è betg disponibel perquai ch'el è scadì.",rT="Quest cuntegn n'è betg anc disponibel. Empruvai pli tard.",nT="Quest cuntegn n'è betg disponibel.",Kk={"Audio Player":"Audio-Player","Video Player":"Video-Player",Play:mv,Pause:gv,Replay:yv,"Current Time":"Temp actual",Duration:_v,"Remaining Time":"Temp restant","Stream Type":"Tip dal stream",LIVE:vv,Loaded:Tv,Progress:bv,"Progress Bar":"Bar da progessiun","progress bar timing: currentTime={1} duration={2}":"{1} da {2}",Fullscreen:Sv,"Non-Fullscreen":"Betg entir visur",Mute:xv,Unmute:Ev,"Playback Rate":"Tempo ",Subtitles:Cv,"subtitles off":"senza suttitels",Captions:wv,"captions off":"senza suttitels",Chapters:Av,Descriptions:Dv,"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:kv,"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:Iv,White:Pv,Black:Lv,Red:Ov,Green:Rv,Blue:Mv,Yellow:Nv,Magenta:Bv,Cyan:Uv,Background:Fv,Window:$v,Transparent:jv,"Semi-Transparent":"Mez transparent",Opaque:qv,"Font Size":"Grandezza dal text","Text Edge Style":"Stil dal text",None:Vv,Raised:Hv,Depressed:zv,Uniform:Gv,Dropshadow:Wv,"Font Family":"Scrittira","Proportional Sans-Serif":"Proportionale Sans-Serif","Monospace Sans-Serif":"Monospace Sans-Serif","Proportional Serif":"Proportionale Serif","Monospace Serif":"Monospace Serif",Casual:Kv,Script:Xv,"Small Caps":"Bustabs pitschens",Reset:Yv,"restore all settings to the default values":"Enavos tar las opziuns da standard",Done:Qv,"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:Jv,AGERATING18:Zv,COMMERCIAL:eT,ENDDATE:tT,GEOBLOCK:iT,LEGAL:sT,STARTDATE:rT,UNKNOWN:nT},Xk=Object.freeze({__proto__:null,AGERATING12:Jv,AGERATING18:Zv,Background:Fv,Black:Lv,Blue:Mv,COMMERCIAL:eT,Captions:wv,Casual:Kv,Chapters:Av,Close:kv,Cyan:Uv,Depressed:zv,Descriptions:Dv,Done:Qv,Dropshadow:Wv,Duration:_v,ENDDATE:tT,Fullscreen:Sv,GEOBLOCK:iT,Green:Rv,LEGAL:sT,LIVE:vv,Loaded:Tv,Magenta:Bv,Mute:xv,None:Vv,Opaque:qv,Pause:gv,Play:mv,Progress:bv,Raised:Hv,Red:Ov,Replay:yv,Reset:Yv,STARTDATE:rT,Script:Xv,Subtitles:Cv,Text:Iv,Transparent:jv,UNKNOWN:nT,Uniform:Gv,Unmute:Ev,White:Pv,Window:$v,Yellow:Nv,default:Kk});De.addLanguage("rm",$e({},Xk));const Yk=["url","mimeType","keySystems"],Qk=["src"];class Z{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&&Z.createTextTrack(e,i).then(a=>{n.forEach(o=>{Z.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}){Z.addRemoteTextTracks(e,t.subtitles),Z.addChapters(e,t.urn,t.chapters),Z.addBlockedSegments(e,t.blockedSegments),Z.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)&&Z.createTextTrack(e,r).then(a=>{i.forEach(o=>{t===o.fullLengthUrn&&Z.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)&&Z.createTextTrack(e,i).then(n=>{t.forEach(a=>{Z.addTextTrackCue(n,a)}),e.textTracks().addTrack(n)})}static blockingReason(e,t){if(!t.mediaData.blockReason)return;const i=e.localize(t.mediaData.blockReason);return Z.error(e,{code:MediaError.MEDIA_ERR_ABORTED,message:i,metadata:{errorType:t.mediaData.blockReason,src:t}}),!0}static composeAkamaiResources(e=[]){return ls(function*(){return Hi.hasToken(e)?Hi.tokenizeSources(e):Promise.resolve(e)})()}static composeKeySystemsResources(e=[]){return zr.hasDrm(e),e.map(t=>$e($e({},t),zr.buildKeySystems(t.drmList)))}static composeMainResources(e){return Z.composeAkamaiResources(Z.composeKeySystemsResources(Z.filterIncompatibleResources(e.getMainResources())))}static composeSrcMediaData({mediaData:e,disableTrackers:t},i){const r=De.obj.merge(i,e),{url:n,mimeType:a,keySystems:o}=r,l=Kh(r,Yk);return{src:n,type:a,keySystems:o,disableTrackers:t,mediaData:l}}static createTextTrack(e,t){return new Promise(i=>{setTimeout(()=>{i(new De.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 Xh(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 Z.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=Z.getBlockedSegment(e);return i&&t>=i.startTime&&tr===t)||e[0]}static getSrcMediaObj(e,t){return ls(function*(){const{src:i}=t,r=Kh(t,Qk),n=yield Z.getMediaComposition(i,Z.dataProvider(e)),a=yield Z.composeMainResources(n),o=Z.getMediaData(a);return Z.composeSrcMediaData(r,o)})()}static handleCurrentTime(e,t){const i=Z.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}=Z.getBlockedSegmentByTime(e,t)||{};return Number.isFinite(i)?i:t}static handleSetSource(e,t,i){return ls(function*(){try{const r=yield Z.getSrcMediaObj(e,t);return Z.srgAnalytics(e),Z.updateTitleBar(e,r),Z.updatePoster(e,r),Z.blockingReason(e,r)?void 0:(Z.addTextTracks(e,r),i(null,r))}catch(r){return Z.dataProviderError(e,r)?void 0:i(r)}})()}static srgAnalytics(e){if(e.options().trackers.srgAnalytics!==!1&&!e.options().trackers.srgAnalytics){const t=new Ri(e,{debug:e.debug(),playerVersion:De.VERSION.pillarbox,tagCommanderScriptURL:e.options().srgOptions.tagCommanderScriptURL});e.options({trackers:{srgAnalytics:t}})}}static updatePoster(e,t,i=Dk){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 Z.cuechangeEventProxy(e),{currentTime:t=>Z.handleCurrentTime(e,t),setCurrentTime:t=>Z.handleSetCurrentTime(e,t),setSource:function(){var t=ls(function*(i,r){return Z.handleSetSource(e,i,r)});return function(r,n){return t.apply(this,arguments)}}()}}}De.use("srgssr/urn",Z.middleware);De.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 Jk={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},aT=s=>(...e)=>({_$litDirective$:s,values:e});class Zk{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 Da extends Zk{constructor(e){if(super(e),this.it=Pe,e.type!==Jk.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===Pe||e==null)return this._t=void 0,this.it=e;if(e===Gi)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:[]}}}Da.directiveName="unsafeHTML",Da.resultType=1;const lI=aT(Da);var Xr,Ku,Yr;class Wu extends ms{constructor(){super();pe(this,Xr);pe(this,Yr,t=>{t.preventDefault();const i=new URL(`${window.location.origin}/${this.href}`),r=Object.fromEntries(i.searchParams.entries());Fo.navigateTo(i.pathname,r)});Fo.addEventListener("routechanged",()=>{je(this,Xr,Ku).call(this)})}connectedCallback(){super.connectedCallback(),je(this,Xr,Ku).call(this),this.addEventListener("click",F(this,Yr))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("click",F(this,Yr))}render(){return df`
+
+
+
+ `}}Xr=new WeakSet,Ku=function(){const t=new URL(`${window.location.origin}/${this.href}`);this.selected=Fo.isActiveRoute(t.pathname)},Yr=new WeakMap,Se(Wu,"properties",{href:{type:String},title:{type:String},selected:{type:Boolean,state:!0}}),Se(Wu,"styles",[ff,V2]);customElements.define("route-link",Wu);const eI=`
+
+
+`,tI=""+new URL("srgssr-logo-DTU79MZS.png",import.meta.url).href;/**
+ * @license
+ * Copyright 2017 Google LLC
+ * SPDX-License-Identifier: BSD-3-Clause
+ */class Xu extends Da{}Xu.directiveName="unsafeSVG",Xu.resultType=2;const iI=aT(Xu),sI="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 oT extends ms{render(){return df`
+
+
+
+ Pillarbox
+
+
+ `}}Se(oT,"styles",[ff,Oa(sI)]);customElements.define("core-demo-header",oT);export{Z as S,V2 as a,Fo as b,Jk as c,aI as d,aT as e,ni as g,Zk as i,lI as o,De as p,Oa as r,ms as s,ff as t,L as v,Gi as w,df as x};
+//# sourceMappingURL=core-demo-header-component-DMYgftkn.js.map
diff --git a/pr-preview/pr-39/assets/core-demo-header-component-DMYgftkn.js.map b/pr-preview/pr-39/assets/core-demo-header-component-DMYgftkn.js.map
new file mode 100644
index 0000000..184de17
--- /dev/null
+++ b/pr-preview/pr-39/assets/core-demo-header-component-DMYgftkn.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"core-demo-header-component-DMYgftkn.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/keycode/index.js","../../node_modules/safe-json-parse/tuple.js","../../node_modules/@babel/runtime/helpers/esm/extends.js","../../node_modules/is-function/index.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/url-toolkit/src/url-toolkit.js","../../node_modules/@videojs/vhs-utils/es/resolve-url.js","../../node_modules/m3u8-parser/node_modules/@videojs/vhs-utils/es/stream.js","../../node_modules/m3u8-parser/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/@videojs/vhs-utils/es/decode-b64-to-uint8-array.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=Symbol.for(\"lit-noChange\"),T=Symbol.for(\"lit-nothing\"),A=new WeakMap,E=r.createTreeWalker(r,129);function C(t,i){if(!Array.isArray(t)||!t.hasOwnProperty(\"raw\"))throw Error(\"invalid template strings array\");return void 0!==s?s.createHTML(i):i}const P=(t,i)=>{const s=t.length-1,o=[];let r,l=2===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[C(t,l+(t[s]||\">\")+(2===i?\" \":\"\")),o]};class V{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]=P(t,s);if(this.el=V.createElement(f,n),E.currentNode=this.el.content,2===s){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(r=E.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=T}_$AI(t,i=this,s,e){const h=this.strings;let o=!1;if(void 0===h)t=N(this,t,i,0),o=!c(t)||t!==this._$AH&&t!==w,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 M(i.insertBefore(l(),t),t,void 0,s??{})}return h._$AI(t),h};export{z as _$LH,x as html,w as noChange,T as nothing,j 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 i}from\"lit-html\";export*from\"lit-html\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */class s 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 i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=e(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return i}}s._$litElement$=!0,s[(\"finalized\",\"finalized\")]=!0,globalThis.litElementHydrateSupport?.({LitElement:s});const r=globalThis.litElementPolyfillSupport;r?.({LitElement:s});const o={_$AK:(t,e,i)=>{t._$AK(e,i)},_$AL:t=>t._$AL};(globalThis.litElementVersions??=[]).push(\"4.0.5\");export{s 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 // /**/..//
/ -> {/..//
/,/**//
/}\n // //