@byomakase/omakase-player 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -44,7 +44,7 @@ ${Gl(r)}`)}),e.join(`
44
44
  `)}function Em(i){let e=0;return i.forEach(t=>{t.duration>e&&(e=t.duration)}),e}function km(i){const e=[];return i.forEach(t=>{e.push(xm(t))}),e.join(`
45
45
 
46
46
  `)}function xm(i){const e=[];i.identifier&&e.push(i.identifier);const t=Aa(i.start),r=Aa(i.end),s=i.styles?`${i.styles}`:"";return e.push(`${t} --> ${r} ${s}`),e.push(i.text),e.join(`
47
- `)}function Aa(i){const e=(i%1).toFixed(3);i=Math.round(i-e);const t=Math.floor(i/3600),r=Math.floor((i-t*3600)/60),s=i-t*3600-r*60;return`${`${_r(t,2)}:`}${_r(r,2)}:${_r(s,2)}.${_r(e*1e3,3)}`}var Pm={hlsSegment:Sm,hlsSegmentPlaylist:Tm};const Am=Rl.parse,Mm=vm.compile,Om=Nl.segment,Lm=Pm;var Rm={parse:Am,compile:Mm,segment:Om,hls:Lm};class Cn{constructor(e,t){this.cues=new Map,this.cuesKeysSorted=[],this.url=e,this.axiosConfig=t}fetch(){return tr(am(this.getUrl(),this.axiosConfig)).pipe(ke(e=>{let t=e.data;try{return Rm.parse(t,{strict:!0,meta:!0}).cues.forEach(s=>{let n=this.mapCue(s);this.cues.set(n.startTime,n),this.cuesKeysSorted.push(n.startTime)}),this.cuesKeysSorted.sort((s,n)=>s-n),!0}catch(r){return console.error(r),!1}}))}getUrl(){return this.url}hasCues(){return this.cues&&this.cues.size>0}findCue(e){let t=this.findCues(e,e);if(t&&t.length===1)return t[0]}findCues(e,t){let r=this.findCueIndex(e),s=this.findCueIndex(t);return s===-1?[]:this.cuesKeysSorted.slice(r,s+1).map(n=>this.cues.get(n))}getCues(){return[...this.cues.values()]}findCueIndex(e){let t=0,r=this.cuesKeysSorted.length-1;for(;t<=r;){const s=Math.floor((t+r)/2);if(this.cuesKeysSorted[s]===e)return s;this.cuesKeysSorted[s]<e?t=s+1:r=s-1}return r===-1&&(r=0),r}}class En extends Cn{constructor(e,t){super(e,t)}static create(e,t){let r=new En(e,t);return r.fetch().pipe(ke(s=>r))}mapCue(e){return{id:e.identifier,startTime:new Z(e.start).toDecimalPlaces(3).toNumber(),endTime:new Z(e.end).toDecimalPlaces(3).toNumber(),text:e.text}}}const Ma={listening:!0,style:{height:20,fill:"rgba(255,73,145)",opacity:1,visible:!0}};class Im extends et{constructor(e,t){super({...Ma,...e,style:{...Ma.style,...e.style}}),this.textTrackCue=this.config.textTrackCue,this.x=this.config.x,this.width=this.config.width,this.listening=this.config.listening,this.subtitlesLane=t,this.subtitlesLane.onSettleLayout$.pipe(k(this.onDestroy$)).subscribe(()=>{let r=this.subtitlesLane.resolveItemHorizontalMeasurement(this.getTextTrackCue());this.setHorizontalMeasurement(r)})}createCanvasNode(){return this.group=new M.Group({x:this.x,y:0,width:this.width,height:this.style.height,visible:this.style.visible,listening:this.listening}),this.backgroundRect=new M.Rect({x:0,y:0,width:this.group.width(),height:this.group.height(),fill:this.style.fill,opacity:this.style.opacity,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1,hitStrokeWidth:0}),this.group.add(this.backgroundRect),this.group}onMeasurementsChange(){this.backgroundRect.size(this.group.getSize())}setPosition(e){this.x=e.x,this.isInitialized()&&this.group.position({x:this.x,y:0})}getPosition(){return this.group.getPosition()}getDimension(){return this.group.getSize()}getRect(){return{...this.getPosition(),...this.getDimension()}}getHorizontalMeasurement(){return{x:this.x,width:this.width}}setHorizontalMeasurement(e){this.x=e.x,this.width=e.width,this.isInitialized()&&this.group.setAttrs({x:this.x,width:this.width}),this.onMeasurementsChange()}setVisible(e){this.style={visible:e},this.isInitialized()&&this.group.visible(e)}getTextTrackCue(){return this.textTrackCue}setTextTrackCue(e){this.textTrackCue=e}compareTo(e){return this.textTrackCue&&e&&this.getTextTrackCue().id===e.getTextTrackCue().id&&this.getTextTrackCue().startTime===e.getTextTrackCue().startTime&&this.getTextTrackCue().endTime===e.getTextTrackCue().endTime?0:-1}destroy(){this.textTrackCue=void 0,this.subtitlesLane=void 0,super.destroy()}}const Nm={...rr,height:40,paddingTop:0,paddingBottom:0,subtitlesLaneItemOpacity:.9,subtitlesLaneItemFill:"rgba(255,73,145)"};class qs extends sr{constructor(e){super({...e,style:{...Nm,...e.style}}),this.subtitlesLaneItemsMap=new Map,this.onSettleLayout$=new V,this._subtitlesVttUrl=this.config.subtitlesVttUrl}createCanvasNode(){return super.createCanvasNode(),this.timecodedGroup=new M.Group({...this.timelinePosition,width:this.timeline.getTimecodedGroupDimension().width,height:this.bodyGroup.height()}),this.timecodedEventCatcher=wi.createEventCatcher({width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.subtitlesLaneItemsGroup=new M.Group({...F.POSITION_TOP_LEFT,y:this.style.paddingTop,width:this.timecodedGroup.width(),height:this.timecodedGroup.height()-(this.style.paddingTop+this.style.paddingBottom)}),this.timecodedGroup.add(this.timecodedEventCatcher),this.timecodedGroup.add(this.subtitlesLaneItemsGroup),this.timeline.addToTimecodedSubtitlesGroup(this.timecodedGroup),this.bodyGroup}settleLayout(){super.settleLayout(),this.timecodedGroup.setAttrs({...this.timelinePosition});let e=this.timeline.getTimecodedGroupHorizontalMeasurement();[this.timecodedGroup,this.timecodedEventCatcher,this.subtitlesLaneItemsGroup].forEach(t=>{t.width(e.width)}),this.onSettleLayout$.next()}afterCanvasNodeInit(){super.afterCanvasNodeInit(),this.fetchAndCreateSubtitles()}clearContent(){this.subtitlesVttFile=void 0,this.clearItems()}clearItems(){this.subtitlesLaneItemsMap.forEach(e=>e.destroy()),this.subtitlesLaneItemsMap.clear(),this.subtitlesLaneItemsGroup.destroyChildren()}createEntities(){if(!this.isVttLoaded())return;this.clearItems(),this.subtitlesVttFile.getCues().forEach(t=>{let r=this.resolveItemHorizontalMeasurement(t),s=new Im({...r,textTrackCue:t,style:{height:this.subtitlesLaneItemsGroup.height(),fill:this.style.subtitlesLaneItemFill,opacity:this.style.subtitlesLaneItemOpacity}},this);this.subtitlesLaneItemsMap.set(t.startTime,s),this.subtitlesLaneItemsGroup.add(s.initCanvasNode())})}resolveItemHorizontalMeasurement(e){let t=this.timeline.constrainTimelinePosition(this.timeline.timeToTimelinePosition(e.startTime)),r=this.timeline.constrainTimelinePosition(this.timeline.timeToTimelinePosition(e.endTime));return{x:t,width:r-t}}fetchAndCreateSubtitles(){this.fetchSubtitlesVttFile(this._subtitlesVttUrl).pipe($e(1)).subscribe(e=>{this.subtitlesVttFile=e,this.createEntities()})}fetchSubtitlesVttFile(e){return e?En.create(e).pipe(ke(t=>t),yi((t,r)=>Se(void 0))):Se(void 0)}isVttLoaded(){return!!this.subtitlesVttFile}get subtitlesVttUrl(){return this._subtitlesVttUrl}set subtitlesVttUrl(e){this._subtitlesVttUrl=e,this.clearContent(),this.fetchAndCreateSubtitles()}}const Dm={listening:!1,style:{...F.POSITION_TOP_LEFT,...F.DIMENSION_ZERO,stroke:"rgba(255,73,145)",strokeWidth:5,visible:!1}};class Ys extends et{constructor(e){super(_i(e,Dm)),this.onClick$=new V,this.onMouseOver$=new V,this.onMouseMove$=new V,this.onMouseOut$=new V,this.onMouseLeave$=new V,this.listening=this.config.listening}createCanvasNode(){return this.group=new M.Group({x:this.style.x,y:this.style.y,width:this.style.width,height:this.style.height,visible:this.style.visible,listening:this.listening}),this.backgroundRect=new M.Rect({x:0,y:0,width:this.group.width(),height:this.group.height(),strokeWidth:this.style.strokeWidth,stroke:this.style.stroke}),this.group.add(this.backgroundRect),this.group}afterCanvasNodeInit(){this.group.on("click",e=>{this.onClick$.next({thumbnail:this})}),this.group.on("mouseover",e=>{this.onMouseOver$.next({thumbnail:this})}),this.group.on("mousemove",e=>{this.onMouseMove$.next({thumbnail:this})}),this.group.on("mouseout",e=>{this.onMouseOut$.next({thumbnail:this})}),this.group.on("mouseleave",e=>{this.onMouseLeave$.next({thumbnail:this})})}destroy(){this.thumbnailVttCue=void 0;for(let t in this.group.eventListeners)this.group.removeEventListener(t);let e=[this.onClick$,this.onMouseOver$,this.onMouseMove$,this.onMouseOut$,this.onMouseLeave$];Vt(...e),bi(...e),super.destroy()}onMeasurementsChange(){this.backgroundRect.size(this.group.getSize())}setImage(e){this.image&&this.image.destroy(),this.image=e,this.style={width:e.width(),height:e.height()},this.group.setAttrs({...this.image.getSize()}),this.backgroundRect.setAttrs({...this.image.getSize()}),this.group.add(this.image)}setVisible(e){this.style={visible:e},this.isInitialized()&&this.group.visible(e)}setPosition(e){this.style={...e},this.isInitialized()&&this.group.position(e)}setVisibleAndX(e,t){this.style={visible:e,x:t},this.isInitialized()&&this.group.setAttrs({visible:e,x:t})}getPosition(){return this.group.getPosition()}getDimension(){return this.group.getSize()}setDimension(e){this.style={...e},this.isInitialized()&&this.group.size(e),this.onMeasurementsChange()}getRect(){return{...this.getPosition(),...this.getDimension()}}getThumbnailVttCue(){return this.thumbnailVttCue}setThumbnailVttCue(e){this.thumbnailVttCue=e}getImage(){return this.image}compareTo(e){return this.thumbnailVttCue&&e&&this.thumbnailVttCue.url===e.thumbnailVttCue.url?0:-1}}class ls extends Cn{constructor(e,t){super(e,t)}static create(e,t){let r=new ls(e,t);return r.fetch().pipe(ke(s=>r))}mapCue(e){return{id:e.identifier,startTime:new Z(e.start).toDecimalPlaces(3).toNumber(),endTime:new Z(e.end).toDecimalPlaces(3).toNumber(),text:e.text,url:this.resolveThumbnailUrl(e)}}resolveThumbnailUrl(e){return this.isUrlAbsolute(e.text)?e.text:this.createThumbnailUrlFromRelativeUrl(e.text)}createThumbnailUrlFromRelativeUrl(e){return this.url.lastIndexOf("/")>2?`${this.url.substring(0,this.url.lastIndexOf("/"))}/${e}`:e}isUrlAbsolute(e){return/^(http(s):\/\/.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/.test(e)}}class ct{static createKonvaImage(e){return new re(t=>{M.Image.fromURL(e,r=>{t.next(r),t.complete()},r=>{console.error(r),t.error(r)})})}static createKonvaImageSizedByWidth(e,t){return ct.createKonvaImage(e).pipe(ke(r=>(r.setAttrs({width:t,height:ct.calculateProportionalHeight(t,r)}),r)))}static createKonvaImageSizedByHeight(e,t){return ct.createKonvaImage(e).pipe(ke(r=>(r.setAttrs({width:ct.calculateProportionalWidth(t,r),height:t}),r)))}static calculateProportionalHeight(e,t){return e*t.getAttrs().image.naturalHeight/t.getAttrs().image.naturalWidth}static calculateProportionalWidth(e,t){return e*t.getAttrs().image.naturalWidth/t.getAttrs().image.naturalHeight}}const Gm={...rr,thumbnailHeight:40,thumbnailStroke:"rgba(121,0,255,0.9)",thumbnailStrokeWidth:0,thumbnailHoverScale:1.5,thumbnailHoverStroke:"rgba(0,255,188,0.9)",thumbnailHoverStrokeWidth:5};class Ks extends sr{constructor(e){super({...e,style:{...Gm,...e.style}}),this.thumbnailsMap=new Map,this.thumbnailsVisibleSet=new Set,this.onSettleLayout$=new V,this.eventStreamBreaker$=new V,this.onClick$=new V,this._thumbnailVttUrl=this.config.thumbnailVttUrl,this._axiosConfig=this.config.axiosConfig}createCanvasNode(){return super.createCanvasNode(),this.timecodedGroup=new M.Group({...this.timelinePosition,width:this.timeline.getTimecodedGroupDimension().width,height:this.bodyGroup.height()}),this.timecodedEventCatcher=wi.createEventCatcher({width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.thumbnailsGroup=new M.Group({x:0,y:this.style.height/2-this.style.thumbnailHeight/2,width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.timecodedGroup.add(this.timecodedEventCatcher),this.timecodedGroup.add(this.thumbnailsGroup),this.timeline.addToTimecodedThumbnailsGroup(this.timecodedGroup),this.thumbnailHover=new Ys({style:{visible:!1,stroke:this.style.thumbnailHoverStroke,strokeWidth:this.style.thumbnailHoverStrokeWidth}}),this.timeline.addToTimecodedSurfaceGroup(this.thumbnailHover.initCanvasNode()),this.bodyGroup}settleLayout(){super.settleLayout(),this.timecodedGroup.setAttrs({...this.timelinePosition});let e=this.timeline.getTimecodedGroupHorizontalMeasurement();[this.timecodedGroup,this.timecodedEventCatcher,this.thumbnailsGroup].forEach(t=>{t.width(e.width)}),this.onSettleLayout$.next()}afterCanvasNodeInit(){super.afterCanvasNodeInit(),this.fetchAndCreateThumbnails(),this.onSettleLayout$.pipe(k(this.onDestroy$)).subscribe(()=>{this.hideThumbnailHover(),this.adjustThumbnails()}),this.onSettleLayout$.pipe(k(this.onDestroy$)).pipe(Ho(100)).subscribe(()=>{this.createAndAdjustThumbnails()}),this.timecodedGroup.on("mouseout mouseleave",e=>{this.hideThumbnailHover()})}onMeasurementsChange(){super.onMeasurementsChange(),this.hideThumbnailHover(),this.createAndAdjustThumbnails()}destroy(){super.destroy(),this.timecodedGroup.destroy(),this.thumbnailHover.destroy(),this.fireEventStreamBreaker()}clearContent(){this.fireEventStreamBreaker(),this.thumbnailVttFile=void 0,this.clearItems()}clearItems(){this.thumbnailsMap.forEach(e=>e.destroy()),this.thumbnailsMap.clear(),this.thumbnailsVisibleSet.clear(),this.thumbnailsGroup.destroyChildren()}fireEventStreamBreaker(){Ge(this.eventStreamBreaker$),this.eventStreamBreaker$=new V}createAndAdjustThumbnails(){this.isVttLoaded()&&(this.resolveVisibleTimestamps(),this.thumbnailVttFile.getCues().forEach(e=>{let t=this.timeline.timeToTimelinePosition(e.startTime),r=this.thumbnailsVisibleSet.has(e.startTime);if(this.timeline.constrainTimelinePosition(t)===t)if(this.thumbnailsMap.has(e.startTime)){let s=this.thumbnailsMap.get(e.startTime);s&&s.setVisibleAndX(r,t)}else r&&(this.thumbnailsMap.set(e.startTime,null),ct.createKonvaImageSizedByHeight(e.url,this.style.thumbnailHeight).subscribe(s=>{let n=this.thumbnailsVisibleSet.has(e.startTime),a=this.createThumbnail(e,s,n);this.thumbnailsMap.set(e.startTime,a),this.thumbnailsGroup.add(a.getCanvasNode())}))}))}adjustThumbnails(){this.isVttLoaded()&&(this.resolveVisibleTimestamps(),this.thumbnailsMap.forEach(e=>{if(e){let t=this.timeline.timeToTimelinePosition(e.getThumbnailVttCue().startTime),r=this.thumbnailsVisibleSet.has(e.getThumbnailVttCue().startTime);e.setVisibleAndX(r,t)}}))}resolveVisibleTimestamps(){let e;this.thumbnailVttFile.getCues().forEach(r=>{let s=this.timeline.timeToTimelinePosition(r.startTime);this.timeline.constrainTimelinePosition(s)===s&&((e?s>=e:!0)?(e=s+this.thumbnailWidth,this.thumbnailsVisibleSet.add(r.startTime)):this.thumbnailsVisibleSet.delete(r.startTime))})}createThumbnail(e,t,r){let s=this.timeline.timeToTimelinePosition(e.startTime),n=new Ys({listening:!0,style:{x:s,y:0,visible:r,stroke:this.style.thumbnailStroke,strokeWidth:this.style.thumbnailStrokeWidth}});return n.setThumbnailVttCue(e),n.initCanvasNode(),n.setImage(t),n.onClick$.pipe(k(this.eventStreamBreaker$)).subscribe(a=>{this.onClick$.next(a)}),n.onMouseOver$.pipe(k(this.eventStreamBreaker$)).subscribe(a=>{this.showThumbnailHover(a.thumbnail)}),n.onMouseMove$.pipe(k(this.eventStreamBreaker$)).subscribe(a=>{this.showThumbnailHover(a.thumbnail)}),n.onMouseOut$.pipe(k(this.eventStreamBreaker$)).subscribe(a=>{this.hideThumbnailHover()}),n.onMouseLeave$.pipe(k(this.eventStreamBreaker$)).subscribe(a=>{this.hideThumbnailHover()}),n}showThumbnailHover(e){if(this.thumbnailHover.setVisible(!0),this.thumbnailHover.compareTo(e)===0){let t=this.resolveThumbnailHoverPosition(e);this.thumbnailHover.setPosition(t),this.thumbnailHover.setVisible(!0)}else ct.createKonvaImageSizedByWidth(e.getThumbnailVttCue().url,e.getImage().width()*this.style.thumbnailHoverScale).subscribe(t=>{this.thumbnailHover.setDimension(t.getSize()),this.thumbnailHover.setImage(t),this.thumbnailHover.setPosition(this.resolveThumbnailHoverPosition(e)),this.thumbnailHover.getCanvasNode().moveToTop()})}hideThumbnailHover(){this.thumbnailHover&&this.thumbnailHover.style.visible&&this.thumbnailHover.setVisible(!1)}resolveThumbnailHoverPosition(e){let t=this.timeline.getTimecodedGroupRect(),r=this.thumbnailHover.getImage().getSize(),s=e.getPosition().x+e.getDimension().width/2-r.width/2,n=e.style.strokeWidth>0?e.style.strokeWidth/2:0;s=s-n<0?n:s+r.width+n>t.width?t.width-r.width-n:s;let h=this.getRect().y+this.thumbnailsGroup.y()+e.getDimension().height/2-this.thumbnailHover.getDimension().height/2;return{x:s,y:h}}fetchAndCreateThumbnails(){this.fetchThumbnailVttFile(this._thumbnailVttUrl,this._axiosConfig,this.style.thumbnailHeight).pipe($e(1)).subscribe(e=>{e&&(this.thumbnailVttFile=e.thumbnailVttFile,this.thumbnailWidth=e.thumbnailWidth,this.createAndAdjustThumbnails())})}fetchThumbnailVttFile(e,t,r){return e?ls.create(e,t).pipe(tc(s=>{let n=s.getCues()[0];return ct.createKonvaImageSizedByHeight(n.url,r).pipe(ke(a=>{let o=a.getSize().width;return{thumbnailVttFile:s,thumbnailWidth:o}}))}),yi((s,n)=>Se(void 0))):Se(void 0)}isVttLoaded(){return!!this.thumbnailVttFile&&!!this.thumbnailWidth}getThumbnailVttFile(){return this.thumbnailVttFile}get thumbnailVttUrl(){return this._thumbnailVttUrl}set thumbnailVttUrl(e){this._thumbnailVttUrl=e,this.clearContent(),this.fetchAndCreateThumbnails()}}class kn extends Cn{constructor(e,t){super(e,t)}static create(e,t){let r=new kn(e,t);return r.fetch().pipe(ke(s=>r))}mapCue(e){let t=e.text.split(","),r=_e.coerce.number().min(-1).max(0).parse(t[0]),s=_e.coerce.number().min(0).max(1).parse(t[1]);return{id:e.identifier,startTime:new Z(e.start).toDecimalPlaces(3).toNumber(),endTime:new Z(e.end).toDecimalPlaces(3).toNumber(),text:e.text,minSample:r,maxSample:s}}}const Oa={listening:!1,style:{height:20,cornerRadius:20,opacity:1,visible:!0,maxSampleFillLinearGradientColorStops:[0,"red",.2,"yellow",1,"green"],minSampleFillLinearGradientColorStops:[0,"green",.8,"yellow",1,"red"]}};class Fm extends et{constructor(e){super({...Oa,...e,style:{...Oa.style,...e.style}}),this.audioVttCue=this.config.audioVttCue,this.x=this.config.x,this.width=this.config.width,this.listening=this.config.listening}createCanvasNode(){this.group=new M.Group({x:this.x,y:0,width:this.width,height:this.style.height,visible:this.style.visible,listening:this.listening});let e=this.style.height/2,t=this.resolveMaxSampleBarHeight(),r=this.resolveMinSampleBarHeight();return this.maxSampleBar=new M.Rect({x:0,width:this.group.width(),y:e-t,height:t,opacity:this.style.opacity,cornerRadius:[this.style.cornerRadius,this.style.cornerRadius,0,0],fillLinearGradientStartPoint:{x:0,y:-(e-t)},fillLinearGradientEndPoint:{x:0,y:t},fillLinearGradientColorStops:this.style.maxSampleFillLinearGradientColorStops,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1,hitStrokeWidth:0}),this.minSampleBar=new M.Rect({x:0,width:this.group.width(),y:e,height:r,opacity:this.style.opacity,cornerRadius:[0,0,this.style.cornerRadius,this.style.cornerRadius],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:e},fillLinearGradientColorStops:this.style.minSampleFillLinearGradientColorStops,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1,hitStrokeWidth:0}),this.group.add(this.maxSampleBar),this.group.add(this.minSampleBar),this.group}resolveMaxSampleBarHeight(){return new Z(this.audioVttCue.maxSample).mul(this.style.height/2).toDecimalPlaces(2).toNumber()}resolveMinSampleBarHeight(){return new Z(this.audioVttCue.minSample).abs().mul(this.style.height/2).toDecimalPlaces(2).toNumber()}setPosition(e){this.x=e.x,this.isInitialized()&&this.group.position({x:this.x,y:0})}getPosition(){return this.group.getPosition()}getDimension(){return this.group.getSize()}getRect(){return{...this.getPosition(),...this.getDimension()}}getAudioVttCue(){return this.audioVttCue}setAudioVttCue(e){this.audioVttCue=e;let t=this.resolveMaxSampleBarHeight(),r=this.resolveMinSampleBarHeight();this.minSampleBar.setAttrs({height:r}),this.maxSampleBar.setAttrs({y:this.style.height/2-t,height:t,fillLinearGradientStartPoint:{x:0,y:-(this.style.height/2-t)},fillLinearGradientEndPoint:{x:0,y:t}})}destroy(){this.audioVttCue=void 0,super.destroy()}}const Hm={...rr,height:40,paddingTop:0,paddingBottom:0,itemWidth:5,itemMinPadding:2,itemCornerRadius:5,maxSampleFillLinearGradientColorStops:[0,"red",.2,"yellow",1,"green"],minSampleFillLinearGradientColorStops:[0,"green",.8,"yellow",1,"red"]};class Fl extends sr{constructor(e){super({...e,style:{...Hm,...e.style}}),this.audioTrackLaneItemsMap=new Map,this.onSettleLayout$=new V,this._audioVttFileUrl=this.config.audioVttFileUrl}createCanvasNode(){return super.createCanvasNode(),this.timecodedGroup=new M.Group({...this.timelinePosition,width:this.timeline.getTimecodedGroupDimension().width,height:this.bodyGroup.height()}),this.timecodedEventCatcher=wi.createEventCatcher({width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.audioTrackLaneItemsGroup=new M.Group({...F.POSITION_TOP_LEFT,y:this.style.paddingTop,width:this.timecodedGroup.width(),height:this.timecodedGroup.height()-(this.style.paddingTop+this.style.paddingBottom)}),this.timecodedGroup.add(this.timecodedEventCatcher),this.timecodedGroup.add(this.audioTrackLaneItemsGroup),this.timeline.addToTimecodedAudioGroup(this.timecodedGroup),this.bodyGroup}settleLayout(){super.settleLayout(),this.timecodedGroup.setAttrs({...this.timelinePosition});let e=this.timeline.getTimecodedGroupHorizontalMeasurement();[this.timecodedGroup,this.timecodedEventCatcher,this.audioTrackLaneItemsGroup].forEach(t=>{t.width(e.width)}),this.onSettleLayout$.next()}afterCanvasNodeInit(){super.afterCanvasNodeInit(),this.fetchAndCreateAudioTrack(),this.onSettleLayout$.pipe(k(this.onDestroy$)).subscribe(()=>{this.settlePosition()}),Nu([this.onSettleLayout$,this.timeline.onScroll$]).pipe(k(this.onDestroy$),Ho(100)).subscribe(()=>{this.settleAll()})}clearContent(){this.audioVttFile=void 0,this.clearItems()}clearItems(){this.audioTrackLaneItemsMap.forEach(e=>e.destroy()),this.audioTrackLaneItemsMap.clear(),this.audioTrackLaneItemsGroup.destroyChildren()}getVisibleCues(){let e=this.timeline.getVisibleTimeRange();return this.audioVttFile.findCues(e.start,e.end)}createEntities(){if(!this.isVttLoaded())return;this.clearItems();let e=this.getVisibleCues(),t=this.timeline.getTimecodedContainerDimension().width;this.numOfInterpolations=new Z(t+this.style.itemMinPadding).div(this.style.itemWidth+this.style.itemMinPadding).floor().toNumber(),this.itemPadding=new Z(t-this.numOfInterpolations*this.style.itemWidth).div(this.numOfInterpolations-1).toNumber();let r=this.resolveNumOfCuesPerInterpolation(e.length),s=this.resolveCuesInterpolations(e,r);for(let n=0;n<this.numOfInterpolations;n++){let a=s.get(n),o=this.resolveInterpolatedItemPosition(n),h=new Fm({x:o,width:this.style.itemWidth,audioVttCue:a,style:{cornerRadius:this.style.itemCornerRadius,height:this.audioTrackLaneItemsGroup.height(),visible:!0,maxSampleFillLinearGradientColorStops:this.style.maxSampleFillLinearGradientColorStops,minSampleFillLinearGradientColorStops:this.style.minSampleFillLinearGradientColorStops}});this.audioTrackLaneItemsMap.set(n,h),this.audioTrackLaneItemsGroup.add(h.initCanvasNode())}}resolveNumOfCuesPerInterpolation(e){return new Z(e).div(this.numOfInterpolations).floor().toNumber()}resolveCuesInterpolations(e,t){let r=e.length-t*this.numOfInterpolations,s=new Map,n=0;for(let a=0;a<this.numOfInterpolations;a++){let o=t+(a<r?1:0),h=n;n=h+o;let l=e.slice(h,n),d=e[h],u=e[n-1],c=0,p=0;l.forEach(m=>{c+=m.minSample,p+=m.maxSample});let f={id:`${a}`,text:"",minSample:new Z(c).div(o).toDecimalPlaces(3).toNumber(),maxSample:new Z(p).div(o).toDecimalPlaces(3).toNumber(),startTime:d.startTime,endTime:u.endTime};s.set(a,f)}return s}settleAll(){if(!this.isVttLoaded()||this.audioTrackLaneItemsMap.size<1)return;let e=this.getVisibleCues(),t=this.resolveNumOfCuesPerInterpolation(e.length),r=this.resolveCuesInterpolations(e,t);for(let s=0;s<this.numOfInterpolations;s++){let n=r.get(s),a=this.audioTrackLaneItemsMap.get(s);a.setAudioVttCue(n),a.setPosition({x:this.resolveInterpolatedItemPosition(s)})}}resolveInterpolatedItemPosition(e){return Math.abs(this.timeline.getTimecodedGroupHorizontalMeasurement().x)+e*this.style.itemWidth+e*this.itemPadding}settlePosition(){if(!(!this.isVttLoaded()||this.audioTrackLaneItemsMap.size<1))for(let e=0;e<this.numOfInterpolations;e++){let t=this.audioTrackLaneItemsMap.get(e),r=this.timeline.timeToTimelinePosition(t.getAudioVttCue().startTime);t.setPosition({x:r})}}fetchAndCreateAudioTrack(){this.fetchAudioTrackVttFile(this._audioVttFileUrl).pipe($e(1)).subscribe(e=>{this.audioVttFile=e,this.createEntities()})}fetchAudioTrackVttFile(e){return e?kn.create(e).pipe(ke(t=>t),yi((t,r)=>Se(void 0))):Se(void 0)}isVttLoaded(){return!!this.audioVttFile}get audioVttFileUrl(){return this._audioVttFileUrl}set audioVttFileUrl(e){this._audioVttFileUrl=e,this.clearContent(),this.fetchAndCreateAudioTrack()}destroy(){this.audioTrackLaneItemsMap.forEach(e=>{e.destroy()}),this.audioVttFile=void 0,Ge(this.onSettleLayout$),super.destroy()}}function Js(i){if(i.from===i.to)return;let e=i.from<i.to,t=e?i.to-i.from:i.from-i.to,r=new M.Animation(s=>{let n=M.Easings.StrongEaseInOut(s.time,0,t,i.duration);if(n>=t)i.onUpdateHandler(s,i.to),r.stop(),i.onCompleteHandler&&(i.onCompleteHandler(s,i.to),r=null);else{let a=i.from+n*(e?1:-1);i.onUpdateHandler(s,a)}},i.layer);r.start()}const Bm={...F.POSITION_TOP_LEFT,width:0,zoomMax:1500,scrollStepNumberOfDivisions:10,style:{height:20,backgroundFill:"#000000",backgroundFillOpacity:.3,handleBarFill:"#01a6f0",handleBarOpacity:1,handleOpacity:1}};class $m extends et{constructor(e){super(_i(e,Bm)),this.onScroll$=new V,this.onZoom$=new V,this.x=this.config.x,this.y=this.config.y,this.width=this.config.width,this.zoomMax=this.config.zoomMax,this.scrollStepNumberOfDivisions=this.config.scrollStepNumberOfDivisions}createCanvasNode(){return this.group=new M.Group({x:this.x,y:this.y,width:this.width,height:this.style.height}),this.background=new M.Rect({...F.POSITION_TOP_LEFT,width:this.group.width(),height:this.style.height,fill:this.style.backgroundFill,opacity:this.style.backgroundFillOpacity}),this.handleGroup=new M.Group({...F.POSITION_TOP_LEFT,width:this.group.width(),height:this.style.height}),this.handleBar=new M.Rect({...F.POSITION_TOP_LEFT,width:this.handleGroup.width(),height:this.style.height,fill:this.style.handleBarFill,opacity:this.style.handleBarOpacity,draggable:!0}),this.leftZoomHandle=new M.Circle({...F.POSITION_TOP_LEFT,fill:this.style.handleBarFill,radius:this.style.height/2,y:this.style.height/2,opacity:this.style.handleOpacity,draggable:!0}),this.rightZoomHandle=new M.Circle({...F.POSITION_TOP_LEFT,fill:this.style.handleBarFill,radius:this.style.height/2,y:this.style.height/2,opacity:this.style.handleOpacity,draggable:!0}),this.handleGroup.add(this.background),this.handleGroup.add(this.handleBar),this.group.add(this.background),this.group.add(this.handleGroup),this.handleGroup.add(this.leftZoomHandle),this.handleGroup.add(this.rightZoomHandle),this.group}afterCanvasNodeInit(){this.styleAdapter.onChange$.pipe(k(this.onDestroy$),We(n=>!!n)).subscribe(n=>{this.onStyleChange()}),this.group.on("click",n=>{this.clickScrollTo(this.group.getRelativePointerPosition().x)}),this.handleBar.on("dragstart dragmove dragend",n=>{let a=this.handleBar.getPosition(),o=this.getConstrainedHandleBarX(a.x);this.handleBar.setAttrs({x:o,y:0}),this.syncLeftRightHandles(),this.handleBar.getRelativePointerPosition().x>=0&&this.handleBar.getRelativePointerPosition().x<=this.handleBar.width()&&this.onScroll$.next({scrollPercent:this.getScrollHandlePercent()})});let e={scaleX:1.5,scaleY:1.5,duration:.1},t={scaleX:1,scaleY:1,duration:.1};this.leftZoomHandle.on("mouseover",n=>{this.leftZoomHandle.to({...e}),it.cursor("ew-resize")}),this.leftZoomHandle.on("mouseout",n=>{this.leftZoomHandle.to({...t}),it.cursor("default")}),this.rightZoomHandle.on("mouseover",n=>{this.rightZoomHandle.to({...e}),it.cursor("ew-resize")}),this.rightZoomHandle.on("mouseout",n=>{this.rightZoomHandle.to({...t}),it.cursor("default")});let r=n=>{let a=n;return a<0?a=0:this.rightZoomHandle.x()-n<=this.minHandleBarWidth&&(a=this.rightZoomHandle.x()-this.minHandleBarWidth),a};this.leftZoomHandle.on("dragstart dragmove dragend",n=>{let a=this.leftZoomHandle.getPosition(),o=r(a.x);this.leftZoomHandle.setAttrs({x:o,y:this.style.height/2}),this.handleBar.setAttrs({x:o,width:this.rightZoomHandle.x()-o}),this.onZoom$.next({zoomPercent:this.getZoomPercent()})});let s=n=>{let a=n,o=this.group.width();return a>o?a=o:n-this.leftZoomHandle.x()<=this.minHandleBarWidth&&(a=this.leftZoomHandle.x()+this.minHandleBarWidth),a};this.rightZoomHandle.on("dragstart dragmove dragend",n=>{let a=this.rightZoomHandle.getPosition(),o=s(a.x);this.rightZoomHandle.setAttrs({x:o,y:this.style.height/2}),this.handleBar.setAttrs({width:o-this.leftZoomHandle.x()}),this.onZoom$.next({zoomPercent:this.getZoomPercent()})})}onMeasurementsChange(){this.group.width(this.width),this.background.width(this.group.width()),this.handleGroup.width(this.group.width()),this.minHandleBarWidth=this.calculateHandleBarWidthFromZoomRatioPercent(this.zoomMax)}onStyleChange(){this.group.setAttrs({height:this.style.height}),this.background.setAttrs({height:this.style.height,fill:this.style.backgroundFill,opacity:this.style.backgroundFillOpacity}),this.handleGroup.setAttrs({height:this.style.height}),this.handleBar.setAttrs({height:this.style.height,fill:this.style.handleBarFill,opacity:this.style.handleBarOpacity}),this.leftZoomHandle.setAttrs({fill:this.style.handleBarFill,radius:this.style.height/2,y:this.style.height/2,opacity:this.style.handleOpacity}),this.rightZoomHandle.setAttrs({fill:this.style.handleBarFill,radius:this.style.height/2,y:this.style.height/2,opacity:this.style.handleOpacity})}getScrollHandleMaxX(){return this.group.width()-this.handleBar.width()}getConstrainedHandleBarX(e){let t=e;return t<0?t=0:t+this.handleBar.width()>this.group.width()&&(t=this.getScrollHandleMaxX()),t}clickScrollTo(e){let t=this.group.width()/this.scrollStepNumberOfDivisions;if(!(e>=this.handleBar.x()&&e<=this.handleBar.x()+this.handleBar.width())){let r=this.handleBar.x()>e,s=this.handleBar.x()+t*(r?-1:1);r?s=s<e?e:s:s=s+this.handleBar.width()>e?e-this.handleBar.width():s,this.scrollToEased(s)}}scrollTo(e){this.handleBar.x(this.getConstrainedHandleBarX(e)),this.syncLeftRightHandles(),this.onScroll$.next({scrollPercent:this.getScrollHandlePercent()})}scrollToEased(e){let t=this.handleBar.x(),r=this.getConstrainedHandleBarX(e);Js({layer:this.handleGroup.getLayer(),duration:F.TIMELINE_SCROLL_EASED_DURATION_MS,from:t,to:r,onUpdateHandler:(s,n)=>{this.scrollTo(n)}})}calculateHandleBarWidthFromZoomRatioPercent(e){return new Z(this.group.width()).mul(100).div(e).toNumber()}getZoomPercent(){return this.group.width()===this.handleBar.width()?100:new Z(this.group.width()).mul(100).div(this.handleBar.width()).toNumber()}getScrollHandlePercent(){return this.handleBar.x()===0?0:new Z(this.handleBar.x()).div(this.group.width()-this.handleBar.width()).mul(100).toNumber()}updateScrollHandle(e){let t=e.getScrollHandleHorizontalMeasurement(this.group.width());this.handleBar.setAttrs({...t}),this.syncLeftRightHandles()}syncLeftRightHandles(){this.leftZoomHandle.x(this.handleBar.x()),this.rightZoomHandle.x(this.handleBar.x()+this.handleBar.width())}setWidth(e){this.width=e,this.onMeasurementsChange()}setPosition(e){this.x=e.x,this.y=e.y,this.group.setAttrs({...e})}getPosition(){return this.group.getPosition()}getRect(){return{...this.group.getPosition(),...this.group.getSize()}}}const Vm={style:{...F.POSITION_TOP_LEFT,height:100,fill:"#737373",fillSnapped:"#ffd500",lineWidth:2,symbolY:0,symbolHeight:15,textFontSize:12,textFill:"#0d0f05",textSnappedFill:"#f43530",visible:!1}};class zm extends et{constructor(e,t){super(_i(e,Vm)),this.stylesProvider=dt.instance(),this.timeline=t}createCanvasNode(){return this.group=new M.Group({x:this.style.x,y:this.style.y,visible:this.style.visible,listening:!1}),this.line=new M.Line({points:[this.style.x,0,this.style.x,this.style.height],stroke:this.style.fill,strokeWidth:this.style.lineWidth,listening:!1}),this.symbol=new M.Circle({y:this.style.symbolY,fill:this.style.fill,radius:this.style.symbolHeight/2,offsetY:-this.style.symbolHeight/2}),this.group.add(this.symbol),this.group.add(this.line),this.label=new M.Label({...F.POSITION_TOP_LEFT,listening:!1}),this.text=new M.Text({fontSize:this.style.textFontSize,fontFamily:this.stylesProvider.styles.omakasePlayerStyle.fontFamily,fill:this.style.textFill,...F.POSITION_TOP_LEFT,text:"",listening:!1}),this.label.y(-this.text.getSelfRect().height),this.label.add(this.text),this.group.add(this.label),this.group}afterCanvasNodeInit(){this.styleAdapter.onChange$.pipe(k(this.onDestroy$)).subscribe(e=>{this.onMeasurementsChange()}),this.stylesProvider.onChange$.pipe(We(e=>!!e),k(this.onDestroy$)).subscribe(e=>{this.text.setAttrs({fontFamily:this.stylesProvider.styles.omakasePlayerStyle.fontFamily})})}onMeasurementsChange(){this.line.points([this.line.x(),0,this.line.x(),this.style.height])}sync(e,t=!1){this.style.visible||this.toggleVisible(!0);let r=this.timeline.timelinePositionToTimeFormatted(e),s=this.text.getSelfRect(),n=s.width/2,a=-n,o=this.timeline.getTimecodedGroupHorizontalMeasurement();o.width-e<n?a=-s.width+(o.width-e):e<n&&(a=-n+(n-e)),this.group.x(e),this.text.text(r),this.label.x(a),t?(this.line.stroke(this.style.fillSnapped),this.text.fill(this.style.fillSnapped),this.symbol.visible(!1)):(this.line.stroke(this.style.fill),this.text.fill(this.style.fill),this.symbol.visible(!0))}toggleVisible(e){this.style={visible:e},this.group.visible(e)}}const Wm={style:{visible:!0,fill:"#f43530",lineWidth:2,symbolHeight:15,scrubberHeight:15,backgroundFill:"#ffffff",backgroundOpacity:0,playProgressFill:"#008cbc",playProgressOpacity:.5,bufferedFill:"#a2a2a2",bufferedOpacity:1}};class Um extends et{constructor(e,t,r){super(_i(e,Wm)),this.timeline=t,this.videoController=r}createCanvasNode(){return this.group=new M.Group({...F.POSITION_TOP_LEFT,listening:!1}),this.background=new M.Rect({...F.POSITION_TOP_LEFT,height:this.style.scrubberHeight,fill:this.style.backgroundFill,opacity:this.style.backgroundOpacity,listening:!1}),this.playProgressBackground=new M.Rect({...F.POSITION_TOP_LEFT,height:this.style.scrubberHeight,fill:this.style.playProgressFill,opacity:this.style.playProgressOpacity,listening:!1}),this.playheadGroup=new M.Group({...F.POSITION_TOP_LEFT,visible:this.style.visible,listening:!1}),this.playheadLine=new M.Line({points:[0,0,0,0],stroke:this.style.fill,strokeWidth:this.style.lineWidth,listening:!1}),this.playheadSymbol=wi.createTriangle({...F.POSITION_TOP_LEFT,height:this.style.symbolHeight,color:this.style.fill}),this.bufferedGroup=new M.Group({...F.POSITION_TOP_LEFT,listening:!1}),this.group.add(this.background),this.group.add(this.bufferedGroup),this.group.add(this.playProgressBackground),this.playheadGroup.add(this.playheadLine),this.playheadGroup.add(this.playheadSymbol),this.group.add(this.playheadGroup),this.group}afterCanvasNodeInit(){this.settleLayout(),this.timeline.onZoom$.pipe(k(this.onDestroy$)).subscribe(e=>{this.settleLayout()}),this.videoController.onVideoLoading$.pipe(k(this.onDestroy$)).subscribe(e=>{this.group.visible(!1)}),this.videoController.onVideoLoaded$.pipe(k(this.onDestroy$)).subscribe(e=>{this.group.visible(!0),this.doPlayProgress(),this.doBufferingProgress()}),this.videoController.onVideoTimeChange$.pipe(k(this.onDestroy$)).subscribe(e=>{this.doPlayProgress()}),this.videoController.onSeeking$.pipe(k(this.onDestroy$)).subscribe(e=>{this.doPlayProgress(),this.doBufferingProgress()}),this.videoController.onBuffering$.pipe(k(this.onDestroy$)).subscribe(e=>{this.doBufferingProgress()})}onMeasurementsChange(){this.settleLayout()}getPlayheadPosition(){return this.playheadGroup.x()}settleLayout(){let e=this.timeline.getTimecodedGroupDimension();[this.group,this.bufferedGroup,this.playheadGroup].forEach(t=>{t.setAttrs({...e})}),[this.background].forEach(t=>{t.setAttrs({width:e.width})}),this.playheadLine.setAttrs({points:[0,0,0,e.height]}),this.doPlayProgress(),this.doBufferingProgress()}doPlayProgress(){let e=this.timeline.timeToTimelinePosition(this.videoController.getCurrentTime());this.playProgressBackground.width(e),this.playheadGroup.x(e)}doBufferingProgress(){let e=this.videoController.getBufferedTimespans();if(e&&e.length>0)if(this.bufferedGroup.hasChildren()){let t=e.length,r=this.bufferedGroup.getChildren().length;t===r?this.bufferedGroup.getChildren().forEach((s,n)=>{let a=e[n],o=this.timeline.timeToTimelinePosition(a.start),h=this.timeline.timeToTimelinePosition(a.end);s.setAttrs({x:o,width:h-o})}):(this.bufferedGroup.getChildren().forEach(s=>s.destroy()),this.createBuffers(e))}else this.createBuffers(e)}createBuffers(e){e.forEach(t=>{let r=this.timeline.timeToTimelinePosition(t.start),s=this.timeline.timeToTimelinePosition(t.end),n=new M.Rect({x:r,y:0,width:s-r,height:this.style.scrubberHeight,fill:this.style.bufferedFill,opacity:this.style.bufferedOpacity,listening:!1});this.bufferedGroup.add(n)})}}const Zm={style:{...F.POSITION_TOP_LEFT,width:150,height:20,textFontSize:20,textFill:"#0d0f05",visible:!0}};class Hl extends et{constructor(e,t){super(_i(e,Zm)),this.stylesProvider=dt.instance(),this.videoEventStreamBreaker$=new V,this.videoController=t}createCanvasNode(){return this.group=new M.Group({x:this.style.x,y:this.style.y,width:this.style.width,height:this.style.height,listening:!1,visible:this.style.visible}),this.text=new M.Text({...F.POSITION_TOP_LEFT,width:this.group.width(),height:this.group.height(),text:"",fontSize:this.style.textFontSize,fontFamily:this.stylesProvider.styles.omakasePlayerStyle.fontFamily,fill:this.style.textFill,visible:!0,align:"left",verticalAlign:"middle"}),this.group.add(this.text),this.group}afterCanvasNodeInit(){super.afterCanvasNodeInit(),this.stylesProvider.onChange$.pipe(We(e=>!!e),k(this.onDestroy$)).subscribe(e=>{this.text.setAttrs({fontFamily:this.stylesProvider.styles.omakasePlayerStyle.fontFamily})}),this.videoController.onVideoLoaded$.pipe(We(e=>!!e),k(this.onDestroy$)).subscribe(e=>{this.onVideoLoadedEvent(e)})}onMeasurementsChange(){this.group.width(this.style.width)}fireVideoEventStreamBreaker(){Ge(this.videoEventStreamBreaker$),this.videoEventStreamBreaker$=new V}onVideoLoadedEvent(e){this.fireVideoEventStreamBreaker(),this.text.text(this.videoController.formatTimestamp(0)),this.videoController.onVideoTimeChange$.pipe(k(this.videoEventStreamBreaker$)).subscribe(t=>{this.text.text(this.videoController.formatTimestamp(t.currentTime))})}setVisible(e){this.style={visible:e},this.isInitialized()&&this.group.visible(e)}setPosition(e){this.style={...e},this.group.setAttrs({...e}),this.onMeasurementsChange()}getRect(){return this.group.getClientRect()}}const jm={...rr,height:60,tickDivisor:5,tickDivisionMinWidth:18,tickFill:"#0d0f05",tickHeight:12,divisionTickFill:"#000000",divisionTickHeight:12*F.GOLDEN_RATIO,timecodeShowFirst:!0,timecodeFontSize:11,timecodeFill:"#0d0f05"};class Xm extends sr{constructor(e,t){super({...e,style:{...jm,...e.style}}),this.onClick$=new V,this.onMouseEnter$=new V,this.onMouseOver$=new V,this.onMouseMove$=new V,this.onMouseOut$=new V,this.onMouseLeave$=new V,this.videoController=t}createCanvasNode(){return super.createCanvasNode(),this.timecodedGroup=new M.Group({...this.timelinePosition,width:this.timeline.getTimecodedGroupDimension().width,height:this.bodyGroup.height()}),this.timecodedEventCatcher=wi.createEventCatcher({width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.ticksGroup=new M.Group({...F.POSITION_TOP_LEFT,width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.timecodedGroup.add(this.timecodedEventCatcher),this.timecodedGroup.add(this.ticksGroup),this.timeline.addToTimecodedBaseGroup(this.timecodedGroup),this.timecodeDisplay=new Hl({style:{x:10,y:0,width:this.leftGroup.width(),height:this.getRect().height}},this.videoController),this.leftGroup.add(this.timecodeDisplay.initCanvasNode()),this.bodyGroup}settleLayout(){super.settleLayout();let e=this.timeline.getTimecodedGroupHorizontalMeasurement();[this.timecodedGroup,this.timecodedEventCatcher,this.ticksGroup].forEach(t=>{t.width(e.width)}),this.refreshTimeDivisions()}afterCanvasNodeInit(){super.afterCanvasNodeInit(),this.timecodedEventCatcher.on("mousemove",e=>{this.onMouseMove$.next({evt:e.evt,position:this.timecodedGroup.getRelativePointerPosition()})}),this.timecodedEventCatcher.on("mouseenter",e=>{this.onMouseEnter$.next({evt:e.evt,position:this.timecodedGroup.getRelativePointerPosition()})}),this.timecodedEventCatcher.on("mouseout",e=>{this.onMouseOut$.next({evt:e.evt,position:this.timecodedGroup.getRelativePointerPosition()})}),this.timecodedEventCatcher.on("mouseleave",e=>{this.onMouseLeave$.next({evt:e.evt,position:this.timecodedGroup.getRelativePointerPosition()})}),this.timecodedEventCatcher.on("click",e=>{this.onClick$.next({evt:e.evt,position:this.timecodedGroup.getRelativePointerPosition()})}),this.videoController.onVideoLoading$.pipe(k(this.onDestroy$)).subscribe(e=>{this.clearContent()}),this.videoController.onVideoLoaded$.pipe(k(this.onDestroy$)).subscribe(e=>{this.settleLayout()})}onStyleChange(){super.onStyleChange(),this.refreshTimeDivisions(!0)}destroy(){this.timecodedGroup.destroy(),this.videoController=null;let e=[this.onClick$,this.onMouseOver$,this.onMouseMove$,this.onMouseOut$,this.onMouseLeave$];Vt(...e),bi(...e),super.destroy()}clearContent(){this.ticksGroup.destroyChildren()}refreshTimeDivisions(e=!1){if(!this.isTimelineReady())return;let t=this.style.tickDivisor,r=this.style.tickDivisionMinWidth,s=this.timeline.getTimecodedGroupRect().width,n=this.resolveTimeDivisionWidth(s,r,t,t),a=new Z(s).div(n).round().toNumber(),o=!e&&this.tickTotalDivisions===a&&!(this.ticksGroup.getChildren().length<1);o||this.clearContent(),this.tickDivisionWidth=n,this.tickTotalDivisions=a;let h=0,l=2,d=2,u=5;for(let c=0;c<this.tickTotalDivisions+1;c++){let p=c===0,f=c===this.tickTotalDivisions,m=c%t===0,g=c*this.tickDivisionWidth,_=m?this.style.divisionTickHeight:this.style.tickHeight,w=this.ticksGroup.height()-_,b=this.ticksGroup.height()-this.style.divisionTickHeight-u;if(o)this.ticksGroup.getChildren()[c].x(g);else{let T=new M.Group({x:g,y:h}),L=0,A=new M.Line({points:[L,w,L,w+_],stroke:this.style.tickFill,strokeWidth:1,listening:!1});T.add(A);let D=new M.Text({fontSize:this.style.timecodeFontSize,fontFamily:this.stylesProvider.styles.omakasePlayerStyle.fontFamily,fill:this.style.timecodeFill,text:`${this.timeline.timelinePositionToTimeFormatted(g)}`,listening:!1}),R=D.getSelfRect(),H=p?L+l:f?L-R.width-d:L-R.width/2,$=b-R.height;D.setAttrs({x:H,y:$});let I=m;I=p?this.style.timecodeShowFirst:I,I&&(T.add(D),T.x()+(D.x()>0?0:D.x()),T.y(),D.width()),this.ticksGroup.add(T)}}}resolveTimeDivisionWidth(e,t,r,s){return new Z(e).div(s).floor().greaterThan(t)?this.resolveTimeDivisionWidth(e,t,r,s*r):new Z(e).div(s/r).toNumber()}}const qm={timelineHTMLElementId:"omakase-timeline",playheadHoverSnapArea:5,zoomScale:1.02,zoomBaseline:100,zoomMax:1500,style:{stageMinWidth:700,backgroundFill:"#f5f5f5",headerBackgroundFill:"#f5f5f5",footerBackgroundFill:"#f5f5f5",scrollbarHeight:15,thumbnailHoverWidth:200,thumbnailHoverStroke:"rgba(255,73,145,0.9)",thumbnailHoverStrokeWidth:5,thumbnailHoverYOffset:0,headerHeight:50,footerHeight:50,leftPanelWidth:200,rightPanelLeftGutterWidth:30,rightPanelRightGutterWidth:30,timecodedContainerClipPadding:20,playheadVisible:!0,playheadFill:"#f43530",playheadLineWidth:2,playheadSymbolHeight:15,playheadScrubberHeight:15,playheadBackgroundFill:"#ffffff",playheadBackgroundOpacity:0,playheadPlayProgressFill:"#008cbc",playheadPlayProgressOpacity:.5,playheadBufferedFill:"#a2a2a2",playheadBufferedOpacity:1}},La="omakase_scrubber_lane";class Ym extends et{constructor(e,t){super(_i(e,qm)),this.scrollWithPlayhead=!0,this.syncTimelineWithPlayheadInProgress=!1,this.mouseWheelEnabled=!1,this.leftPanelVisible=!0,this.videoEventBreaker$=new V,this.onScroll$=new V,this.onZoom$=new V,this.timelineHTMLElementId=this.config.timelineHTMLElementId,this.thumbnailVttUrl=this.config.thumbnailVttUrl,this.axiosConfig=this.config.axiosConfig,this.playheadHoverSnapArea=this.config.playheadHoverSnapArea,this.zoomScale=this.config.zoomScale,this.zoomBaseline=this.config.zoomBaseline,this.zoomMax=this.config.zoomMax,this.timecodedGroupNodes=[],this.timelineLanes=[],this.timelineLanesMap=new Map,this.timelineHTMLElement=document.getElementById(this.timelineHTMLElementId),this.videoController=t}createCanvasNode(){let e=this.resolveStageDimension();return this.width=e.width,this.stage=new M.Stage({container:this.timelineHTMLElementId,...e}),this.layer=new M.Layer,this.stage.add(this.layer),this.layoutGroup=new M.Group({...F.POSITION_TOP_LEFT}),this.layer.add(this.layoutGroup),this.layoutBackground=new M.Rect({...F.POSITION_TOP_LEFT,fill:this.style.backgroundFill}),this.headerGroup=new M.Group({...F.POSITION_TOP_LEFT}),this.headerBackground=new M.Rect({...F.POSITION_TOP_LEFT,fill:this.style.headerBackgroundFill}),this.footerGroup=new M.Group({...F.POSITION_TOP_LEFT}),this.footerBackground=new M.Rect({...F.POSITION_TOP_LEFT,fill:this.style.footerBackgroundFill}),this.bodyGroup=new M.Group({...F.POSITION_TOP_LEFT}),this.bodyContentGroup=new M.Group({...F.POSITION_TOP_LEFT}),this.leftPanel=new M.Group({...F.POSITION_TOP_LEFT}),this.rightPanel=new M.Group({...F.POSITION_TOP_LEFT}),this.timecodedContainer=new M.Group({...F.POSITION_TOP_LEFT}),this.timecodedGroup=new M.Group({...F.POSITION_TOP_LEFT,draggable:!0}),this.timecodedBaseGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedBaseGroup"}),this.timecodedThumbnailsGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedThumbnailsGroup"}),this.timecodedSubtitlesGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedSubtitlesGroup"}),this.timecodedAudioGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedAudioGroup"}),this.timecodedMarkersGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedMarkersGroup"}),this.timecodedSurfaceGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedSurfaceGroup"}),this.timecodedBackground=new M.Rect({...F.POSITION_TOP_LEFT,fill:"yellow",opacity:0,listening:!1}),this.timecodedEventCatcher=wi.createEventCatcher(),this.thumbnailHover=new Ys({style:{visible:!1,stroke:this.style.thumbnailHoverStroke,strokeWidth:this.style.thumbnailHoverStrokeWidth}}),this.layoutGroup.add(this.layoutBackground),this.layoutGroup.add(this.headerGroup),this.layoutGroup.add(this.footerGroup),this.layoutGroup.add(this.bodyGroup),this.headerGroup.add(this.headerBackground),this.footerGroup.add(this.footerBackground),this.bodyGroup.add(this.bodyContentGroup),this.bodyGroup.add(this.leftPanel),this.bodyGroup.add(this.rightPanel),this.rightPanel.add(this.timecodedContainer),this.timecodedContainer.add(this.timecodedGroup),[this.timecodedBackground,this.timecodedEventCatcher,this.timecodedBaseGroup,this.timecodedThumbnailsGroup,this.timecodedSubtitlesGroup,this.timecodedAudioGroup,this.timecodedMarkersGroup,this.timecodedSurfaceGroup].forEach(t=>{this.timecodedGroupNodes.push(t),this.timecodedGroup.add(t)}),this.scrollbar=new $m({style:{height:this.style.scrollbarHeight}}),this.rightPanel.add(this.scrollbar.initCanvasNode()),this.playhead=new Um({style:{visible:this.style.playheadVisible,fill:this.style.playheadFill,lineWidth:this.style.playheadLineWidth,symbolHeight:this.style.playheadSymbolHeight,backgroundFill:this.style.playheadBackgroundFill,backgroundOpacity:this.style.playheadBackgroundOpacity,scrubberHeight:this.style.playheadScrubberHeight,playProgressFill:this.style.playheadPlayProgressFill,playProgressOpacity:this.style.playheadPlayProgressOpacity,bufferedFill:this.style.playheadBufferedFill,bufferedOpacity:this.style.playheadBufferedOpacity}},this,this.videoController),this.playheadHover=new zm({},this),[this.playhead,this.playheadHover].forEach(t=>{this.addToTimecodedSurfaceGroup(t.initCanvasNode())}),this.headerTimecodeDisplay=new Hl({style:{x:10,y:10,visible:!1}},this.videoController),this.headerGroup.add(this.headerTimecodeDisplay.initCanvasNode()),this.settleLayout(),this.addToTimecodedSurfaceGroup(this.thumbnailHover.initCanvasNode()),this.scrubberLane=new Xm({id:La,description:""},this.videoController),this.addLanes([this.scrubberLane]),this.stage}afterCanvasNodeInit(){this.videoController.onVideoLoading$.pipe(We(e=>!!e),k(this.onDestroy$)).subscribe(e=>{this.clearContent()}),this.videoController.onVideoLoaded$.pipe(We(e=>!!e),k(this.onDestroy$)).subscribe(e=>{this.onVideoLoadedEvent(e)}),be(window,"resize").pipe(k(this.onDestroy$)).subscribe(e=>{setTimeout(()=>{this.onWindowResize(e)},200)}),this.timecodedGroup.on("mouseenter",e=>{this.playheadHover.toggleVisible(this.videoController.isVideoLoaded())}),this.timecodedGroup.on("mouseleave",e=>{this.playheadHover.toggleVisible(!1)}),this.timecodedGroup.on("mousemove",e=>{if(!this.videoController.isVideoLoaded())return;let t=this.timecodedGroup.getRelativePointerPosition().x;this.playheadHoverMove(t)}),this.timecodedMarkersGroup.on("mousemove",e=>{if(!this.videoController.isVideoLoaded())return;let t=this.timecodedGroup.getRelativePointerPosition().x;this.playheadHoverMove(t)}),this.timecodedGroup.on("wheel",e=>{if(!this.videoController.isVideoLoaded())return;if(this.mouseWheelEnabled){let r=e.evt;r.preventDefault();let s=r.deltaY>0?"IN":"OUT";r.ctrlKey&&(s=s==="IN"?"OUT":"IN"),this.zoomStep(s,this.timecodedGroup.getRelativePointerPosition().x),this.updateScrollWithPlayhead()}let t=this.timecodedGroup.getRelativePointerPosition().x;this.playheadHoverMove(t)}),this.timecodedGroup.on("dragstart dragmove dragend",e=>{if(!this.videoController.isVideoLoaded()){this.timecodedGroup.setAttrs({...F.POSITION_TOP_LEFT});return}if(e.target===this.timecodedGroup){let t=this.timecodedGroup.getPosition();this.timecodedGroup.setAttrs({x:this.getConstrainedTimelineX(t.x),y:0}),this.onScroll$.next(this.createScrollEvent()),this.scrollbar.updateScrollHandle(this)}this.updateScrollWithPlayhead()}),this.timecodedGroup.on("dragmove",e=>{it.cursor("grabbing")}),this.timecodedGroup.on("dragend",e=>{it.cursor("default")}),this.scrubberLane.onMouseMove$.pipe(k(this.onDestroy$)).subscribe(e=>{if(!this.videoController.isVideoLoaded())return;this.mouseWheelEnabled=!0;let t=this.timecodedGroup.getRelativePointerPosition().x,r=this.timelinePositionToTime(t);if(this.thumbnailVttFile){let s=this.thumbnailVttFile.findCue(r);this.showThumbnailHover(s)}}),this.scrubberLane.onMouseEnter$.pipe(k(this.onDestroy$)).subscribe(e=>{this.mouseWheelEnabled=!0}),this.scrubberLane.onMouseLeave$.pipe(k(this.onDestroy$)).subscribe(e=>{this.hideThumbnailHover(),this.mouseWheelEnabled=!1}),this.scrubberLane.onClick$.pipe(k(this.onDestroy$)).subscribe(e=>{if(!this.videoController.isVideoLoaded())return;this.updateScrollWithPlayhead();let t=this.timecodedGroup.getRelativePointerPosition().x;this.playheadHoverMove(t),this.videoController.isVideoLoaded()&&this.videoController.seekToTimestamp(this.timelinePositionToTime(t)).subscribe(()=>{})}),this.scrollbar.onScroll$.pipe(k(this.onDestroy$)).subscribe(e=>{this.videoController.isVideoLoaded()&&(this.setHorizontalScrollPercent(this.scrollbar.getScrollHandlePercent()),this.updateScrollWithPlayhead(),this.onScroll$.next(this.createScrollEvent()))}),this.scrollbar.onZoom$.pipe(k(this.onDestroy$)).subscribe(e=>{this.videoController.isVideoLoaded()&&(this.zoomByPercent(e.zoomPercent,!1),this.updateScrollWithPlayhead())}),this.thumbnailVttUrl&&this.fetchThumbnailVttFile().subscribe()}settleLayout(){this.stage.setAttrs({...this.resolveStageDimension()});let e=this.calculateHeights();this.headerGroup.setAttrs({width:this.width,height:this.style.headerHeight}),this.bodyGroup.setAttrs({y:this.headerGroup.y()+this.headerGroup.height(),width:this.layoutGroup.width(),height:e.bodyHeight}),this.footerGroup.setAttrs({y:this.bodyGroup.y()+this.bodyGroup.height(),width:this.width,height:this.style.footerHeight}),this.layoutGroup.setAttrs({width:this.width,height:e.layoutHeight}),this.layoutBackground.setAttrs({...this.layoutGroup.getSize()}),this.headerBackground.setAttrs({...this.headerGroup.getSize()}),this.footerBackground.setAttrs({...this.footerGroup.getSize()}),[this.bodyContentGroup].forEach(t=>{t.setAttrs({...this.bodyGroup.getSize()})}),[this.leftPanel,this.rightPanel].forEach(t=>{t.setAttrs({height:this.bodyGroup.getSize().height})}),this.leftPanel.setAttrs({width:this.leftPanelVisible?this.style.leftPanelWidth:0,visible:this.leftPanelVisible}),this.rightPanel.setAttrs({x:this.leftPanel.x()+this.leftPanel.width()+this.style.rightPanelLeftGutterWidth,width:this.layoutGroup.width()-(this.leftPanel.width()+this.style.rightPanelLeftGutterWidth+this.style.rightPanelRightGutterWidth)}),[this.timecodedContainer,this.timecodedGroup,...this.timecodedGroupNodes].forEach(t=>{t.setAttrs({...this.rightPanel.getSize()})}),this.timecodedContainer.clipFunc(t=>{t.rect(-this.style.timecodedContainerClipPadding,-500,this.timecodedContainer.width()+2*this.style.timecodedContainerClipPadding,this.timecodedContainer.height()+500)}),this.timecodedThumbnailsGroup.clipFunc(t=>{t.rect(0,0,this.timecodedThumbnailsGroup.width(),this.timecodedThumbnailsGroup.height())}),this.scrollbar.setPosition({...this.scrollbar.getPosition(),y:this.leftPanel.getSize().height}),this.scrollbar.setWidth(this.timecodedContainer.width()),this.scrollbar.updateScrollHandle(this),this.maxTimecodedGroupWidth=this.calculateWidthFromZoomRatioPercent(this.zoomMax),this.playheadHover.style={height:this.timecodedContainer.height()},this.timelineLanes.forEach(t=>{t.onMeasurementsChange()}),this.playhead.onMeasurementsChange()}onMeasurementsChange(){this.settleLayout();let e=this.getTimecodedGroupDimension();this.timelineLanes.forEach(t=>{t.onMeasurementsChange()}),this.zoomByWidth(e.width,this.resolveZoomFocus()),this.scrollbar.updateScrollHandle(this)}onWindowResize(e){let t=this.resolveStageDimension();this.width=t.width,this.onMeasurementsChange()}calculateHeights(){let t=this.getLanes().map(r=>r.getDimension().height).reduce((r,s)=>r+s,0);return{bodyHeight:t,layoutHeight:this.style.headerHeight+t+this.style.footerHeight}}resolveStageDimension(){let e=this.getTimelineHTMLElementRect(),t=this.calculateHeights();return{width:e.width>=this.style.stageMinWidth?e.width:this.style.stageMinWidth,height:t.layoutHeight}}getTimelineHTMLElementRect(){return{x:this.timelineHTMLElement.offsetLeft,y:this.timelineHTMLElement.offsetTop,width:this.timelineHTMLElement.offsetWidth,height:this.timelineHTMLElement.offsetHeight}}showThumbnailHover(e){if(e)if(this.thumbnailHover.setVisible(!0),this.thumbnailHover.getThumbnailVttCue()===e){this.thumbnailHover.setThumbnailVttCue(e);let t=this.resolveThumbnailPosition(this.thumbnailHover);this.thumbnailHover.setPosition(t),this.thumbnailHover.getCanvasNode().moveToTop()}else ct.createKonvaImageSizedByWidth(e.url,this.style.thumbnailHoverWidth).subscribe(t=>{this.thumbnailHover.setThumbnailVttCue(e),this.thumbnailHover.setDimension(t.getSize()),this.thumbnailHover.setImage(t),this.thumbnailHover.setPosition(this.resolveThumbnailPosition(this.thumbnailHover)),this.thumbnailHover.getCanvasNode().moveToTop()})}hideThumbnailHover(){this.thumbnailHover&&this.thumbnailHover.setVisible(!1)}resolveThumbnailPosition(e){let t=this.timecodedGroup.getRelativePointerPosition(),r=this.getTimecodedGroupDimension(),s=e.getImage().getSize(),n=t.x-s.width/2,a=e.style.strokeWidth>0?e.style.strokeWidth/2:0;n=n-a<0?a:n+s.width+a>r.width?r.width-s.width-a:n;let h=this.scrubberLane.getRect();return{x:n,y:h.y+h.height+e.style.strokeWidth/2+this.style.thumbnailHoverYOffset}}createScrollEvent(){return{scrollPercent:this.getHorizontalScrollPercent()}}createZoomEvent(){return{zoomPercent:this.getZoomPercent()}}getHorizontalScrollPercent(){if(this.isSnappedStart())return 0;if(this.isSnappedEnd())return 100;{let e=new Z(this.getTimecodedContainerDimension().width-this.getTimecodedGroupDimension().width).abs();return new Z(this.getTimecodedGroupPosition().x).abs().mul(100).div(e).toNumber()}}setHorizontalScrollPercent(e){this.setTimelinePosition(this.calculateTimelineXFromScrollPercent(e))}getScrollHandleHorizontalMeasurement(e){let t=this.getTimecodedGroupDimension().width,r=this.getTimecodedGroupPosition().x,s;return t<=e?s={width:e,x:0}:s={width:new Z(e).mul(e).div(t).round().toNumber(),x:new Z(r).abs().mul(e).div(t).toNumber()},s}scrollTo(e){return e=_e.coerce.number().min(0).max(100).parse(e),this.scrollToPercentEased(e)}scrollToPlayhead(){let e=-this.playhead.getPlayheadPosition()+this.getTimecodedContainerDimension().width/2;return this.scrollToEased(e)}scrollToPercent(e){let t=this.calculateTimelineXFromScrollPercent(e);this.scrollTimeline(t)}scrollToPercentEased(e){let t=this.calculateTimelineXFromScrollPercent(e);return this.scrollToEased(t)}scrollToEased(e){return new re(t=>{let r=this.getTimecodedGroupPosition().x;Js({layer:this.timecodedGroup.getLayer(),duration:F.TIMELINE_SCROLL_EASED_DURATION_MS,from:r,to:e,onUpdateHandler:(s,n)=>{this.scrollTimeline(n)},onCompleteHandler:(s,n)=>{t.next(this.getHorizontalScrollPercent()),t.complete()}})})}isPlayheadInTimecodedView(){return this.isInVisiblePositionRange(this.playhead.getPlayheadPosition())}updateScrollWithPlayhead(){let e=this.playhead.getPlayheadPosition(),t=e<this.getVisiblePositionRange().start,r=this.isInVisiblePositionRange(e);this.scrollWithPlayhead=r&&!t}syncTimelineWithPlayhead(){return new re(e=>{this.scrollToEased(-this.playhead.getPlayheadPosition()).pipe(ke(t=>{e.next(this.getHorizontalScrollPercent()),e.complete()})).subscribe()})}setTimelinePosition(e){let t=this.getConstrainedTimelineX(e);this.timecodedGroup.x(t)}scrollTimeline(e){let t=this.getTimecodedGroupPosition().x;this.setTimelinePosition(e),this.getTimecodedGroupPosition().x!==t&&(this.scrollbar.updateScrollHandle(this),this.setHorizontalScrollPercent(this.scrollbar.getScrollHandlePercent()),this.onScroll$.next(this.createScrollEvent()))}calculateTimelineXFromScrollPercent(e){e=this.getConstrainedScrollPercent(e);let t=this.getTimecodedGroupDimension(),r=this.getTimecodedContainerDimension();if(t.width>r.width){let s=new Z(r.width-t.width);return new Z(e).mul(s).div(100).toDecimalPlaces(2).toNumber()}else return 0}getZoomPercent(){let e=this.getTimecodedGroupDimension(),t=this.getTimecodedContainerDimension();return e.width>t.width?new Z(e.width).mul(100).div(t.width).round().toNumber():this.zoomBaseline}zoomTo(e){return e=_e.coerce.number().min(this.getZoomBaseline()).max(this.getZoomMax()).parse(e),this.zoomToEased(e)}zoomIn(){return new re(e=>{this.zoomStep("IN",this.timecodedGroup.getRelativePointerPosition().x),e.next(this.getZoomPercent()),e.complete()})}zoomOut(){return new re(e=>{this.zoomStep("OUT",this.timecodedGroup.getRelativePointerPosition().x),e.next(this.getZoomPercent()),e.complete()})}zoomToEased(e){return new re(t=>{e=this.getConstrainedZoomPercent(e);let r=this.getTimecodedGroupDimension().width,s=this.calculateWidthFromZoomRatioPercent(e);Js({layer:this.timecodedGroup.getLayer(),duration:F.TIMELINE_ZOOM_EASED_DURATION_MS,from:r,to:s,onUpdateHandler:(n,a)=>{this.zoomByWidth(a,this.resolveZoomFocus())},onCompleteHandler:(n,a)=>{t.next(this.getZoomPercent()),t.complete()}})})}zoomStep(e,t){let r=new Z(this.getTimecodedGroupDimension().width),s=(e==="IN"?r.mul(this.zoomScale):r.div(this.zoomScale)).round().toNumber();this.zoomByWidth(s,t)}zoomByPercent(e,t=!0){e=this.getConstrainedZoomPercent(e);let r=this.calculateWidthFromZoomRatioPercent(e);return this.zoomByWidth(r,this.resolveZoomFocus(),t),this.getZoomPercent()}zoomByWidth(e,t,r=!0){let s=this.getTimecodedGroupPosition().x,n=this.getTimecodedGroupDimension().width;e=this.getConstrainedWidth(e);let a=this.calculateNewPosition(e,t);this.hideThumbnailHover(),this.timecodedGroup.setAttrs({width:e,x:a}),this.timecodedGroupNodes.forEach(h=>{h.width(e)}),(this.getTimecodedGroupDimension().width!==n||this.getTimecodedGroupPosition().x!==s)&&(r?this.scrollbar.updateScrollHandle(this):this.playheadHover.toggleVisible(!1),this.setHorizontalScrollPercent(this.scrollbar.getScrollHandlePercent()),this.onZoom$.next(this.createZoomEvent()),this.onScroll$.next(this.createScrollEvent()))}calculateNewPosition(e,t=0){let r=this.getTimecodedGroupPosition().x,s=this.getTimecodedGroupDimension().width,n=this.getTimecodedContainerRect(),a=e>s?"IN":"OUT",o=r;if(e===n.width)o=0;else if(e>n.width){if(t>0){let h=new Z(t).div(s);if(h.greaterThanOrEqualTo(0)&&h.lessThanOrEqualTo(1)){let l=e-s,d=h.mul(l).abs().round().toNumber(),u=r+d*(a==="IN"?-1:1);o=u<0?u:0}}if(e>n.width){let h=n.x+n.width;o+e<=h&&(o=n.width-e)}}return o}resolveZoomFocus(){return this.videoController.isVideoLoaded()?this.resolvePlayheadSyncPosition():this.isSnappedStart()?0:this.isSnappedEnd()?this.getTimecodedGroupDimension().width:this.getTimecodedGroupDimension().width/2}calculateWidthFromZoomRatioPercent(e){return new Z(this.getTimecodedContainerDimension().width).mul(e).div(100).round().toNumber()}getConstrainedWidth(e){let t=this.getTimecodedContainerDimension();return e>=t.width?e<=this.maxTimecodedGroupWidth?e:this.maxTimecodedGroupWidth:t.width}getConstrainedZoomPercent(e){return e<this.zoomBaseline?this.zoomBaseline:e>this.zoomMax?this.zoomMax:e}getConstrainedScrollPercent(e){return e<0?0:e>100?100:e}playheadHoverMove(e){if(this.videoController.isVideoLoaded()&&this.playheadHover){let t=!1;if(!this.videoController.isPlaying()){let r=this.resolvePlayheadSyncPosition();e>r-this.playheadHoverSnapArea&&e<r+this.playheadHoverSnapArea&&(e=r,t=!0)}this.playheadHover.sync(e,t)}}resolvePlayheadSyncPosition(){return this.timeToTimelinePosition(this.videoController.getCurrentTime())}onVideoLoadedEvent(e){this.fireVideoEventBreaker(),this.clearContent(),this.syncVideoMetadata(),this.videoController.onVideoTimeChange$.pipe(k(this.videoEventBreaker$)).subscribe(t=>{this.syncVideoMetadata()}),this.videoController.onPlay$.pipe(k(this.videoEventBreaker$)).subscribe(t=>{this.updateScrollWithPlayhead()})}fireVideoEventBreaker(){Ge(this.videoEventBreaker$),this.videoEventBreaker$=new V}setThumbnailVttFile(e){this.thumbnailVttFile=e}syncVideoMetadata(){this.scrollWithPlayhead&&!this.isPlayheadInTimecodedView()&&!this.syncTimelineWithPlayheadInProgress&&(this.syncTimelineWithPlayheadInProgress=!0,this.syncTimelineWithPlayhead().subscribe(e=>{this.syncTimelineWithPlayheadInProgress=!1}))}addLane(e){if(this.timelineLanesMap.has(e.getId()))throw new Error(`TimelineLane with id=${e.getId()} already exist`);let t=this.timelineLanes.length<1,r={...F.POSITION_TOP_LEFT};t||(r.y=this.timelineLanes.map(s=>s.getRect().height).reduce((s,n)=>s+n,0)),e.setTimeline(this),e.setVideoController(this.videoController),e.setTimelinePosition(r),e.initCanvasNode(),this.timelineLanes.push(e),this.timelineLanesMap.set(e.getId(),e),this.bodyContentGroup.add(e.getCanvasNode()),this.settleLayout()}removeLane(e){if(!this.timelineLanesMap.has(e))throw new Error(`TimelineLane with id=${e} doesn't exist`);let t=this.timelineLanesMap.get(e);this.timelineLanes.splice(this.timelineLanes.findIndex(s=>s.getId()===e),1),this.timelineLanesMap.delete(e),t.clearContent(),t.destroy();let r={...F.POSITION_TOP_LEFT};this.timelineLanes.forEach(s=>{s.setTimelinePosition({...r}),r.y=r.y+s.getRect().height}),this.timelineLanes.forEach(s=>{s.onMeasurementsChange()}),this.settleLayout()}getScrollbar(){return this.scrollbar}addLanes(e){e.forEach(t=>this.addLane(t))}getLanes(){return[...this.timelineLanesMap.values()]}getLane(e){return this.timelineLanesMap.get(e)}getScrubberLane(){return this.getLane(La)}getMarkerLane(e){let t=this.getLane(e);return t instanceof Ws?t:void 0}getThumbnailLane(e){let t=this.getLane(e);return t instanceof Ks?t:void 0}getSubtitlesLane(e){let t=this.getLane(e);return t instanceof qs?t:void 0}getAudioTrackLane(e){let t=this.getLane(e);return t instanceof Fl?t:void 0}createMarkerLane(e){let t=new Ws(e);return this.addLane(t),t}createThumbnailLane(e){let t=new Ks(e);return this.addLane(t),t}createSubtitlesLane(e){let t=new qs(e);return this.addLane(t),t}isTimelineReady(){return this.videoController.isVideoLoaded()}addToTimecodedBaseGroup(e){this.timecodedBaseGroup.add(e)}addToTimecodedSurfaceGroup(e){this.timecodedSurfaceGroup.add(e)}addToTimecodedMarkersGroup(e){this.timecodedMarkersGroup.add(e)}addToTimecodedThumbnailsGroup(e){this.timecodedThumbnailsGroup.add(e)}addToTimecodedSubtitlesGroup(e){this.timecodedSubtitlesGroup.add(e)}addToTimecodedAudioGroup(e){this.timecodedAudioGroup.add(e)}constrainTimelinePosition(e){let t=this.getTimecodedGroupDimension();return e<0?0:e>t.width?t.width:e}timelinePositionToTime(e){let t=this.constrainTimelinePosition(e);return this.videoController.isVideoLoaded()?new Z(t).mul(this.videoController.getDuration()).div(this.getTimecodedGroupDimension().width).toNumber():0}timelinePositionToTimeFormatted(e){return this.videoController.isVideoLoaded()?this.videoController.formatTimestamp(this.timelinePositionToTime(e)):""}timelinePositionToFrame(e){return this.videoController.isVideoLoaded()?this.videoController.calculateTimeToFrame(this.timelinePositionToTime(e)):0}timeToTimelinePosition(e){return new Z(e).mul(this.getTimecodedGroupDimension().width).div(this.videoController.getDuration()).toNumber()}getConstrainedTimelineX(e){let t=this.getTimecodedGroupDimension(),r=this.getTimecodedContainerDimension();if(t.width<=r.width)return 0;{let s=r.width-t.width;return e<s?s:e>0?0:e}}getBodyGroupRect(){return{...this.bodyGroup.getPosition(),...this.bodyGroup.getSize()}}getLeftPanelRect(){return{...this.leftPanel.getPosition(),...this.leftPanel.getSize()}}getLeftPanelVisible(){return this.leftPanelVisible}getRightPanelRect(){return{...this.rightPanel.getSize(),...this.rightPanel.getPosition()}}getTimecodedContainerDimension(){return this.timecodedContainer.getSize()}getTimecodedContainerPosition(){return this.timecodedContainer.getPosition()}getTimecodedContainerRect(){return{...this.getTimecodedContainerDimension(),...this.getTimecodedContainerPosition()}}getTimecodedGroupDimension(){return this.timecodedGroup.getSize()}getTimecodedGroupPosition(){return this.timecodedGroup.getPosition()}getTimecodedGroupRect(){return{...this.timecodedGroup.getPosition(),...this.timecodedGroup.getSize()}}getTimecodedGroupHorizontalMeasurement(){return{x:this.timecodedGroup.x(),width:this.timecodedGroup.width()}}getRelativePointerPosition(){return this.timecodedGroup.getRelativePointerPosition()}getLayoutGroupDimension(){return this.layoutGroup.getSize()}getLayoutGroupPosition(){return this.layoutGroup.getPosition()}getRect(){return{...this.getLayoutGroupDimension(),...this.getLayoutGroupPosition()}}getVisiblePositionRange(){let e=Math.abs(this.timecodedGroup.x()),t=e+this.timecodedContainer.width();return{start:e,end:t}}isInVisiblePositionRange(e){let t=this.getVisiblePositionRange();return e>=t.start&&e<=t.end}isSnappedStart(){return this.getTimecodedGroupPosition().x===0}isSnappedEnd(){return this.getTimecodedContainerDimension().width-this.getTimecodedGroupDimension().width===this.getTimecodedGroupPosition().x}getVisibleTimeRange(){let e=this.getVisiblePositionRange(),t=this.timelinePositionToTime(e.start),r=this.timelinePositionToTime(e.end);return{start:t,end:r}}getZoomBaseline(){return this.zoomBaseline}getZoomMax(){return this.zoomMax}fetchThumbnailVttFile(){return this.thumbnailVttUrl?ls.create(this.thumbnailVttUrl,this.axiosConfig).pipe(ke(e=>(this.thumbnailVttFile=e,e)),yi((e,t)=>Se(void 0))):Se(void 0)}toggleLeftPanelVisible(e){this.leftPanelVisible=e,this.leftPanel.visible(e),this.settleLayout(),this.timelineLanes.forEach(t=>{t.onMeasurementsChange()}),this.headerTimecodeDisplay.setVisible(!e)}clearContent(){this.setThumbnailVttFile(void 0),this.timelineLanes.forEach(e=>{e.clearContent()}),this.zoomByPercent(this.zoomBaseline)}destroy(){this.timelineHTMLElement=void 0,this.videoController=void 0,this.thumbnailVttFile=void 0,pn(this.videoEventBreaker$);let e=[this.onScroll$,this.onZoom$];Vt(...e),bi(...e),[this.scrollbar,this.playheadHover,this.playhead,...this.timelineLanes,this.thumbnailHover,this.headerTimecodeDisplay].forEach(r=>{r&&r.destroy()}),super.destroy()}}class Qs{static timeToFrame(e,t){return t.mul(e).floor().toNumber()}static frameToTime(e,t){return new Z(e).dividedBy(t).toNumber()}}class ri{constructor(){this.resolveUserAgent()}static instance(){return ri._instance||(ri._instance=new ri),ri._instance}resolveUserAgent(){this._userAgent=window.navigator&&window.navigator.userAgent||"",this._isAndroid=/Android/i.test(this._userAgent),this._isFirefox=/Firefox/i.test(this._userAgent),this._isEdge=/Edg/i.test(this._userAgent),this._isChromium=/Chrome/i.test(this._userAgent)||/CriOS/i.test(this._userAgent),this._isChrome=!this.isEdge&&this.isChromium,this._isSafari=/Safari/i.test(this._userAgent)&&!this.isChrome&&!this.isAndroid&&!this.isEdge}get isSafari(){return this._isSafari}get isFirefox(){return this._isFirefox}get isEdge(){return this._isEdge}get isChromium(){return this._isChromium}get isChrome(){return this._isChrome}get isAndroid(){return this._isAndroid}}const tt=class{static formatVideoTimestamp(i,e){if(i<=0)return tt.VIDEO_ZERO_TIMESTAMP;const t=Math.floor(i/3600),r=Math.floor(i%3600/60),s=Math.floor(i%60);let n=new Z(Qs.timeToFrame(i,e)).mod(e).toNumber();return`${tt.padZero(t)}:${tt.padZero(r)}:${tt.padZero(s)}:${tt.padZero(n)}`}static padZero(i,e=2){return i.toString().padStart(e,"0")}};let en=tt;en.VIDEO_ZERO_TIMESTAMP=`${tt.padZero(0)}:${tt.padZero(0)}:${tt.padZero(0)}:${tt.padZero(0)}`;class Km{constructor(){this._state={playing:!1,paused:!0,waiting:!1,seeking:!1,buffering:!1,ended:!1},this.onChange$=new ti(this._state)}updateState(e){let t={...this._state,...e},r=this.compare(this._state,t)===0;this._state=t,r||this.onChange$.next(this._state)}compare(e,t){return e.playing===t.playing&&e.paused===t.paused&&e.waiting===t.waiting&&e.seeking===t.seeking&&e.buffering===t.buffering&&e.ended===t.ended?0:-1}get state(){return this._state}setPlaying(){this.updateState({playing:!0,paused:!1,waiting:!1,seeking:!1,buffering:!1,ended:!1})}setPaused(){this.updateState({playing:!1,paused:!0,waiting:!1,seeking:!1,buffering:!1,ended:!1})}setEnded(){this.updateState({playing:!1,paused:!0,waiting:!1,seeking:!1,buffering:!1,ended:!0})}set waiting(e){this.updateState({waiting:e})}set seeking(e){this.updateState({seeking:e,ended:!1})}set buffering(e){this.updateState({buffering:e})}}function Ra(i){let e;return typeof i=="string"?e=i:i instanceof st?(console.log(i),e=i.errors.map(t=>t.message).join(". ")):i instanceof Error?e=i.message:e="Unexpected error",e}function Jm(i){return{errorMap:(e,t)=>({message:i})}}const Be={PAUSE:"pause",WAITING:"waiting",PLAYING:"playing",TIMEUPDATE:"timeupdate",SEEKING:"seeking",SEEKED:"seeked",LOADEDDATA:"loadeddata",LOADEDMETEDATA:"loadedmetadata",ENDED:"ended",PROGRESS:"progress"};class Qm{constructor(e,t){if(this.browserProvider=ri.instance(),this.helpMenuGroups=[],this._isVideoLoaded=!1,this.frameDurationSpillOverCorrection=.001,this.syncLoopMaxIterations=20,this.seekInProgress=!1,this.videoStalledCheckIntervalMs=700,this.videoFrameCallback$=new ti(null),this.videoEventBreaker$=new V,this.onDestroy$=new V,this.seekBreaker$=new V,this.onVideoLoaded$=new ti(void 0),this.onVideoLoading$=new V,this.onPlay$=new V,this.onPause$=new V,this.onVideoTimeChange$=new V,this.onSeeking$=new V,this.onSeeked$=new V,this.onBuffering$=new V,this.onEnded$=new V,this.onAudioSwitched$=new V,this.onPlaybackState$=new V,this.onHelpMenuChange$=new ti(void 0),this.onVideoError$=new V,this.domController=e,this.crossorigin=t,this.videoElement=this.domController.videoElement,this.videoElement.crossOrigin=this.crossorigin,!this.videoElement)throw new Error("VideoController element not set");this.videoFrameCallback$.pipe(k(this.onDestroy$)).subscribe(r=>{r&&(this.seekInProgress||(this.isPlaying()?this.videoTimeChangeHandlerExecutor():this.isPaused()))})}loadVideo(e,t,r){try{return e=li.url()(e),t=_e.coerce.number().min(0).max(100).parse(t,Jm("Invalid frameRate")),this.onVideoLoading$.next({sourceUrl:e,frameRate:t}),this._isVideoLoaded=!1,this.video=void 0,this.detachVideoEventListeners(),this.videoLoad(e,t,r).pipe(ke(s=>{this.video=s,this.frameRateDecimal=new Z(this.video.frameRate),this.syncStepCurrentTimeMediaTime=0,this.playbackStateMachine=new Km,this.initEventHandlers(),this.startVideoFrameCallback(),this._isVideoLoaded=!0,this.onVideoLoaded$.next({video:this.video});let n=Number.parseFloat(this.getDuration().toFixed(3));return Number.isInteger(n*this.video.frameRate)&&(n=Number.parseFloat((n-this.frameDurationSpillOverCorrection).toFixed(3)),this.video.setCorrectedDuration(n)),this.getHls().on(Ze.Events.FRAG_LOADED,(a,o)=>{o.frag.endList&&o.frag.type=="main"&&this.getCorrectedDuration()>o.frag.start+o.frag.duration&&this.video.setCorrectedDuration(Number.isInteger(o.frag.start+o.frag.duration*this.video.frameRate)?o.frag.start+o.frag.duration-this.frameDurationSpillOverCorrection:o.frag.start+o.frag.duration)}),s}),yi((s,n)=>{let a=Ra(s);return this.onVideoError$.next({type:"VIDEO_LOAD_ERROR",message:a}),ia(()=>new Error(a))}))}catch(s){let n=Ra(s);return this.onVideoError$.next({type:"VIDEO_LOAD_ERROR",message:n}),ia(()=>new Error(n))}}initEventHandlers(){be(this.videoElement,Be.PAUSE).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.getCurrentTime()>=this.getCorrectedDuration()?this.getTotalFrames():this.getCurrentFrame(),this.getCurrentTime()<this.getCorrectedDuration()?this.seekToFrame(this.getCurrentTime()>=this.getCorrectedDuration()?this.getTotalFrames():this.getCurrentFrame()).subscribe(t=>{this.videoTimeChangeHandlerExecutor(),this.onPause$.next({})}):this.syncVideoFrames({}).subscribe(t=>{this.videoTimeChangeHandlerExecutor(),this.onPause$.next({})})}),be(this.videoElement,Be.WAITING).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.waiting=!0}),be(this.videoElement,Be.PLAYING).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.setPlaying(),this.videoStalledCheckLastCurrentTime=void 0}),be(this.videoElement,Be.PAUSE).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.setPaused(),this.videoStalledCheckLastCurrentTime=void 0}),be(this.videoElement,Be.PROGRESS).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.onBuffering$.next({bufferedTimespans:this.getBufferedTimespans()})}),be(this.videoElement,Be.ENDED).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.onEnded$.next({})}),this.playbackStateMachine.onChange$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.onPlaybackState$.next(e)}),this.onPlay$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.setPlaying(),this.videoStalledCheckLastCurrentTime=void 0}),this.onPause$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.setPaused(),this.videoStalledCheckLastCurrentTime=void 0}),this.onSeeking$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.seeking=!0}),this.onSeeked$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.seeking=!1}),this.onEnded$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.setEnded(),this.videoStalledCheckLastCurrentTime=void 0}),Xu(this.videoStalledCheckIntervalMs).pipe(k(this.videoEventBreaker$)).subscribe(e=>{let t=this.getCurrentTime();if(!this.videoStalledCheckLastCurrentTime){this.videoStalledCheckLastCurrentTime=t;return}if(this.playbackStateMachine.state.playing){let r=this.videoStalledCheckIntervalMs*.8/1e3*this.getPlaybackRate(),s=this.videoStalledCheckLastCurrentTime+r,n=t<s;this.playbackStateMachine.waiting=n,this.videoStalledCheckLastCurrentTime=t}})}getBufferedTimespans(){if(!this.isVideoLoaded())return[];let e=[],t=this.videoElement.buffered;for(let r=0;r<t.length;r++)e.push({start:t.start(r),end:t.end(r)});return e}startVideoFrameCallback(){let e=()=>{this.videoElement?this.videoFrameCallbackHandle=this.videoElement.requestVideoFrameCallback((r,s)=>{t({now:r,metadata:s})}):console.debug("Cannot call requestVideoFrameCallback, videoElement not found")},t=r=>{this.videoFrameCallback$.next(r),e()};e()}detachVideoEventListeners(){Ge(this.videoEventBreaker$),this.videoEventBreaker$=new V,this.videoElement&&this.videoFrameCallbackHandle&&this.videoElement.cancelVideoFrameCallback(this.videoFrameCallbackHandle)}syncVideoFrames(e){return console.debug("syncFrames - START",e),new re(t=>{let r=new ti(!1),s=new V,n=this.syncLoopMaxIterations;this.seekBreaker$.pipe(k(s)).subscribe(()=>{console.debug("%csyncFrames - seek breaker triggered","color: gray"),r.next(!0),a()});let a=()=>{Ge(s),t.next(!0),t.complete(),console.debug("%csyncFrames - END","color: gray")},o=h=>{r.pipe($e(1)).subscribe(l=>{l?console.debug("%csyncFrames - seek skipped, breaker already triggered","color: gray"):this._seekTimeFireAndForget(h)})};if(this.isPlaying())console.debug("%csyncFrames - SKIPPED: video is playing","color: gray"),a();else if(this.getCorrectedDuration()<=this.getCurrentTime())console.debug("%csyncFrames - SKIPPED: video exceeded duration","color: magenta"),a();else{let h=u=>{let c=this.getCurrentTime(),p=this.calculateTimeToFrame(c),f=u?u.metadata.mediaTime:void 0,m=f?this.calculateTimeToFrame(f):void 0;if(this.isPlaying())return console.debug("%csyncFrames - UNKNOWN: video is playing","color: gray"),!0;if(p===0)return console.debug(`%csyncFrames - OK: currentTimeFrame[${p}] === 0`,"color: green"),!0;if(e.seekToFrame){if(e.seekToFrame===p&&(p===m||!m))return console.debug(`%csyncFrames - OK: ((currentTimeFrame[${p}] === mediaTimeFrame[${m}]) || !mediaTimeFrame[${m}])`,"color: green"),!0}else if(p===m||!m)return console.debug(`%csyncFrames - OK: currentTimeFrame[${p}] === mediaTimeFrame[${m}]`,"color: green"),!0;return!1},l,d=u=>{let c=this.syncLoopMaxIterations-n;if(console.debug(`syncFrames.syncLoop - START (${c})`,{syncConditions:e,videoFrameCallbackData:u,dropped:this.videoElement.getVideoPlaybackQuality()}),this.isPlaying()){a();return}if(h(u)){a();return}let p=this.getCurrentTime(),f=this.calculateTimeToFrame(p),m=u?u.metadata.mediaTime:void 0,g=m?this.calculateTimeToFrame(m):void 0;if(n--<=0){console.debug(`%csyncFrames - TOO MANY SYNCs, EXITING.. : currentTime[${p}], mediaTime[${m}], currentTimeFrame[${f}], mediaTimeFrame[${g}]`,"color: red"),a();return}if(console.debug(`syncFrames - currentTime[${p}|${this.formatTimestamp(p)}], mediaTime[${m}|${this.formatTimestamp(m)}], currentTimeFrame[${f}], mediaTimeFrame[${g}], `),e.seekToFrame)if(l||(l=p),e.seekToFrame===f)if(f===g||!g)console.debug(`%csyncFrames - OK: ((currentTimeFrame[${f}] === mediaTimeFrame[${g}]) || !mediaTimeFrame[${g}])`,"color: green"),a();else{console.debug(`%csyncFrames - CORRECTION SEEK TO FRAME; currentTimeFrame[${f}] ${f>g?">":"<"} mediaTimeFrame[${g}]`,"color: red");let _=Math.abs(f-g);console.debug(`%csyncFrames - frameDiff: ${_}`,"color: orange");let w=this.syncStepCurrentTimeMediaTime*(f>g?1:-1);o(Z.add(p,w).toNumber())}else{console.debug(`%csyncFrames - CORRECTION SEEK TO FRAME; syncConditions.seekToFrame[${e.seekToFrame}] !== currentTimeFrame[${f}] | seekToFrameTimeBaseline=${l}`,"color: red");let _=Math.abs(e.seekToFrame-f),w=_*this.video.frameDuration,T=(e.seekToFrame>=f?Z.add(l,w):Z.sub(l,w)).toNumber();l=T,console.debug(`%csyncFrames - frameDiff: ${_}`,"color: orange"),console.debug(`%csyncFrames - frameCorrectionTime: ${w}`,"color: orange"),console.debug(`%csyncFrames - seekTo: ${T}`,"color: orange"),o(T)}else f===g||!g?(console.debug(`%csyncFrames - OK: currentTimeFrame[${f}] === mediaTimeFrame[${g}]`,"color: green"),a()):(console.debug(`%csyncFrames - CORRECTION; currentTimeFrame[${f}] ${f>g?">":"<"} mediaTimeFrame[${g}]`,"color: red"),c===0?o(p):f>g?o(Z.add(p,this.syncStepCurrentTimeMediaTime).toNumber()):o(m+this.syncStepCurrentTimeMediaTime));console.debug("syncFrames.syncLoop - END")};this.videoFrameCallback$.pipe(Ju((e.seekToFrame,0)),k(s)).subscribe(u=>{console.debug("syncFrames.syncLoop - videoFrameCallback$ trigger",u),d(u)})}})}seekTimeAndSync(e,t={}){return new re(r=>{this.seekInProgress&&(Ge(this.seekBreaker$),this.seekBreaker$=new V),this.seekInProgress=!0,isNaN(e)||(e=e<0?0:e>this.getDuration()?this.getDuration():e,be(this.videoElement,Be.SEEKING).pipe(k(this.seekBreaker$),$e(1)).subscribe(s=>{this.onSeeking$.next({newTime:e,currentTime:this.getCurrentTime()})}),be(this.videoElement,Be.SEEKED).pipe(k(this.seekBreaker$),$e(1)).subscribe(s=>{this.syncVideoFrames(t).subscribe(n=>{this.getCorrectedDuration()>this.getHTMLVideoElement().duration&&this.video.setCorrectedDuration(Number.isInteger(this.getHTMLVideoElement().duration*this.video.frameRate)?this.getHTMLVideoElement().duration-this.frameDurationSpillOverCorrection:this.getHTMLVideoElement().duration);let a=()=>{this.seekInProgress=!1,r.next(!0),r.complete(),this.videoTimeChangeHandlerExecutor()};this.getCurrentTime()>this.getCorrectedDuration()?this.seekTimeWithoutSync(this.getCorrectedDuration()).pipe(k(this.seekBreaker$),$e(1)).subscribe(()=>{this.onEnded$.next({}),a()}):(this.onSeeked$.next({currentTime:this.getCurrentTime()}),a())})}),console.debug(`Seeking to timestamp: ${e} ${this.formatTimestamp(e)}`),this.setCurrentTime(e))})}seekTimeWithoutSync(e){return new re(t=>{this.seekInProgress&&(Ge(this.seekBreaker$),this.seekBreaker$=new V),this.seekInProgress=!0,isNaN(e)||(e=e<0?0:e>this.getDuration()?this.getDuration():e,be(this.videoElement,Be.SEEKING).pipe(k(this.seekBreaker$),$e(1)).subscribe(r=>{this.onSeeking$.next({newTime:e,currentTime:this.getCurrentTime()})}),be(this.videoElement,Be.SEEKED).pipe(k(this.seekBreaker$),$e(1)).subscribe(r=>{this.onSeeked$.next({currentTime:this.getCurrentTime()}),this.seekInProgress=!1,t.next(!0),t.complete(),this.videoTimeChangeHandlerExecutor()}),console.debug(`Seeking to timestamp: ${e} ${this.formatTimestamp(e)}`),this.setCurrentTime(e))})}_seekTimeFireAndForget(e){if(!isNaN(e)){let t=this.getCurrentTime();e=e<0?0:e>this.getDuration()?this.getDuration():e;let r=e===t?"NONE":e>t?"FORWARD":"BACKWARD",s=Z.sub(t,e).abs();console.debug(`Seeking from currentTime[${t}] to newTime[${e}], direction: ${r} ${s.toNumber()}`),this.setCurrentTime(e)}}_seekTimeAndSyncNoEmitEvents(e){return this.isPlaying()?Se(!1):new re(t=>{isNaN(e)||(e=e<0?0:e>this.getDuration()?this.getDuration():e,be(this.videoElement,Be.SEEKED).pipe(ui()).subscribe(r=>{this.syncVideoFrames({}).subscribe(s=>{t.next(!0),t.complete(),this.videoTimeChangeHandlerExecutor()})}),console.debug(`Seeking ${e}`),this.setCurrentTime(e))})}seekFromCurrentTimeAndSync(e,t={}){let r=this.getCurrentTime();t.currentTime&&(r=t.currentTime);let s=Z.add(r,e).toNumber(),n;t.seekDirection?n=t.seekDirection:n=s===r?"NONE":s>r?"FORWARD":"BACKWARD";let a=Z.sub(r,s).abs().toNumber();return console.debug(`Seeking from currentTime ${r} to ${s}, direction: ${n} ${a}`),this.seekTimeAndSync(s,t)}setCurrentTime(e){this.videoElement.currentTime=e}getFrameRateDecimal(){return this.frameRateDecimal}_seekToFrame(e){if(!this.isPlaying()&&!isNaN(e)){if(console.debug(`Seeking to frame: ${e}`),e<=0)return this.seekTimeAndSync(0,{});{let t=this.calculateFrameToTime(e)+new Z(this.frameDurationSpillOverCorrection).toNumber(),r=this.calculateTimeToFrame(t);return r!==e&&e!=this.getCorrectedDuration()*this.getFrameRate()?(console.error(`Frame numbers don't match. Wanted: ${e}, calculated: ${r}`),Se(!1)):this.seekTimeAndSync(t,{seekToFrame:e,seekToTimestamp:t,currentTime:this.getCurrentTime()}).pipe(ke(s=>s))}}}_seekFromCurrentFrame(e){let t=this.getCurrentFrame(),r=t+e;if(console.debug(`seekFromCurrentFrame - Current frame: ${t}, wanted frame: ${r}`),t!==r){if(r<=0)return this._seekToFrame(0);if(r>=this.getTotalFrames()||r>=this.getCorrectedDuration()*this.getFrameRate()&&!this.playbackStateMachine.state.ended)return this._seekToFrame(this.getCorrectedDuration()*this.getFrameRate());if(r>=this.getTotalFrames()||r>=this.getCorrectedDuration()*this.getFrameRate()&&this.playbackStateMachine.state.ended)return Se(!1);{let s=this.calculateFrameToTime(e),n=t/this.getFrameRate()+this.frameDurationSpillOverCorrection;return this.seekFromCurrentTimeAndSync(s,{seekToFrame:r,currentTime:n,seekDirection:e>0?"FORWARD":"BACKWARD"}).pipe(ke(a=>a))}}else return Se(!0)}videoTimeChangeHandlerExecutor(){let e=this.getCurrentTime(),t=this.getCurrentFrame();this.onVideoTimeChange$.next({currentTime:e,frame:t})}getPlaybackState(){return this.playbackStateMachine.state}getVideo(){return this.isVideoLoaded()?this.video:void 0}getHTMLVideoElement(){return this.videoElement}calculateTimeToFrame(e){return Qs.timeToFrame(e,this.getFrameRateDecimal())}calculateFrameToTime(e){return Qs.frameToTime(e,this.getFrameRateDecimal())}play(){this.isVideoLoaded()&&!this.isPlaying()&&this.videoElement.play().then(()=>{this.onPlay$.next({})})}pause(){this.isVideoLoaded()&&this.isPlaying()&&this.videoElement.pause()}togglePlayPause(){this.isPlaying()?this.pause():this.play()}isPlaying(){return this.isVideoLoaded()&&this.videoElement.currentTime>0&&this.videoElement.currentTime<this.getDuration()&&!this.videoElement.paused&&!this.videoElement.ended&&this.videoElement.readyState>this.videoElement.HAVE_CURRENT_DATA}isPaused(){return!this.isPlaying()}isSeeking(){return this.seekInProgress}getCurrentTime(){return this.isVideoLoaded()?this.videoElement.currentTime:0}getPlaybackRate(){return this.isVideoLoaded()?this.videoElement.playbackRate:0}setPlaybackRate(e){if(this.isVideoLoaded()){try{e=_e.coerce.number().min(.1).max(16).default(1).parse(e)}catch{e=1}this.videoElement.playbackRate=e}}getVolume(){return this.isVideoLoaded()?this.videoElement.volume:0}setVolume(e){if(this.isVideoLoaded()){try{e=_e.coerce.number().min(0).max(1).default(1).parse(e)}catch{e=1}this.videoElement.volume=e}}getDuration(){return this.isVideoLoaded()?this.video.duration:0}getCorrectedDuration(){return this.isVideoLoaded()?this.video.correctedDuration:0}getFrameRate(){return this.isVideoLoaded()?this.video.frameRate:0}getTotalFrames(){return this.isVideoLoaded()?this.video.totalFrames:0}getCurrentFrame(){return this.isVideoLoaded()?this.calculateTimeToFrame(this.getCurrentTime()):0}seekToFrame(e){return!this.isVideoLoaded()||this.playbackStateMachine.state.ended&&e>=this.getCurrentFrame()?Se(!1):(e=_e.coerce.number().min(0).max(this.getTotalFrames()).parse(e),this._seekToFrame(e))}seekFromCurrentFrame(e){return this.isVideoLoaded()?(e=_e.coerce.number().parse(e),this._seekFromCurrentFrame(e)):Se(!1)}seekPreviousFrame(){return this.isVideoLoaded()?this.seekFromCurrentFrame(-1):Se(!1)}seekNextFrame(){return this.isVideoLoaded()?this.seekFromCurrentFrame(1):Se(!1)}seekToTimestamp(e){return!this.isVideoLoaded()||this.playbackStateMachine.state.ended&&e>=this.getCorrectedDuration()?Se(!1):(e=_e.coerce.number().parse(e),e>this.getCorrectedDuration()&&(e=this.getCorrectedDuration()),this.seekTimeAndSync(e,{seekToTimestamp:e,seekDirection:e===this.getCurrentTime()?"NONE":e>this.getCurrentTime()?"FORWARD":"BACKWARD"}))}formatTimestamp(e){return this.isVideoLoaded()?(e=_e.coerce.number().min(0).parse(e),en.formatVideoTimestamp(e,this.getFrameRateDecimal())):en.VIDEO_ZERO_TIMESTAMP}mute(){this.isVideoLoaded()&&(this.videoElement.muted=!0)}unmute(){this.isVideoLoaded()&&(this.videoElement.muted=!1)}isFullscreen(){return this.isVideoLoaded()?this.domController.isFullscreen():!1}toggleFullscreen(){this.isVideoLoaded()&&this.domController.toggleFullscreen(this.videoElement)}getAudioTracks(){throw new Error("unsupported")}getCurrentAudioTrack(){throw new Error("unsupported")}setAudioTrack(e){throw new Error("unsupported")}isVideoLoaded(){return this._isVideoLoaded}getHls(){throw new Error("Unsupported or video not loaded with Hls.js")}addHelpMenuGroup(e){this.helpMenuGroups.push(e),this.onHelpMenuChange$.next()}getHelpMenuGroups(){return this.helpMenuGroups}destroy(){pn(this.videoEventBreaker$,this.seekBreaker$),Vt(this.videoFrameCallback$);let e=[this.onVideoLoaded$,this.onVideoLoading$,this.onPlay$,this.onPause$,this.onVideoTimeChange$,this.onSeeking$,this.onSeeked$,this.onBuffering$,this.onEnded$,this.onAudioSwitched$,this.onPlaybackState$,this.onHelpMenuChange$,this.onVideoError$];Vt(...e),bi(...e);try{this.getHls()&&(this.getHls().removeAllListeners(),this.getHls().destroy())}catch(t){console.error(t)}Ge(this.onDestroy$),this.videoElement=null,this.domController=null,this._isVideoLoaded=!1,this.playbackStateMachine=null}}class eg{constructor(e,t,r,s){this._element=e,this._sourceUrl=t,this._frameRate=r,this._duration=s,this._totalFrames=new Z(this._duration).mul(this._frameRate).ceil().toNumber(),this._frameDuration=new Z(1).div(this._frameRate).toNumber()}get element(){return this._element}get sourceUrl(){return this._sourceUrl}get frameRate(){return this._frameRate}get duration(){return this._duration}get totalFrames(){return this._totalFrames}get frameDuration(){return this._frameDuration}get correctedDuration(){return this._correctedDuration}setCorrectedDuration(e){console.debug(`%cVideo duration correction: initialDuration:${this.duration} > updatedDuration:${e} `,"color: magenta"),this._correctedDuration=e}}class tg extends Qm{constructor(e,t){super(e,t),Ze.isSupported()?console.debug("video load with hls.js"):console.error("hls is not supported through MediaSource extensions");let r={...Ze.DefaultConfig,enableWorker:!1};this.hls=new Ze(r)}videoLoad(e,t,r){return new re(s=>{this.hls.on(Ze.Events.ERROR,function(h,l){l.type;let d=l.details;l.fatal,d.includes("audioTrackLoadError")||(s.error(`Error loading video. Hls error details: ${d}`),s.complete())});let n=new re(h=>{this.hls.once(Ze.Events.MEDIA_ATTACHED,function(l,d){console.debug("video element and hls.js are now bound together"),h.next(!0),h.complete()})}),a=new re(h=>{this.hls.once(Ze.Events.MANIFEST_PARSED,function(l,d){console.debug("manifest loaded, found "+d.levels.length+" quality level"),h.next(!0),h.complete()})}),o=be(this.videoElement,Be.LOADEDDATA).pipe(ui());$u([n,a,o]).pipe(ui()).subscribe(h=>{r=r&&_e.coerce.number().parse(r),r=r||this.videoElement.duration;let l=new eg(this.videoElement,e,t,r);s.next(l),s.complete()}),this.hls.loadSource(e),this.hls.attachMedia(this.videoElement)})}initEventHandlers(){super.initEventHandlers(),this.hls.on(Ze.Events.ERROR,function(e,t){t.type,t.details,t.fatal,console.error(e,t),t.details===Ze.ErrorDetails.BUFFER_STALLED_ERROR||t.details===Ze.ErrorDetails.BUFFER_APPEND_ERROR||(t.details,Ze.ErrorDetails.BUFFER_APPENDING_ERROR)})}getAudioTracks(){return this.isVideoLoaded?this.hls.audioTracks:null}getCurrentAudioTrack(){return this.getAudioTracks()[this.hls.audioTrack]}setAudioTrack(e){if(!this.isVideoLoaded)return null;let t=this.hls.audioTrack;this.hls.audioTrack=e;let r=this.hls.audioTrack;r>=0&&t!==r&&this.onAudioSwitched$.next({audioTrack:this.getCurrentAudioTrack()})}getHls(){return this.hls}}class ig{constructor(e){this.hidden=!0,this.id=e.id,this.src=e.src,this.default=e.default,this.label=e.label,this.language=e.language,this.cues=[]}}class rg extends ig{constructor(e){super(e)}}class xn{constructor(e){this.subtitlesTracks=new Map,this.onCreate$=new V,this.onRemove$=new V,this.onShow$=new V,this.onHide$=new V,this.videoController=e,this.videoController.onVideoLoaded$.pipe(We(t=>!!t)).subscribe(t=>{this.removeAllTracks()})}getDomTextTrack(e){if(this.videoController&&this.videoController.getHTMLVideoElement()){let t=this.videoController.getHTMLVideoElement().textTracks.getTrackById(e.id);if(t.kind==="subtitles")return t}}removeDomTextTrack(e){return this.getDomTextTrack(e)?(this.videoController.getHTMLVideoElement().querySelectorAll("track").forEach(r=>{r.getAttribute("id")===e.id&&r.parentElement.removeChild(r)}),!0):!1}static createHTMLTrackElement(e){let t=document.createElement("track");return t.kind="subtitles",t.id=e.id,t.label=e.label,t.srclang=e.language,t.src=e.src,t.default=e.default,t}createVttTrack(e){return this.videoController.isVideoLoaded?new re(t=>{let r=new rg({...e});this.subtitlesTracks.has(r.id)&&this.removeTrack(r.id),r.element=xn.createHTMLTrackElement(r),be(r.element,"load").pipe(ui()).subscribe(n=>{this.subtitlesTracks.set(r.id,r),t.next(r),t.complete(),this.onCreate$.next({textTrack:r})}),this.videoController.getHTMLVideoElement().appendChild(r.element);let s=this.getDomTextTrack(r);s.mode="hidden"}):Se(void 0)}getTracks(){if(this.videoController.isVideoLoaded)return[...this.subtitlesTracks.values()]}removeAllTracks(){this.videoController.isVideoLoaded&&this.subtitlesTracks.forEach((e,t)=>{this.removeTrack(e.id)})}removeTrack(e){if(!this.videoController.isVideoLoaded)return;let t=this.subtitlesTracks.get(e);t&&(this.subtitlesTracks.delete(e),this.removeDomTextTrack(t),this.onRemove$.next({}))}getCurrentTrack(){return this.currentTrack}showTrack(e=void 0){if(!this.videoController.isVideoLoaded||(e=e||(this.getCurrentTrack()?this.getCurrentTrack().id:void 0),!e))return;let t=this.subtitlesTracks.get(e);if(t){let r=this.getDomTextTrack(t);if(r){for(let s=0;s<this.videoController.getHTMLVideoElement().textTracks.length;s++){let n=this.videoController.getHTMLVideoElement().textTracks[s];n.mode="hidden"}r.mode="showing",t.hidden=!1,this.currentTrack=t,this.onShow$.next({})}}}hideTrack(e=void 0){if(!this.videoController.isVideoLoaded||(e=e||(this.getCurrentTrack()?this.getCurrentTrack().id:void 0),!e))return;let t=this.subtitlesTracks.get(e);if(t){let r=this.getDomTextTrack(t);r&&(r.mode="hidden",t.hidden=!0,this.onHide$.next({}))}}destroy(){this.removeAllTracks();let e=[this.onCreate$,this.onRemove$,this.onShow$,this.onHide$];Vt(...e),bi(...e),this.currentTrack=void 0,this.videoController=void 0}}var tn={},sg={get exports(){return tn},set exports(i){tn=i}};(function(i){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function s(h,l,d){this.fn=h,this.context=l,this.once=d||!1}function n(h,l,d,u,c){if(typeof d!="function")throw new TypeError("The listener must be a function");var p=new s(d,u||h,c),f=t?t+l:l;return h._events[f]?h._events[f].fn?h._events[f]=[h._events[f],p]:h._events[f].push(p):(h._events[f]=p,h._eventsCount++),h}function a(h,l){--h._eventsCount===0?h._events=new r:delete h._events[l]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],d,u;if(this._eventsCount===0)return l;for(u in d=this._events)e.call(d,u)&&l.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(d)):l},o.prototype.listeners=function(l){var d=t?t+l:l,u=this._events[d];if(!u)return[];if(u.fn)return[u.fn];for(var c=0,p=u.length,f=new Array(p);c<p;c++)f[c]=u[c].fn;return f},o.prototype.listenerCount=function(l){var d=t?t+l:l,u=this._events[d];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,d,u,c,p,f){var m=t?t+l:l;if(!this._events[m])return!1;var g=this._events[m],_=arguments.length,w,b;if(g.fn){switch(g.once&&this.removeListener(l,g.fn,void 0,!0),_){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,d),!0;case 3:return g.fn.call(g.context,d,u),!0;case 4:return g.fn.call(g.context,d,u,c),!0;case 5:return g.fn.call(g.context,d,u,c,p),!0;case 6:return g.fn.call(g.context,d,u,c,p,f),!0}for(b=1,w=new Array(_-1);b<_;b++)w[b-1]=arguments[b];g.fn.apply(g.context,w)}else{var T=g.length,L;for(b=0;b<T;b++)switch(g[b].once&&this.removeListener(l,g[b].fn,void 0,!0),_){case 1:g[b].fn.call(g[b].context);break;case 2:g[b].fn.call(g[b].context,d);break;case 3:g[b].fn.call(g[b].context,d,u);break;case 4:g[b].fn.call(g[b].context,d,u,c);break;default:if(!w)for(L=1,w=new Array(_-1);L<_;L++)w[L-1]=arguments[L];g[b].fn.apply(g[b].context,w)}}return!0},o.prototype.on=function(l,d,u){return n(this,l,d,u,!1)},o.prototype.once=function(l,d,u){return n(this,l,d,u,!0)},o.prototype.removeListener=function(l,d,u,c){var p=t?t+l:l;if(!this._events[p])return this;if(!d)return a(this,p),this;var f=this._events[p];if(f.fn)f.fn===d&&(!c||f.once)&&(!u||f.context===u)&&a(this,p);else{for(var m=0,g=[],_=f.length;m<_;m++)(f[m].fn!==d||c&&!f[m].once||u&&f[m].context!==u)&&g.push(f[m]);g.length?this._events[p]=g.length===1?g[0]:g:a(this,p)}return this},o.prototype.removeAllListeners=function(l){var d;return l?(d=t?t+l:l,this._events[d]&&a(this,d)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,i.exports=o})(sg);const ng={OMAKASE_SUBTITLES_HIDE:"omakaseSubtitlesHide",OMAKASE_TIMELINE_ZOOM:"omakaseTimelineZoom",OMAKASE_VIDEO_LOADED:"omakaseVideoLoaded",OMAKASE_VIDEO_PAUSE:"omakaseVideoPause",OMAKASE_VIDEO_PLAY:"omakaseVideoPlay",OMAKASE_VIDEO_SEEKED:"omakaseVideoSeeked",OMAKASE_VIDEO_SEEKING:"omakaseVideoSeeking",OMAKASE_VIDEO_BUFFERING:"omakaseVideoBuffering",OMAKASE_VIDEO_ENDED:"omakaseVideoEnded",OMAKASE_VIDEO_TIME_CHANGE:"omakaseVideoTimeChange",OMAKASE_VIDEO_AUDIO_SWITCHED:"omakaseVideoAudioSwitched",OMAKASE_AUDIO_SWITCHED:"omakaseAudioSwitched",OMAKASE_SUBTITLES_CREATE:"omakaseSubtitlesCreate",OMAKASE_SUBTITLES_REMOVE:"omakaseSubtitlesRemove",OMAKASE_SUBTITLES_SHOW:"omakaseSubtitlesShow",OMAKASE_TIMELINE_SCROLL:"omakaseTimelineScroll"};class ag{constructor(e){this.onAudioSwitched$=new V,this.videoController=e}getAudioTracks(){return this.videoController.getAudioTracks()}getCurrentAudioTrack(){return this.videoController.getCurrentAudioTrack()}setAudioTrack(e){let t=this.getCurrentAudioTrack();this.videoController.setAudioTrack(e);let r=this.getCurrentAudioTrack();t!==r&&this.onAudioSwitched$.next({audioTrack:r})}destroy(){}}class Pi{static isFullscreenEnabled(){const e=document;return e.fullscreenEnabled||e.webkitFullscreenEnabled||!!e.webkitCancelFullScreen||e.mozFullScreenEnabled||e.msFullscreenEnabled||!1}static isFullscreen(){const e=document;return!!(e.fullscreenElement||e.webkitFullscreenElement||e.webkitCurrentFullScreenElement||e.mozFullScreenElement||e.msFullscreenElement)}static requestFullscreen(e,t){const r=e??document.documentElement,s=r.requestFullscreen||r.webkitRequestFullscreen||r.webkitRequestFullScreen||r.mozRequestFullScreen||r.msRequestFullscreen;if(!s)throw new Error("Unsupported");return s.call(r,t)}static exitFullscreen(){const e=document,t=e.exitFullscreen||e.webkitExitFullscreen||e.webkitCancelFullScreen||e.mozCancelFullScreen||e.msExitFullscreen;if(!t)throw new Error("Unsupported");return t.call(e)}}const fe={player:"omakase-player",playerWrapper:"omakase-player-wrapper",video:"omakase-video",videoControls:"omakase-video-controls",buttonPlay:"omakase-button-play",buttonPause:"omakase-button-pause",buttonLoading:"omakase-button-loading",buttonError:"omakase-button-error",buttonReplay:"omakase-button-replay",buttonHelp:"omakase-help-button",help:"omakase-help",helpMenu:"omakase-help-menu",errorMessage:"omakase-error-message"};class og{constructor(e){this._playerHTMLElementId=e,this.divPlayer=this.getElementById(this._playerHTMLElementId),this.createDom()}createDom(){this.divPlayer.classList.add(`${fe.player}`),this.divPlayer.innerHTML=`<div class="${fe.playerWrapper}">
47
+ `)}function Aa(i){const e=(i%1).toFixed(3);i=Math.round(i-e);const t=Math.floor(i/3600),r=Math.floor((i-t*3600)/60),s=i-t*3600-r*60;return`${`${_r(t,2)}:`}${_r(r,2)}:${_r(s,2)}.${_r(e*1e3,3)}`}var Pm={hlsSegment:Sm,hlsSegmentPlaylist:Tm};const Am=Rl.parse,Mm=vm.compile,Om=Nl.segment,Lm=Pm;var Rm={parse:Am,compile:Mm,segment:Om,hls:Lm};class Cn{constructor(e,t){this.cues=new Map,this.cuesKeysSorted=[],this.url=e,this.axiosConfig=t}fetch(){return tr(am(this.getUrl(),this.axiosConfig)).pipe(ke(e=>{let t=e.data;try{return Rm.parse(t,{strict:!0,meta:!0}).cues.forEach(s=>{let n=this.mapCue(s);this.cues.set(n.startTime,n),this.cuesKeysSorted.push(n.startTime)}),this.cuesKeysSorted.sort((s,n)=>s-n),!0}catch(r){return console.error(r),!1}}))}getUrl(){return this.url}hasCues(){return this.cues&&this.cues.size>0}findCue(e){let t=this.findCues(e,e);if(t&&t.length===1)return t[0]}findCues(e,t){let r=this.findCueIndex(e),s=this.findCueIndex(t);return s===-1?[]:this.cuesKeysSorted.slice(r,s+1).map(n=>this.cues.get(n))}getCues(){return[...this.cues.values()]}findCueIndex(e){let t=0,r=this.cuesKeysSorted.length-1;for(;t<=r;){const s=Math.floor((t+r)/2);if(this.cuesKeysSorted[s]===e)return s;this.cuesKeysSorted[s]<e?t=s+1:r=s-1}return r===-1&&(r=0),r}}class En extends Cn{constructor(e,t){super(e,t)}static create(e,t){let r=new En(e,t);return r.fetch().pipe(ke(s=>r))}mapCue(e){return{id:e.identifier,startTime:new Z(e.start).toDecimalPlaces(3).toNumber(),endTime:new Z(e.end).toDecimalPlaces(3).toNumber(),text:e.text}}}const Ma={listening:!0,style:{height:20,fill:"rgba(255,73,145)",opacity:1,visible:!0}};class Im extends et{constructor(e,t){super({...Ma,...e,style:{...Ma.style,...e.style}}),this.textTrackCue=this.config.textTrackCue,this.x=this.config.x,this.width=this.config.width,this.listening=this.config.listening,this.subtitlesLane=t,this.subtitlesLane.onSettleLayout$.pipe(k(this.onDestroy$)).subscribe(()=>{let r=this.subtitlesLane.resolveItemHorizontalMeasurement(this.getTextTrackCue());this.setHorizontalMeasurement(r)})}createCanvasNode(){return this.group=new M.Group({x:this.x,y:0,width:this.width,height:this.style.height,visible:this.style.visible,listening:this.listening}),this.backgroundRect=new M.Rect({x:0,y:0,width:this.group.width(),height:this.group.height(),fill:this.style.fill,opacity:this.style.opacity,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1,hitStrokeWidth:0}),this.group.add(this.backgroundRect),this.group}onMeasurementsChange(){this.backgroundRect.size(this.group.getSize())}setPosition(e){this.x=e.x,this.isInitialized()&&this.group.position({x:this.x,y:0})}getPosition(){return this.group.getPosition()}getDimension(){return this.group.getSize()}getRect(){return{...this.getPosition(),...this.getDimension()}}getHorizontalMeasurement(){return{x:this.x,width:this.width}}setHorizontalMeasurement(e){this.x=e.x,this.width=e.width,this.isInitialized()&&this.group.setAttrs({x:this.x,width:this.width}),this.onMeasurementsChange()}setVisible(e){this.style={visible:e},this.isInitialized()&&this.group.visible(e)}getTextTrackCue(){return this.textTrackCue}setTextTrackCue(e){this.textTrackCue=e}compareTo(e){return this.textTrackCue&&e&&this.getTextTrackCue().id===e.getTextTrackCue().id&&this.getTextTrackCue().startTime===e.getTextTrackCue().startTime&&this.getTextTrackCue().endTime===e.getTextTrackCue().endTime?0:-1}destroy(){this.textTrackCue=void 0,this.subtitlesLane=void 0,super.destroy()}}const Nm={...rr,height:40,paddingTop:0,paddingBottom:0,subtitlesLaneItemOpacity:.9,subtitlesLaneItemFill:"rgba(255,73,145)"};class qs extends sr{constructor(e){super({...e,style:{...Nm,...e.style}}),this.subtitlesLaneItemsMap=new Map,this.onSettleLayout$=new V,this._subtitlesVttUrl=this.config.subtitlesVttUrl}createCanvasNode(){return super.createCanvasNode(),this.timecodedGroup=new M.Group({...this.timelinePosition,width:this.timeline.getTimecodedGroupDimension().width,height:this.bodyGroup.height()}),this.timecodedEventCatcher=wi.createEventCatcher({width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.subtitlesLaneItemsGroup=new M.Group({...F.POSITION_TOP_LEFT,y:this.style.paddingTop,width:this.timecodedGroup.width(),height:this.timecodedGroup.height()-(this.style.paddingTop+this.style.paddingBottom)}),this.timecodedGroup.add(this.timecodedEventCatcher),this.timecodedGroup.add(this.subtitlesLaneItemsGroup),this.timeline.addToTimecodedSubtitlesGroup(this.timecodedGroup),this.bodyGroup}settleLayout(){super.settleLayout(),this.timecodedGroup.setAttrs({...this.timelinePosition});let e=this.timeline.getTimecodedGroupHorizontalMeasurement();[this.timecodedGroup,this.timecodedEventCatcher,this.subtitlesLaneItemsGroup].forEach(t=>{t.width(e.width)}),this.onSettleLayout$.next()}afterCanvasNodeInit(){super.afterCanvasNodeInit(),this.fetchAndCreateSubtitles()}clearContent(){this.subtitlesVttFile=void 0,this.clearItems()}clearItems(){this.subtitlesLaneItemsMap.forEach(e=>e.destroy()),this.subtitlesLaneItemsMap.clear(),this.subtitlesLaneItemsGroup.destroyChildren()}createEntities(){if(!this.isVttLoaded())return;this.clearItems(),this.subtitlesVttFile.getCues().forEach(t=>{let r=this.resolveItemHorizontalMeasurement(t),s=new Im({...r,textTrackCue:t,style:{height:this.subtitlesLaneItemsGroup.height(),fill:this.style.subtitlesLaneItemFill,opacity:this.style.subtitlesLaneItemOpacity}},this);this.subtitlesLaneItemsMap.set(t.startTime,s),this.subtitlesLaneItemsGroup.add(s.initCanvasNode())})}resolveItemHorizontalMeasurement(e){let t=this.timeline.constrainTimelinePosition(this.timeline.timeToTimelinePosition(e.startTime)),r=this.timeline.constrainTimelinePosition(this.timeline.timeToTimelinePosition(e.endTime));return{x:t,width:r-t}}fetchAndCreateSubtitles(){this.fetchSubtitlesVttFile(this._subtitlesVttUrl).pipe($e(1)).subscribe(e=>{this.subtitlesVttFile=e,this.createEntities()})}fetchSubtitlesVttFile(e){return e?En.create(e).pipe(ke(t=>t),yi((t,r)=>Se(void 0))):Se(void 0)}isVttLoaded(){return!!this.subtitlesVttFile}get subtitlesVttUrl(){return this._subtitlesVttUrl}set subtitlesVttUrl(e){this._subtitlesVttUrl=e,this.clearContent(),this.fetchAndCreateSubtitles()}}const Dm={listening:!1,style:{...F.POSITION_TOP_LEFT,...F.DIMENSION_ZERO,stroke:"rgba(255,73,145)",strokeWidth:5,visible:!1}};class Ys extends et{constructor(e){super(_i(e,Dm)),this.onClick$=new V,this.onMouseOver$=new V,this.onMouseMove$=new V,this.onMouseOut$=new V,this.onMouseLeave$=new V,this.listening=this.config.listening}createCanvasNode(){return this.group=new M.Group({x:this.style.x,y:this.style.y,width:this.style.width,height:this.style.height,visible:this.style.visible,listening:this.listening}),this.backgroundRect=new M.Rect({x:0,y:0,width:this.group.width(),height:this.group.height(),strokeWidth:this.style.strokeWidth,stroke:this.style.stroke}),this.group.add(this.backgroundRect),this.group}afterCanvasNodeInit(){this.group.on("click",e=>{this.onClick$.next({thumbnail:this})}),this.group.on("mouseover",e=>{this.onMouseOver$.next({thumbnail:this})}),this.group.on("mousemove",e=>{this.onMouseMove$.next({thumbnail:this})}),this.group.on("mouseout",e=>{this.onMouseOut$.next({thumbnail:this})}),this.group.on("mouseleave",e=>{this.onMouseLeave$.next({thumbnail:this})})}destroy(){this.thumbnailVttCue=void 0;for(let t in this.group.eventListeners)this.group.removeEventListener(t);let e=[this.onClick$,this.onMouseOver$,this.onMouseMove$,this.onMouseOut$,this.onMouseLeave$];Vt(...e),bi(...e),super.destroy()}onMeasurementsChange(){this.backgroundRect.size(this.group.getSize())}setImage(e){this.image&&this.image.destroy(),this.image=e,this.style={width:e.width(),height:e.height()},this.group.setAttrs({...this.image.getSize()}),this.backgroundRect.setAttrs({...this.image.getSize()}),this.group.add(this.image)}setVisible(e){this.style={visible:e},this.isInitialized()&&this.group.visible(e)}setPosition(e){this.style={...e},this.isInitialized()&&this.group.position(e)}setVisibleAndX(e,t){this.style={visible:e,x:t},this.isInitialized()&&this.group.setAttrs({visible:e,x:t})}getPosition(){return this.group.getPosition()}getDimension(){return this.group.getSize()}setDimension(e){this.style={...e},this.isInitialized()&&this.group.size(e),this.onMeasurementsChange()}getRect(){return{...this.getPosition(),...this.getDimension()}}getThumbnailVttCue(){return this.thumbnailVttCue}setThumbnailVttCue(e){this.thumbnailVttCue=e}getImage(){return this.image}compareTo(e){return this.thumbnailVttCue&&e&&this.thumbnailVttCue.url===e.thumbnailVttCue.url?0:-1}}class ls extends Cn{constructor(e,t){super(e,t)}static create(e,t){let r=new ls(e,t);return r.fetch().pipe(ke(s=>r))}mapCue(e){return{id:e.identifier,startTime:new Z(e.start).toDecimalPlaces(3).toNumber(),endTime:new Z(e.end).toDecimalPlaces(3).toNumber(),text:e.text,url:this.resolveThumbnailUrl(e)}}resolveThumbnailUrl(e){return this.isUrlAbsolute(e.text)?e.text:this.createThumbnailUrlFromRelativeUrl(e.text)}createThumbnailUrlFromRelativeUrl(e){return this.url.lastIndexOf("/")>2?`${this.url.substring(0,this.url.lastIndexOf("/"))}/${e}`:e}isUrlAbsolute(e){return/^(http(s):\/\/.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/.test(e)}}class ct{static createKonvaImage(e){return new re(t=>{M.Image.fromURL(e,r=>{t.next(r),t.complete()},r=>{console.error(r),t.error(r)})})}static createKonvaImageSizedByWidth(e,t){return ct.createKonvaImage(e).pipe(ke(r=>(r.setAttrs({width:t,height:ct.calculateProportionalHeight(t,r)}),r)))}static createKonvaImageSizedByHeight(e,t){return ct.createKonvaImage(e).pipe(ke(r=>(r.setAttrs({width:ct.calculateProportionalWidth(t,r),height:t}),r)))}static calculateProportionalHeight(e,t){return e*t.getAttrs().image.naturalHeight/t.getAttrs().image.naturalWidth}static calculateProportionalWidth(e,t){return e*t.getAttrs().image.naturalWidth/t.getAttrs().image.naturalHeight}}const Gm={...rr,thumbnailHeight:40,thumbnailStroke:"rgba(121,0,255,0.9)",thumbnailStrokeWidth:0,thumbnailHoverScale:1.5,thumbnailHoverStroke:"rgba(0,255,188,0.9)",thumbnailHoverStrokeWidth:5};class Ks extends sr{constructor(e){super({...e,style:{...Gm,...e.style}}),this.thumbnailsMap=new Map,this.thumbnailsVisibleSet=new Set,this.onSettleLayout$=new V,this.eventStreamBreaker$=new V,this.onClick$=new V,this._thumbnailVttUrl=this.config.thumbnailVttUrl,this._axiosConfig=this.config.axiosConfig}createCanvasNode(){return super.createCanvasNode(),this.timecodedGroup=new M.Group({...this.timelinePosition,width:this.timeline.getTimecodedGroupDimension().width,height:this.bodyGroup.height()}),this.timecodedEventCatcher=wi.createEventCatcher({width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.thumbnailsGroup=new M.Group({x:0,y:this.style.height/2-this.style.thumbnailHeight/2,width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.timecodedGroup.add(this.timecodedEventCatcher),this.timecodedGroup.add(this.thumbnailsGroup),this.timeline.addToTimecodedThumbnailsGroup(this.timecodedGroup),this.thumbnailHover=new Ys({style:{visible:!1,stroke:this.style.thumbnailHoverStroke,strokeWidth:this.style.thumbnailHoverStrokeWidth}}),this.timeline.addToTimecodedSurfaceGroup(this.thumbnailHover.initCanvasNode()),this.bodyGroup}settleLayout(){super.settleLayout(),this.timecodedGroup.setAttrs({...this.timelinePosition});let e=this.timeline.getTimecodedGroupHorizontalMeasurement();[this.timecodedGroup,this.timecodedEventCatcher,this.thumbnailsGroup].forEach(t=>{t.width(e.width)}),this.onSettleLayout$.next()}afterCanvasNodeInit(){super.afterCanvasNodeInit(),this.fetchAndCreateThumbnails(),this.onSettleLayout$.pipe(k(this.onDestroy$)).subscribe(()=>{this.hideThumbnailHover(),this.adjustThumbnails()}),this.onSettleLayout$.pipe(k(this.onDestroy$)).pipe(Ho(100)).subscribe(()=>{this.createAndAdjustThumbnails()}),this.timecodedGroup.on("mouseout mouseleave",e=>{this.hideThumbnailHover()})}onMeasurementsChange(){super.onMeasurementsChange(),this.hideThumbnailHover(),this.createAndAdjustThumbnails()}destroy(){super.destroy(),this.timecodedGroup.destroy(),this.thumbnailHover.destroy(),this.fireEventStreamBreaker()}clearContent(){this.fireEventStreamBreaker(),this.thumbnailVttFile=void 0,this.clearItems()}clearItems(){this.thumbnailsMap.forEach(e=>e.destroy()),this.thumbnailsMap.clear(),this.thumbnailsVisibleSet.clear(),this.thumbnailsGroup.destroyChildren()}fireEventStreamBreaker(){Ge(this.eventStreamBreaker$),this.eventStreamBreaker$=new V}createAndAdjustThumbnails(){this.isVttLoaded()&&(this.resolveVisibleTimestamps(),this.thumbnailVttFile.getCues().forEach(e=>{let t=this.timeline.timeToTimelinePosition(e.startTime),r=this.thumbnailsVisibleSet.has(e.startTime);if(this.timeline.constrainTimelinePosition(t)===t)if(this.thumbnailsMap.has(e.startTime)){let s=this.thumbnailsMap.get(e.startTime);s&&s.setVisibleAndX(r,t)}else r&&(this.thumbnailsMap.set(e.startTime,null),ct.createKonvaImageSizedByHeight(e.url,this.style.thumbnailHeight).subscribe(s=>{let n=this.thumbnailsVisibleSet.has(e.startTime),a=this.createThumbnail(e,s,n);this.thumbnailsMap.set(e.startTime,a),this.thumbnailsGroup.add(a.getCanvasNode())}))}))}adjustThumbnails(){this.isVttLoaded()&&(this.resolveVisibleTimestamps(),this.thumbnailsMap.forEach(e=>{if(e){let t=this.timeline.timeToTimelinePosition(e.getThumbnailVttCue().startTime),r=this.thumbnailsVisibleSet.has(e.getThumbnailVttCue().startTime);e.setVisibleAndX(r,t)}}))}resolveVisibleTimestamps(){let e;this.thumbnailVttFile.getCues().forEach(r=>{let s=this.timeline.timeToTimelinePosition(r.startTime);this.timeline.constrainTimelinePosition(s)===s&&((e?s>=e:!0)?(e=s+this.thumbnailWidth,this.thumbnailsVisibleSet.add(r.startTime)):this.thumbnailsVisibleSet.delete(r.startTime))})}createThumbnail(e,t,r){let s=this.timeline.timeToTimelinePosition(e.startTime),n=new Ys({listening:!0,style:{x:s,y:0,visible:r,stroke:this.style.thumbnailStroke,strokeWidth:this.style.thumbnailStrokeWidth}});return n.setThumbnailVttCue(e),n.initCanvasNode(),n.setImage(t),n.onClick$.pipe(k(this.eventStreamBreaker$)).subscribe(a=>{this.onClick$.next(a)}),n.onMouseOver$.pipe(k(this.eventStreamBreaker$)).subscribe(a=>{this.showThumbnailHover(a.thumbnail)}),n.onMouseMove$.pipe(k(this.eventStreamBreaker$)).subscribe(a=>{this.showThumbnailHover(a.thumbnail)}),n.onMouseOut$.pipe(k(this.eventStreamBreaker$)).subscribe(a=>{this.hideThumbnailHover()}),n.onMouseLeave$.pipe(k(this.eventStreamBreaker$)).subscribe(a=>{this.hideThumbnailHover()}),n}showThumbnailHover(e){if(this.thumbnailHover.setVisible(!0),this.thumbnailHover.compareTo(e)===0){let t=this.resolveThumbnailHoverPosition(e);this.thumbnailHover.setPosition(t),this.thumbnailHover.setVisible(!0)}else ct.createKonvaImageSizedByWidth(e.getThumbnailVttCue().url,e.getImage().width()*this.style.thumbnailHoverScale).subscribe(t=>{this.thumbnailHover.setDimension(t.getSize()),this.thumbnailHover.setImage(t),this.thumbnailHover.setPosition(this.resolveThumbnailHoverPosition(e)),this.thumbnailHover.getCanvasNode().moveToTop()})}hideThumbnailHover(){this.thumbnailHover&&this.thumbnailHover.style.visible&&this.thumbnailHover.setVisible(!1)}resolveThumbnailHoverPosition(e){let t=this.timeline.getTimecodedGroupRect(),r=this.thumbnailHover.getImage().getSize(),s=e.getPosition().x+e.getDimension().width/2-r.width/2,n=e.style.strokeWidth>0?e.style.strokeWidth/2:0;s=s-n<0?n:s+r.width+n>t.width?t.width-r.width-n:s;let h=this.getRect().y+this.thumbnailsGroup.y()+e.getDimension().height/2-this.thumbnailHover.getDimension().height/2;return{x:s,y:h}}fetchAndCreateThumbnails(){this.fetchThumbnailVttFile(this._thumbnailVttUrl,this._axiosConfig,this.style.thumbnailHeight).pipe($e(1)).subscribe(e=>{e&&(this.thumbnailVttFile=e.thumbnailVttFile,this.thumbnailWidth=e.thumbnailWidth,this.createAndAdjustThumbnails())})}fetchThumbnailVttFile(e,t,r){return e?ls.create(e,t).pipe(tc(s=>{let n=s.getCues()[0];return ct.createKonvaImageSizedByHeight(n.url,r).pipe(ke(a=>{let o=a.getSize().width;return{thumbnailVttFile:s,thumbnailWidth:o}}))}),yi((s,n)=>Se(void 0))):Se(void 0)}isVttLoaded(){return!!this.thumbnailVttFile&&!!this.thumbnailWidth}getThumbnailVttFile(){return this.thumbnailVttFile}get thumbnailVttUrl(){return this._thumbnailVttUrl}set thumbnailVttUrl(e){this._thumbnailVttUrl=e,this.clearContent(),this.fetchAndCreateThumbnails()}}class kn extends Cn{constructor(e,t){super(e,t)}static create(e,t){let r=new kn(e,t);return r.fetch().pipe(ke(s=>r))}mapCue(e){let t=e.text.split(","),r=_e.coerce.number().min(-1).max(0).parse(t[0]),s=_e.coerce.number().min(0).max(1).parse(t[1]);return{id:e.identifier,startTime:new Z(e.start).toDecimalPlaces(3).toNumber(),endTime:new Z(e.end).toDecimalPlaces(3).toNumber(),text:e.text,minSample:r,maxSample:s}}}const Oa={listening:!1,style:{height:20,cornerRadius:20,opacity:1,visible:!0,maxSampleFillLinearGradientColorStops:[0,"red",.2,"yellow",1,"green"],minSampleFillLinearGradientColorStops:[0,"green",.8,"yellow",1,"red"]}};class Fm extends et{constructor(e){super({...Oa,...e,style:{...Oa.style,...e.style}}),this.audioVttCue=this.config.audioVttCue,this.x=this.config.x,this.width=this.config.width,this.listening=this.config.listening}createCanvasNode(){this.group=new M.Group({x:this.x,y:0,width:this.width,height:this.style.height,visible:this.style.visible,listening:this.listening});let e=this.style.height/2,t=this.resolveMaxSampleBarHeight(),r=this.resolveMinSampleBarHeight();return this.maxSampleBar=new M.Rect({x:0,width:this.group.width(),y:e-t,height:t,opacity:this.style.opacity,cornerRadius:[this.style.cornerRadius,this.style.cornerRadius,0,0],fillLinearGradientStartPoint:{x:0,y:-(e-t)},fillLinearGradientEndPoint:{x:0,y:t},fillLinearGradientColorStops:this.style.maxSampleFillLinearGradientColorStops,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1,hitStrokeWidth:0}),this.minSampleBar=new M.Rect({x:0,width:this.group.width(),y:e,height:r,opacity:this.style.opacity,cornerRadius:[0,0,this.style.cornerRadius,this.style.cornerRadius],fillLinearGradientStartPoint:{x:0,y:0},fillLinearGradientEndPoint:{x:0,y:e},fillLinearGradientColorStops:this.style.minSampleFillLinearGradientColorStops,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1,hitStrokeWidth:0}),this.group.add(this.maxSampleBar),this.group.add(this.minSampleBar),this.group}resolveMaxSampleBarHeight(){return new Z(this.audioVttCue.maxSample).mul(this.style.height/2).toDecimalPlaces(2).toNumber()}resolveMinSampleBarHeight(){return new Z(this.audioVttCue.minSample).abs().mul(this.style.height/2).toDecimalPlaces(2).toNumber()}setPosition(e){this.x=e.x,this.isInitialized()&&this.group.position({x:this.x,y:0})}getPosition(){return this.group.getPosition()}getDimension(){return this.group.getSize()}getRect(){return{...this.getPosition(),...this.getDimension()}}getAudioVttCue(){return this.audioVttCue}setAudioVttCue(e){this.audioVttCue=e;let t=this.resolveMaxSampleBarHeight(),r=this.resolveMinSampleBarHeight();this.minSampleBar.setAttrs({height:r}),this.maxSampleBar.setAttrs({y:this.style.height/2-t,height:t,fillLinearGradientStartPoint:{x:0,y:-(this.style.height/2-t)},fillLinearGradientEndPoint:{x:0,y:t}})}destroy(){this.audioVttCue=void 0,super.destroy()}}const Hm={...rr,height:40,paddingTop:0,paddingBottom:0,itemWidth:5,itemMinPadding:2,itemCornerRadius:5,maxSampleFillLinearGradientColorStops:[0,"red",.2,"yellow",1,"green"],minSampleFillLinearGradientColorStops:[0,"green",.8,"yellow",1,"red"]};class Fl extends sr{constructor(e){super({...e,style:{...Hm,...e.style}}),this.audioTrackLaneItemsMap=new Map,this.onSettleLayout$=new V,this._audioVttFileUrl=this.config.audioVttFileUrl}createCanvasNode(){return super.createCanvasNode(),this.timecodedGroup=new M.Group({...this.timelinePosition,width:this.timeline.getTimecodedGroupDimension().width,height:this.bodyGroup.height()}),this.timecodedEventCatcher=wi.createEventCatcher({width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.audioTrackLaneItemsGroup=new M.Group({...F.POSITION_TOP_LEFT,y:this.style.paddingTop,width:this.timecodedGroup.width(),height:this.timecodedGroup.height()-(this.style.paddingTop+this.style.paddingBottom)}),this.timecodedGroup.add(this.timecodedEventCatcher),this.timecodedGroup.add(this.audioTrackLaneItemsGroup),this.timeline.addToTimecodedAudioGroup(this.timecodedGroup),this.bodyGroup}settleLayout(){super.settleLayout(),this.timecodedGroup.setAttrs({...this.timelinePosition});let e=this.timeline.getTimecodedGroupHorizontalMeasurement();[this.timecodedGroup,this.timecodedEventCatcher,this.audioTrackLaneItemsGroup].forEach(t=>{t.width(e.width)}),this.onSettleLayout$.next()}afterCanvasNodeInit(){super.afterCanvasNodeInit(),this.fetchAndCreateAudioTrack(),this.onSettleLayout$.pipe(k(this.onDestroy$)).subscribe(()=>{this.settlePosition()}),Nu([this.onSettleLayout$,this.timeline.onScroll$]).pipe(k(this.onDestroy$),Ho(100)).subscribe(()=>{this.settleAll()})}clearContent(){this.audioVttFile=void 0,this.clearItems()}clearItems(){this.audioTrackLaneItemsMap.forEach(e=>e.destroy()),this.audioTrackLaneItemsMap.clear(),this.audioTrackLaneItemsGroup.destroyChildren()}getVisibleCues(){let e=this.timeline.getVisibleTimeRange();return this.audioVttFile.findCues(e.start,e.end)}createEntities(){if(!this.isVttLoaded())return;this.clearItems();let e=this.getVisibleCues(),t=this.timeline.getTimecodedContainerDimension().width;this.numOfInterpolations=new Z(t+this.style.itemMinPadding).div(this.style.itemWidth+this.style.itemMinPadding).floor().toNumber(),this.itemPadding=new Z(t-this.numOfInterpolations*this.style.itemWidth).div(this.numOfInterpolations-1).toNumber();let r=this.resolveNumOfCuesPerInterpolation(e.length),s=this.resolveCuesInterpolations(e,r);for(let n=0;n<this.numOfInterpolations;n++){let a=s.get(n),o=this.resolveInterpolatedItemPosition(n),h=new Fm({x:o,width:this.style.itemWidth,audioVttCue:a,style:{cornerRadius:this.style.itemCornerRadius,height:this.audioTrackLaneItemsGroup.height(),visible:!0,maxSampleFillLinearGradientColorStops:this.style.maxSampleFillLinearGradientColorStops,minSampleFillLinearGradientColorStops:this.style.minSampleFillLinearGradientColorStops}});this.audioTrackLaneItemsMap.set(n,h),this.audioTrackLaneItemsGroup.add(h.initCanvasNode())}}resolveNumOfCuesPerInterpolation(e){return new Z(e).div(this.numOfInterpolations).floor().toNumber()}resolveCuesInterpolations(e,t){let r=e.length-t*this.numOfInterpolations,s=new Map,n=0;for(let a=0;a<this.numOfInterpolations;a++){let o=t+(a<r?1:0),h=n;n=h+o;let l=e.slice(h,n),d=e[h],u=e[n-1],c=0,p=0;l.forEach(m=>{c+=m.minSample,p+=m.maxSample});let f={id:`${a}`,text:"",minSample:new Z(c).div(o).toDecimalPlaces(3).toNumber(),maxSample:new Z(p).div(o).toDecimalPlaces(3).toNumber(),startTime:d.startTime,endTime:u.endTime};s.set(a,f)}return s}settleAll(){if(!this.isVttLoaded()||this.audioTrackLaneItemsMap.size<1)return;let e=this.getVisibleCues(),t=this.resolveNumOfCuesPerInterpolation(e.length),r=this.resolveCuesInterpolations(e,t);for(let s=0;s<this.numOfInterpolations;s++){let n=r.get(s),a=this.audioTrackLaneItemsMap.get(s);a.setAudioVttCue(n),a.setPosition({x:this.resolveInterpolatedItemPosition(s)})}}resolveInterpolatedItemPosition(e){return Math.abs(this.timeline.getTimecodedGroupHorizontalMeasurement().x)+e*this.style.itemWidth+e*this.itemPadding}settlePosition(){if(!(!this.isVttLoaded()||this.audioTrackLaneItemsMap.size<1))for(let e=0;e<this.numOfInterpolations;e++){let t=this.audioTrackLaneItemsMap.get(e),r=this.timeline.timeToTimelinePosition(t.getAudioVttCue().startTime);t.setPosition({x:r})}}fetchAndCreateAudioTrack(){this.fetchAudioTrackVttFile(this._audioVttFileUrl).pipe($e(1)).subscribe(e=>{this.audioVttFile=e,this.createEntities()})}fetchAudioTrackVttFile(e){return e?kn.create(e).pipe(ke(t=>t),yi((t,r)=>Se(void 0))):Se(void 0)}isVttLoaded(){return!!this.audioVttFile}get audioVttFileUrl(){return this._audioVttFileUrl}set audioVttFileUrl(e){this._audioVttFileUrl=e,this.clearContent(),this.fetchAndCreateAudioTrack()}destroy(){this.audioTrackLaneItemsMap.forEach(e=>{e.destroy()}),this.audioVttFile=void 0,Ge(this.onSettleLayout$),super.destroy()}}function Js(i){if(i.from===i.to)return;let e=i.from<i.to,t=e?i.to-i.from:i.from-i.to,r=new M.Animation(s=>{let n=M.Easings.StrongEaseInOut(s.time,0,t,i.duration);if(n>=t)i.onUpdateHandler(s,i.to),r.stop(),i.onCompleteHandler&&(i.onCompleteHandler(s,i.to),r=null);else{let a=i.from+n*(e?1:-1);i.onUpdateHandler(s,a)}},i.layer);r.start()}const Bm={...F.POSITION_TOP_LEFT,width:0,zoomMax:1500,scrollStepNumberOfDivisions:10,style:{height:20,backgroundFill:"#000000",backgroundFillOpacity:.3,handleBarFill:"#01a6f0",handleBarOpacity:1,handleOpacity:1}};class $m extends et{constructor(e){super(_i(e,Bm)),this.onScroll$=new V,this.onZoom$=new V,this.x=this.config.x,this.y=this.config.y,this.width=this.config.width,this.zoomMax=this.config.zoomMax,this.scrollStepNumberOfDivisions=this.config.scrollStepNumberOfDivisions}createCanvasNode(){return this.group=new M.Group({x:this.x,y:this.y,width:this.width,height:this.style.height}),this.background=new M.Rect({...F.POSITION_TOP_LEFT,width:this.group.width(),height:this.style.height,fill:this.style.backgroundFill,opacity:this.style.backgroundFillOpacity}),this.handleGroup=new M.Group({...F.POSITION_TOP_LEFT,width:this.group.width(),height:this.style.height}),this.handleBar=new M.Rect({...F.POSITION_TOP_LEFT,width:this.handleGroup.width(),height:this.style.height,fill:this.style.handleBarFill,opacity:this.style.handleBarOpacity,draggable:!0}),this.leftZoomHandle=new M.Circle({...F.POSITION_TOP_LEFT,fill:this.style.handleBarFill,radius:this.style.height/2,y:this.style.height/2,opacity:this.style.handleOpacity,draggable:!0}),this.rightZoomHandle=new M.Circle({...F.POSITION_TOP_LEFT,fill:this.style.handleBarFill,radius:this.style.height/2,y:this.style.height/2,opacity:this.style.handleOpacity,draggable:!0}),this.handleGroup.add(this.background),this.handleGroup.add(this.handleBar),this.group.add(this.background),this.group.add(this.handleGroup),this.handleGroup.add(this.leftZoomHandle),this.handleGroup.add(this.rightZoomHandle),this.group}afterCanvasNodeInit(){this.styleAdapter.onChange$.pipe(k(this.onDestroy$),We(n=>!!n)).subscribe(n=>{this.onStyleChange()}),this.group.on("click",n=>{this.clickScrollTo(this.group.getRelativePointerPosition().x)}),this.handleBar.on("dragstart dragmove dragend",n=>{let a=this.handleBar.getPosition(),o=this.getConstrainedHandleBarX(a.x);this.handleBar.setAttrs({x:o,y:0}),this.syncLeftRightHandles(),this.handleBar.getRelativePointerPosition().x>=0&&this.handleBar.getRelativePointerPosition().x<=this.handleBar.width()&&this.onScroll$.next({scrollPercent:this.getScrollHandlePercent()})});let e={scaleX:1.5,scaleY:1.5,duration:.1},t={scaleX:1,scaleY:1,duration:.1};this.leftZoomHandle.on("mouseover",n=>{this.leftZoomHandle.to({...e}),it.cursor("ew-resize")}),this.leftZoomHandle.on("mouseout",n=>{this.leftZoomHandle.to({...t}),it.cursor("default")}),this.rightZoomHandle.on("mouseover",n=>{this.rightZoomHandle.to({...e}),it.cursor("ew-resize")}),this.rightZoomHandle.on("mouseout",n=>{this.rightZoomHandle.to({...t}),it.cursor("default")});let r=n=>{let a=n;return a<0?a=0:this.rightZoomHandle.x()-n<=this.minHandleBarWidth&&(a=this.rightZoomHandle.x()-this.minHandleBarWidth),a};this.leftZoomHandle.on("dragstart dragmove dragend",n=>{let a=this.leftZoomHandle.getPosition(),o=r(a.x);this.leftZoomHandle.setAttrs({x:o,y:this.style.height/2}),this.handleBar.setAttrs({x:o,width:this.rightZoomHandle.x()-o}),this.onZoom$.next({zoomPercent:this.getZoomPercent()})});let s=n=>{let a=n,o=this.group.width();return a>o?a=o:n-this.leftZoomHandle.x()<=this.minHandleBarWidth&&(a=this.leftZoomHandle.x()+this.minHandleBarWidth),a};this.rightZoomHandle.on("dragstart dragmove dragend",n=>{let a=this.rightZoomHandle.getPosition(),o=s(a.x);this.rightZoomHandle.setAttrs({x:o,y:this.style.height/2}),this.handleBar.setAttrs({width:o-this.leftZoomHandle.x()}),this.onZoom$.next({zoomPercent:this.getZoomPercent()})})}onMeasurementsChange(){this.group.width(this.width),this.background.width(this.group.width()),this.handleGroup.width(this.group.width()),this.minHandleBarWidth=this.calculateHandleBarWidthFromZoomRatioPercent(this.zoomMax)}onStyleChange(){this.group.setAttrs({height:this.style.height}),this.background.setAttrs({height:this.style.height,fill:this.style.backgroundFill,opacity:this.style.backgroundFillOpacity}),this.handleGroup.setAttrs({height:this.style.height}),this.handleBar.setAttrs({height:this.style.height,fill:this.style.handleBarFill,opacity:this.style.handleBarOpacity}),this.leftZoomHandle.setAttrs({fill:this.style.handleBarFill,radius:this.style.height/2,y:this.style.height/2,opacity:this.style.handleOpacity}),this.rightZoomHandle.setAttrs({fill:this.style.handleBarFill,radius:this.style.height/2,y:this.style.height/2,opacity:this.style.handleOpacity})}getScrollHandleMaxX(){return this.group.width()-this.handleBar.width()}getConstrainedHandleBarX(e){let t=e;return t<0?t=0:t+this.handleBar.width()>this.group.width()&&(t=this.getScrollHandleMaxX()),t}clickScrollTo(e){let t=this.group.width()/this.scrollStepNumberOfDivisions;if(!(e>=this.handleBar.x()&&e<=this.handleBar.x()+this.handleBar.width())){let r=this.handleBar.x()>e,s=this.handleBar.x()+t*(r?-1:1);r?s=s<e?e:s:s=s+this.handleBar.width()>e?e-this.handleBar.width():s,this.scrollToEased(s)}}scrollTo(e){this.handleBar.x(this.getConstrainedHandleBarX(e)),this.syncLeftRightHandles(),this.onScroll$.next({scrollPercent:this.getScrollHandlePercent()})}scrollToEased(e){let t=this.handleBar.x(),r=this.getConstrainedHandleBarX(e);Js({layer:this.handleGroup.getLayer(),duration:F.TIMELINE_SCROLL_EASED_DURATION_MS,from:t,to:r,onUpdateHandler:(s,n)=>{this.scrollTo(n)}})}calculateHandleBarWidthFromZoomRatioPercent(e){return new Z(this.group.width()).mul(100).div(e).toNumber()}getZoomPercent(){return this.group.width()===this.handleBar.width()?100:new Z(this.group.width()).mul(100).div(this.handleBar.width()).toNumber()}getScrollHandlePercent(){return this.handleBar.x()===0?0:new Z(this.handleBar.x()).div(this.group.width()-this.handleBar.width()).mul(100).toNumber()}updateScrollHandle(e){let t=e.getScrollHandleHorizontalMeasurement(this.group.width());this.handleBar.setAttrs({...t}),this.syncLeftRightHandles()}syncLeftRightHandles(){this.leftZoomHandle.x(this.handleBar.x()),this.rightZoomHandle.x(this.handleBar.x()+this.handleBar.width())}setWidth(e){this.width=e,this.onMeasurementsChange()}setPosition(e){this.x=e.x,this.y=e.y,this.group.setAttrs({...e})}getPosition(){return this.group.getPosition()}getRect(){return{...this.group.getPosition(),...this.group.getSize()}}}const Vm={style:{...F.POSITION_TOP_LEFT,height:100,fill:"#737373",fillSnapped:"#ffd500",lineWidth:2,symbolY:0,symbolHeight:15,textFontSize:12,textFill:"#0d0f05",textSnappedFill:"#f43530",visible:!1}};class zm extends et{constructor(e,t){super(_i(e,Vm)),this.stylesProvider=dt.instance(),this.timeline=t}createCanvasNode(){return this.group=new M.Group({x:this.style.x,y:this.style.y,visible:this.style.visible,listening:!1}),this.line=new M.Line({points:[this.style.x,0,this.style.x,this.style.height],stroke:this.style.fill,strokeWidth:this.style.lineWidth,listening:!1}),this.symbol=new M.Circle({y:this.style.symbolY,fill:this.style.fill,radius:this.style.symbolHeight/2,offsetY:-this.style.symbolHeight/2}),this.group.add(this.symbol),this.group.add(this.line),this.label=new M.Label({...F.POSITION_TOP_LEFT,listening:!1}),this.text=new M.Text({fontSize:this.style.textFontSize,fontFamily:this.stylesProvider.styles.omakasePlayerStyle.fontFamily,fill:this.style.textFill,...F.POSITION_TOP_LEFT,text:"",listening:!1}),this.label.y(-this.text.getSelfRect().height),this.label.add(this.text),this.group.add(this.label),this.group}afterCanvasNodeInit(){this.styleAdapter.onChange$.pipe(k(this.onDestroy$)).subscribe(e=>{this.onMeasurementsChange()}),this.stylesProvider.onChange$.pipe(We(e=>!!e),k(this.onDestroy$)).subscribe(e=>{this.text.setAttrs({fontFamily:this.stylesProvider.styles.omakasePlayerStyle.fontFamily})})}onMeasurementsChange(){this.line.points([this.line.x(),0,this.line.x(),this.style.height])}sync(e,t=!1){this.style.visible||this.toggleVisible(!0);let r=this.timeline.timelinePositionToTimeFormatted(e),s=this.text.getSelfRect(),n=s.width/2,a=-n,o=this.timeline.getTimecodedGroupHorizontalMeasurement();o.width-e<n?a=-s.width+(o.width-e):e<n&&(a=-n+(n-e)),this.group.x(e),this.text.text(r),this.label.x(a),t?(this.line.stroke(this.style.fillSnapped),this.text.fill(this.style.fillSnapped),this.symbol.visible(!1)):(this.line.stroke(this.style.fill),this.text.fill(this.style.fill),this.symbol.visible(!0))}toggleVisible(e){this.style={visible:e},this.group.visible(e)}}const Wm={style:{visible:!0,fill:"#f43530",lineWidth:2,symbolHeight:15,scrubberHeight:15,backgroundFill:"#ffffff",backgroundOpacity:0,playProgressFill:"#008cbc",playProgressOpacity:.5,bufferedFill:"#a2a2a2",bufferedOpacity:1}};class Um extends et{constructor(e,t,r){super(_i(e,Wm)),this.timeline=t,this.videoController=r}createCanvasNode(){return this.group=new M.Group({...F.POSITION_TOP_LEFT,listening:!1}),this.background=new M.Rect({...F.POSITION_TOP_LEFT,height:this.style.scrubberHeight,fill:this.style.backgroundFill,opacity:this.style.backgroundOpacity,listening:!1}),this.playProgressBackground=new M.Rect({...F.POSITION_TOP_LEFT,height:this.style.scrubberHeight,fill:this.style.playProgressFill,opacity:this.style.playProgressOpacity,listening:!1}),this.playheadGroup=new M.Group({...F.POSITION_TOP_LEFT,visible:this.style.visible,listening:!1}),this.playheadLine=new M.Line({points:[0,0,0,0],stroke:this.style.fill,strokeWidth:this.style.lineWidth,listening:!1}),this.playheadSymbol=wi.createTriangle({...F.POSITION_TOP_LEFT,height:this.style.symbolHeight,color:this.style.fill}),this.bufferedGroup=new M.Group({...F.POSITION_TOP_LEFT,listening:!1}),this.group.add(this.background),this.group.add(this.bufferedGroup),this.group.add(this.playProgressBackground),this.playheadGroup.add(this.playheadLine),this.playheadGroup.add(this.playheadSymbol),this.group.add(this.playheadGroup),this.group}afterCanvasNodeInit(){this.settleLayout(),this.timeline.onZoom$.pipe(k(this.onDestroy$)).subscribe(e=>{this.settleLayout()}),this.videoController.onVideoLoading$.pipe(k(this.onDestroy$)).subscribe(e=>{this.group.visible(!1)}),this.videoController.onVideoLoaded$.pipe(k(this.onDestroy$)).subscribe(e=>{this.group.visible(!0),this.doPlayProgress(),this.doBufferingProgress()}),this.videoController.onVideoTimeChange$.pipe(k(this.onDestroy$)).subscribe(e=>{this.doPlayProgress()}),this.videoController.onSeeking$.pipe(k(this.onDestroy$)).subscribe(e=>{this.doPlayProgress(),this.doBufferingProgress()}),this.videoController.onBuffering$.pipe(k(this.onDestroy$)).subscribe(e=>{this.doBufferingProgress()})}onMeasurementsChange(){this.settleLayout()}getPlayheadPosition(){return this.playheadGroup.x()}settleLayout(){let e=this.timeline.getTimecodedGroupDimension();[this.group,this.bufferedGroup,this.playheadGroup].forEach(t=>{t.setAttrs({...e})}),[this.background].forEach(t=>{t.setAttrs({width:e.width})}),this.playheadLine.setAttrs({points:[0,0,0,e.height]}),this.doPlayProgress(),this.doBufferingProgress()}doPlayProgress(){let e=this.timeline.timeToTimelinePosition(this.videoController.getCurrentTime());this.playProgressBackground.width(e),this.playheadGroup.x(e)}doBufferingProgress(){let e=this.videoController.getBufferedTimespans();if(e&&e.length>0)if(this.bufferedGroup.hasChildren()){let t=e.length,r=this.bufferedGroup.getChildren().length;t===r?this.bufferedGroup.getChildren().forEach((s,n)=>{let a=e[n],o=this.timeline.timeToTimelinePosition(a.start),h=this.timeline.timeToTimelinePosition(a.end);s.setAttrs({x:o,width:h-o})}):(this.bufferedGroup.getChildren().forEach(s=>s.destroy()),this.createBuffers(e))}else this.createBuffers(e)}createBuffers(e){e.forEach(t=>{let r=this.timeline.timeToTimelinePosition(t.start),s=this.timeline.timeToTimelinePosition(t.end),n=new M.Rect({x:r,y:0,width:s-r,height:this.style.scrubberHeight,fill:this.style.bufferedFill,opacity:this.style.bufferedOpacity,listening:!1});this.bufferedGroup.add(n)})}}const Zm={style:{...F.POSITION_TOP_LEFT,width:150,height:20,textFontSize:20,textFill:"#0d0f05",visible:!0}};class Hl extends et{constructor(e,t){super(_i(e,Zm)),this.stylesProvider=dt.instance(),this.videoEventStreamBreaker$=new V,this.videoController=t}createCanvasNode(){return this.group=new M.Group({x:this.style.x,y:this.style.y,width:this.style.width,height:this.style.height,listening:!1,visible:this.style.visible}),this.text=new M.Text({...F.POSITION_TOP_LEFT,width:this.group.width(),height:this.group.height(),text:"",fontSize:this.style.textFontSize,fontFamily:this.stylesProvider.styles.omakasePlayerStyle.fontFamily,fill:this.style.textFill,visible:!0,align:"left",verticalAlign:"middle"}),this.group.add(this.text),this.group}afterCanvasNodeInit(){super.afterCanvasNodeInit(),this.stylesProvider.onChange$.pipe(We(e=>!!e),k(this.onDestroy$)).subscribe(e=>{this.text.setAttrs({fontFamily:this.stylesProvider.styles.omakasePlayerStyle.fontFamily})}),this.videoController.onVideoLoaded$.pipe(We(e=>!!e),k(this.onDestroy$)).subscribe(e=>{this.onVideoLoadedEvent(e)})}onMeasurementsChange(){this.group.width(this.style.width)}fireVideoEventStreamBreaker(){Ge(this.videoEventStreamBreaker$),this.videoEventStreamBreaker$=new V}onVideoLoadedEvent(e){this.fireVideoEventStreamBreaker(),this.text.text(this.videoController.formatTimestamp(0)),this.videoController.onVideoTimeChange$.pipe(k(this.videoEventStreamBreaker$)).subscribe(t=>{this.text.text(this.videoController.formatTimestamp(t.currentTime))})}setVisible(e){this.style={visible:e},this.isInitialized()&&this.group.visible(e)}setPosition(e){this.style={...e},this.group.setAttrs({...e}),this.onMeasurementsChange()}getRect(){return this.group.getClientRect()}}const jm={...rr,height:60,tickDivisor:5,tickDivisionMinWidth:18,tickFill:"#0d0f05",tickHeight:12,divisionTickFill:"#000000",divisionTickHeight:12*F.GOLDEN_RATIO,timecodeShowFirst:!0,timecodeFontSize:11,timecodeFill:"#0d0f05"};class Xm extends sr{constructor(e,t){super({...e,style:{...jm,...e.style}}),this.onClick$=new V,this.onMouseEnter$=new V,this.onMouseOver$=new V,this.onMouseMove$=new V,this.onMouseOut$=new V,this.onMouseLeave$=new V,this.videoController=t}createCanvasNode(){return super.createCanvasNode(),this.timecodedGroup=new M.Group({...this.timelinePosition,width:this.timeline.getTimecodedGroupDimension().width,height:this.bodyGroup.height()}),this.timecodedEventCatcher=wi.createEventCatcher({width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.ticksGroup=new M.Group({...F.POSITION_TOP_LEFT,width:this.timecodedGroup.width(),height:this.timecodedGroup.height()}),this.timecodedGroup.add(this.timecodedEventCatcher),this.timecodedGroup.add(this.ticksGroup),this.timeline.addToTimecodedBaseGroup(this.timecodedGroup),this.timecodeDisplay=new Hl({style:{x:10,y:0,width:this.leftGroup.width(),height:this.getRect().height}},this.videoController),this.leftGroup.add(this.timecodeDisplay.initCanvasNode()),this.bodyGroup}settleLayout(){super.settleLayout();let e=this.timeline.getTimecodedGroupHorizontalMeasurement();[this.timecodedGroup,this.timecodedEventCatcher,this.ticksGroup].forEach(t=>{t.width(e.width)}),this.refreshTimeDivisions()}afterCanvasNodeInit(){super.afterCanvasNodeInit(),this.timecodedEventCatcher.on("mousemove",e=>{this.onMouseMove$.next({evt:e.evt,position:this.timecodedGroup.getRelativePointerPosition()})}),this.timecodedEventCatcher.on("mouseenter",e=>{this.onMouseEnter$.next({evt:e.evt,position:this.timecodedGroup.getRelativePointerPosition()})}),this.timecodedEventCatcher.on("mouseout",e=>{this.onMouseOut$.next({evt:e.evt,position:this.timecodedGroup.getRelativePointerPosition()})}),this.timecodedEventCatcher.on("mouseleave",e=>{this.onMouseLeave$.next({evt:e.evt,position:this.timecodedGroup.getRelativePointerPosition()})}),this.timecodedEventCatcher.on("click",e=>{this.onClick$.next({evt:e.evt,position:this.timecodedGroup.getRelativePointerPosition()})}),this.videoController.onVideoLoading$.pipe(k(this.onDestroy$)).subscribe(e=>{this.clearContent()}),this.videoController.onVideoLoaded$.pipe(k(this.onDestroy$)).subscribe(e=>{this.settleLayout()})}onStyleChange(){super.onStyleChange(),this.refreshTimeDivisions(!0)}destroy(){this.timecodedGroup.destroy(),this.videoController=null;let e=[this.onClick$,this.onMouseOver$,this.onMouseMove$,this.onMouseOut$,this.onMouseLeave$];Vt(...e),bi(...e),super.destroy()}clearContent(){this.ticksGroup.destroyChildren()}refreshTimeDivisions(e=!1){if(!this.isTimelineReady())return;let t=this.style.tickDivisor,r=this.style.tickDivisionMinWidth,s=this.timeline.getTimecodedGroupRect().width,n=this.resolveTimeDivisionWidth(s,r,t,t),a=new Z(s).div(n).round().toNumber(),o=!e&&this.tickTotalDivisions===a&&!(this.ticksGroup.getChildren().length<1);o||this.clearContent(),this.tickDivisionWidth=n,this.tickTotalDivisions=a;let h=0,l=2,d=2,u=5;for(let c=0;c<this.tickTotalDivisions+1;c++){let p=c===0,f=c===this.tickTotalDivisions,m=c%t===0,g=c*this.tickDivisionWidth,_=m?this.style.divisionTickHeight:this.style.tickHeight,w=this.ticksGroup.height()-_,b=this.ticksGroup.height()-this.style.divisionTickHeight-u;if(o)this.ticksGroup.getChildren()[c].x(g);else{let T=new M.Group({x:g,y:h}),L=0,A=new M.Line({points:[L,w,L,w+_],stroke:this.style.tickFill,strokeWidth:1,listening:!1});T.add(A);let D=new M.Text({fontSize:this.style.timecodeFontSize,fontFamily:this.stylesProvider.styles.omakasePlayerStyle.fontFamily,fill:this.style.timecodeFill,text:`${this.timeline.timelinePositionToTimeFormatted(g)}`,listening:!1}),R=D.getSelfRect(),H=p?L+l:f?L-R.width-d:L-R.width/2,$=b-R.height;D.setAttrs({x:H,y:$});let I=m;I=p?this.style.timecodeShowFirst:I,I&&(T.add(D),T.x()+(D.x()>0?0:D.x()),T.y(),D.width()),this.ticksGroup.add(T)}}}resolveTimeDivisionWidth(e,t,r,s){return new Z(e).div(s).floor().greaterThan(t)?this.resolveTimeDivisionWidth(e,t,r,s*r):new Z(e).div(s/r).toNumber()}}const qm={timelineHTMLElementId:"omakase-timeline",playheadHoverSnapArea:5,zoomScale:1.02,zoomBaseline:100,zoomMax:1500,style:{stageMinWidth:700,backgroundFill:"#f5f5f5",headerBackgroundFill:"#f5f5f5",footerBackgroundFill:"#f5f5f5",scrollbarHeight:15,thumbnailHoverWidth:200,thumbnailHoverStroke:"rgba(255,73,145,0.9)",thumbnailHoverStrokeWidth:5,thumbnailHoverYOffset:0,headerHeight:50,footerHeight:50,leftPanelWidth:200,rightPanelLeftGutterWidth:30,rightPanelRightGutterWidth:30,timecodedContainerClipPadding:20,playheadVisible:!0,playheadFill:"#f43530",playheadLineWidth:2,playheadSymbolHeight:15,playheadScrubberHeight:15,playheadBackgroundFill:"#ffffff",playheadBackgroundOpacity:0,playheadPlayProgressFill:"#008cbc",playheadPlayProgressOpacity:.5,playheadBufferedFill:"#a2a2a2",playheadBufferedOpacity:1}},La="omakase_scrubber_lane";class Ym extends et{constructor(e,t){super(_i(e,qm)),this.scrollWithPlayhead=!0,this.syncTimelineWithPlayheadInProgress=!1,this.mouseWheelEnabled=!1,this.leftPanelVisible=!0,this.videoEventBreaker$=new V,this.onScroll$=new V,this.onZoom$=new V,this.timelineHTMLElementId=this.config.timelineHTMLElementId,this.thumbnailVttUrl=this.config.thumbnailVttUrl,this.axiosConfig=this.config.axiosConfig,this.playheadHoverSnapArea=this.config.playheadHoverSnapArea,this.zoomScale=this.config.zoomScale,this.zoomBaseline=this.config.zoomBaseline,this.zoomMax=this.config.zoomMax,this.timecodedGroupNodes=[],this.timelineLanes=[],this.timelineLanesMap=new Map,this.timelineHTMLElement=document.getElementById(this.timelineHTMLElementId),this.videoController=t}createCanvasNode(){let e=this.resolveStageDimension();return this.width=e.width,this.stage=new M.Stage({container:this.timelineHTMLElementId,...e}),this.layer=new M.Layer,this.stage.add(this.layer),this.layoutGroup=new M.Group({...F.POSITION_TOP_LEFT}),this.layer.add(this.layoutGroup),this.layoutBackground=new M.Rect({...F.POSITION_TOP_LEFT,fill:this.style.backgroundFill}),this.headerGroup=new M.Group({...F.POSITION_TOP_LEFT}),this.headerBackground=new M.Rect({...F.POSITION_TOP_LEFT,fill:this.style.headerBackgroundFill}),this.footerGroup=new M.Group({...F.POSITION_TOP_LEFT}),this.footerBackground=new M.Rect({...F.POSITION_TOP_LEFT,fill:this.style.footerBackgroundFill}),this.bodyGroup=new M.Group({...F.POSITION_TOP_LEFT}),this.bodyContentGroup=new M.Group({...F.POSITION_TOP_LEFT}),this.leftPanel=new M.Group({...F.POSITION_TOP_LEFT}),this.rightPanel=new M.Group({...F.POSITION_TOP_LEFT}),this.timecodedContainer=new M.Group({...F.POSITION_TOP_LEFT}),this.timecodedGroup=new M.Group({...F.POSITION_TOP_LEFT,draggable:!0}),this.timecodedBaseGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedBaseGroup"}),this.timecodedThumbnailsGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedThumbnailsGroup"}),this.timecodedSubtitlesGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedSubtitlesGroup"}),this.timecodedAudioGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedAudioGroup"}),this.timecodedMarkersGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedMarkersGroup"}),this.timecodedSurfaceGroup=new M.Group({...F.POSITION_TOP_LEFT,name:"timecodedSurfaceGroup"}),this.timecodedBackground=new M.Rect({...F.POSITION_TOP_LEFT,fill:"yellow",opacity:0,listening:!1}),this.timecodedEventCatcher=wi.createEventCatcher(),this.thumbnailHover=new Ys({style:{visible:!1,stroke:this.style.thumbnailHoverStroke,strokeWidth:this.style.thumbnailHoverStrokeWidth}}),this.layoutGroup.add(this.layoutBackground),this.layoutGroup.add(this.headerGroup),this.layoutGroup.add(this.footerGroup),this.layoutGroup.add(this.bodyGroup),this.headerGroup.add(this.headerBackground),this.footerGroup.add(this.footerBackground),this.bodyGroup.add(this.bodyContentGroup),this.bodyGroup.add(this.leftPanel),this.bodyGroup.add(this.rightPanel),this.rightPanel.add(this.timecodedContainer),this.timecodedContainer.add(this.timecodedGroup),[this.timecodedBackground,this.timecodedEventCatcher,this.timecodedBaseGroup,this.timecodedThumbnailsGroup,this.timecodedSubtitlesGroup,this.timecodedAudioGroup,this.timecodedMarkersGroup,this.timecodedSurfaceGroup].forEach(t=>{this.timecodedGroupNodes.push(t),this.timecodedGroup.add(t)}),this.scrollbar=new $m({style:{height:this.style.scrollbarHeight}}),this.rightPanel.add(this.scrollbar.initCanvasNode()),this.playhead=new Um({style:{visible:this.style.playheadVisible,fill:this.style.playheadFill,lineWidth:this.style.playheadLineWidth,symbolHeight:this.style.playheadSymbolHeight,backgroundFill:this.style.playheadBackgroundFill,backgroundOpacity:this.style.playheadBackgroundOpacity,scrubberHeight:this.style.playheadScrubberHeight,playProgressFill:this.style.playheadPlayProgressFill,playProgressOpacity:this.style.playheadPlayProgressOpacity,bufferedFill:this.style.playheadBufferedFill,bufferedOpacity:this.style.playheadBufferedOpacity}},this,this.videoController),this.playheadHover=new zm({},this),[this.playhead,this.playheadHover].forEach(t=>{this.addToTimecodedSurfaceGroup(t.initCanvasNode())}),this.headerTimecodeDisplay=new Hl({style:{x:10,y:10,visible:!1}},this.videoController),this.headerGroup.add(this.headerTimecodeDisplay.initCanvasNode()),this.settleLayout(),this.addToTimecodedSurfaceGroup(this.thumbnailHover.initCanvasNode()),this.scrubberLane=new Xm({id:La,description:""},this.videoController),this.addLanes([this.scrubberLane]),this.stage}afterCanvasNodeInit(){this.videoController.onVideoLoading$.pipe(We(e=>!!e),k(this.onDestroy$)).subscribe(e=>{this.clearContent()}),this.videoController.onVideoLoaded$.pipe(We(e=>!!e),k(this.onDestroy$)).subscribe(e=>{this.onVideoLoadedEvent(e)}),be(window,"resize").pipe(k(this.onDestroy$)).subscribe(e=>{setTimeout(()=>{this.onWindowResize(e)},200)}),this.timecodedGroup.on("mouseenter",e=>{this.playheadHover.toggleVisible(this.videoController.isVideoLoaded())}),this.timecodedGroup.on("mouseleave",e=>{this.playheadHover.toggleVisible(!1)}),this.timecodedGroup.on("mousemove",e=>{if(!this.videoController.isVideoLoaded())return;let t=this.timecodedGroup.getRelativePointerPosition().x;this.playheadHoverMove(t)}),this.timecodedMarkersGroup.on("mousemove",e=>{if(!this.videoController.isVideoLoaded())return;let t=this.timecodedGroup.getRelativePointerPosition().x;this.playheadHoverMove(t)}),this.timecodedGroup.on("wheel",e=>{if(!this.videoController.isVideoLoaded())return;if(this.mouseWheelEnabled){let r=e.evt;r.preventDefault();let s=r.deltaY>0?"IN":"OUT";r.ctrlKey&&(s=s==="IN"?"OUT":"IN"),this.zoomStep(s,this.timecodedGroup.getRelativePointerPosition().x),this.updateScrollWithPlayhead()}let t=this.timecodedGroup.getRelativePointerPosition().x;this.playheadHoverMove(t)}),this.timecodedGroup.on("dragstart dragmove dragend",e=>{if(!this.videoController.isVideoLoaded()){this.timecodedGroup.setAttrs({...F.POSITION_TOP_LEFT});return}if(e.target===this.timecodedGroup){let t=this.timecodedGroup.getPosition();this.timecodedGroup.setAttrs({x:this.getConstrainedTimelineX(t.x),y:0}),this.onScroll$.next(this.createScrollEvent()),this.scrollbar.updateScrollHandle(this)}this.updateScrollWithPlayhead()}),this.timecodedGroup.on("dragmove",e=>{it.cursor("grabbing")}),this.timecodedGroup.on("dragend",e=>{it.cursor("default")}),this.scrubberLane.onMouseMove$.pipe(k(this.onDestroy$)).subscribe(e=>{if(!this.videoController.isVideoLoaded())return;this.mouseWheelEnabled=!0;let t=this.timecodedGroup.getRelativePointerPosition().x,r=this.timelinePositionToTime(t);if(this.thumbnailVttFile){let s=this.thumbnailVttFile.findCue(r);this.showThumbnailHover(s)}}),this.scrubberLane.onMouseEnter$.pipe(k(this.onDestroy$)).subscribe(e=>{this.mouseWheelEnabled=!0}),this.scrubberLane.onMouseLeave$.pipe(k(this.onDestroy$)).subscribe(e=>{this.hideThumbnailHover(),this.mouseWheelEnabled=!1}),this.scrubberLane.onClick$.pipe(k(this.onDestroy$)).subscribe(e=>{if(!this.videoController.isVideoLoaded())return;this.updateScrollWithPlayhead();let t=this.timecodedGroup.getRelativePointerPosition().x;this.playheadHoverMove(t),this.videoController.isVideoLoaded()&&this.videoController.seekToTimestamp(this.timelinePositionToTime(t)).subscribe(()=>{})}),this.scrollbar.onScroll$.pipe(k(this.onDestroy$)).subscribe(e=>{this.videoController.isVideoLoaded()&&(this.setHorizontalScrollPercent(this.scrollbar.getScrollHandlePercent()),this.updateScrollWithPlayhead(),this.onScroll$.next(this.createScrollEvent()))}),this.scrollbar.onZoom$.pipe(k(this.onDestroy$)).subscribe(e=>{this.videoController.isVideoLoaded()&&(this.zoomByPercent(e.zoomPercent,!1),this.updateScrollWithPlayhead())}),this.thumbnailVttUrl&&this.fetchThumbnailVttFile().subscribe()}settleLayout(){this.stage.setAttrs({...this.resolveStageDimension()});let e=this.calculateHeights();this.headerGroup.setAttrs({width:this.width,height:this.style.headerHeight}),this.bodyGroup.setAttrs({y:this.headerGroup.y()+this.headerGroup.height(),width:this.layoutGroup.width(),height:e.bodyHeight}),this.footerGroup.setAttrs({y:this.bodyGroup.y()+this.bodyGroup.height(),width:this.width,height:this.style.footerHeight}),this.layoutGroup.setAttrs({width:this.width,height:e.layoutHeight}),this.layoutBackground.setAttrs({...this.layoutGroup.getSize()}),this.headerBackground.setAttrs({...this.headerGroup.getSize()}),this.footerBackground.setAttrs({...this.footerGroup.getSize()}),[this.bodyContentGroup].forEach(t=>{t.setAttrs({...this.bodyGroup.getSize()})}),[this.leftPanel,this.rightPanel].forEach(t=>{t.setAttrs({height:this.bodyGroup.getSize().height})}),this.leftPanel.setAttrs({width:this.leftPanelVisible?this.style.leftPanelWidth:0,visible:this.leftPanelVisible}),this.rightPanel.setAttrs({x:this.leftPanel.x()+this.leftPanel.width()+this.style.rightPanelLeftGutterWidth,width:this.layoutGroup.width()-(this.leftPanel.width()+this.style.rightPanelLeftGutterWidth+this.style.rightPanelRightGutterWidth)}),[this.timecodedContainer,this.timecodedGroup,...this.timecodedGroupNodes].forEach(t=>{t.setAttrs({...this.rightPanel.getSize()})}),this.timecodedContainer.clipFunc(t=>{t.rect(-this.style.timecodedContainerClipPadding,-500,this.timecodedContainer.width()+2*this.style.timecodedContainerClipPadding,this.timecodedContainer.height()+500)}),this.timecodedThumbnailsGroup.clipFunc(t=>{t.rect(0,0,this.timecodedThumbnailsGroup.width(),this.timecodedThumbnailsGroup.height())}),this.scrollbar.setPosition({...this.scrollbar.getPosition(),y:this.leftPanel.getSize().height}),this.scrollbar.setWidth(this.timecodedContainer.width()),this.scrollbar.updateScrollHandle(this),this.maxTimecodedGroupWidth=this.calculateWidthFromZoomRatioPercent(this.zoomMax),this.playheadHover.style={height:this.timecodedContainer.height()},this.timelineLanes.forEach(t=>{t.onMeasurementsChange()}),this.playhead.onMeasurementsChange()}onMeasurementsChange(){this.settleLayout();let e=this.getTimecodedGroupDimension();this.timelineLanes.forEach(t=>{t.onMeasurementsChange()}),this.zoomByWidth(e.width,this.resolveZoomFocus()),this.scrollbar.updateScrollHandle(this)}onWindowResize(e){let t=this.resolveStageDimension();this.width=t.width,this.onMeasurementsChange()}calculateHeights(){let t=this.getLanes().map(r=>r.getDimension().height).reduce((r,s)=>r+s,0);return{bodyHeight:t,layoutHeight:this.style.headerHeight+t+this.style.footerHeight}}resolveStageDimension(){let e=this.getTimelineHTMLElementRect(),t=this.calculateHeights();return{width:e.width>=this.style.stageMinWidth?e.width:this.style.stageMinWidth,height:t.layoutHeight}}getTimelineHTMLElementRect(){return{x:this.timelineHTMLElement.offsetLeft,y:this.timelineHTMLElement.offsetTop,width:this.timelineHTMLElement.offsetWidth,height:this.timelineHTMLElement.offsetHeight}}showThumbnailHover(e){if(e)if(this.thumbnailHover.setVisible(!0),this.thumbnailHover.getThumbnailVttCue()===e){this.thumbnailHover.setThumbnailVttCue(e);let t=this.resolveThumbnailPosition(this.thumbnailHover);this.thumbnailHover.setPosition(t),this.thumbnailHover.getCanvasNode().moveToTop()}else ct.createKonvaImageSizedByWidth(e.url,this.style.thumbnailHoverWidth).subscribe(t=>{this.thumbnailHover.setThumbnailVttCue(e),this.thumbnailHover.setDimension(t.getSize()),this.thumbnailHover.setImage(t),this.thumbnailHover.setPosition(this.resolveThumbnailPosition(this.thumbnailHover)),this.thumbnailHover.getCanvasNode().moveToTop()})}hideThumbnailHover(){this.thumbnailHover&&this.thumbnailHover.setVisible(!1)}resolveThumbnailPosition(e){let t=this.timecodedGroup.getRelativePointerPosition(),r=this.getTimecodedGroupDimension(),s=e.getImage().getSize(),n=t.x-s.width/2,a=e.style.strokeWidth>0?e.style.strokeWidth/2:0;n=n-a<0?a:n+s.width+a>r.width?r.width-s.width-a:n;let h=this.scrubberLane.getRect();return{x:n,y:h.y+h.height+e.style.strokeWidth/2+this.style.thumbnailHoverYOffset}}createScrollEvent(){return{scrollPercent:this.getHorizontalScrollPercent()}}createZoomEvent(){return{zoomPercent:this.getZoomPercent()}}getHorizontalScrollPercent(){if(this.isSnappedStart())return 0;if(this.isSnappedEnd())return 100;{let e=new Z(this.getTimecodedContainerDimension().width-this.getTimecodedGroupDimension().width).abs();return new Z(this.getTimecodedGroupPosition().x).abs().mul(100).div(e).toNumber()}}setHorizontalScrollPercent(e){this.setTimelinePosition(this.calculateTimelineXFromScrollPercent(e))}getScrollHandleHorizontalMeasurement(e){let t=this.getTimecodedGroupDimension().width,r=this.getTimecodedGroupPosition().x,s;return t<=e?s={width:e,x:0}:s={width:new Z(e).mul(e).div(t).round().toNumber(),x:new Z(r).abs().mul(e).div(t).toNumber()},s}scrollTo(e){return e=_e.coerce.number().min(0).max(100).parse(e),this.scrollToPercentEased(e)}scrollToPlayhead(){let e=-this.playhead.getPlayheadPosition()+this.getTimecodedContainerDimension().width/2;return this.scrollToEased(e)}scrollToPercent(e){let t=this.calculateTimelineXFromScrollPercent(e);this.scrollTimeline(t)}scrollToPercentEased(e){let t=this.calculateTimelineXFromScrollPercent(e);return this.scrollToEased(t)}scrollToEased(e){return new re(t=>{let r=this.getTimecodedGroupPosition().x;Js({layer:this.timecodedGroup.getLayer(),duration:F.TIMELINE_SCROLL_EASED_DURATION_MS,from:r,to:e,onUpdateHandler:(s,n)=>{this.scrollTimeline(n)},onCompleteHandler:(s,n)=>{t.next(this.getHorizontalScrollPercent()),t.complete()}})})}isPlayheadInTimecodedView(){return this.isInVisiblePositionRange(this.playhead.getPlayheadPosition())}updateScrollWithPlayhead(){let e=this.playhead.getPlayheadPosition(),t=e<this.getVisiblePositionRange().start,r=this.isInVisiblePositionRange(e);this.scrollWithPlayhead=r&&!t}syncTimelineWithPlayhead(){return new re(e=>{this.scrollToEased(-this.playhead.getPlayheadPosition()).pipe(ke(t=>{e.next(this.getHorizontalScrollPercent()),e.complete()})).subscribe()})}setTimelinePosition(e){let t=this.getConstrainedTimelineX(e);this.timecodedGroup.x(t)}scrollTimeline(e){let t=this.getTimecodedGroupPosition().x;this.setTimelinePosition(e),this.getTimecodedGroupPosition().x!==t&&(this.scrollbar.updateScrollHandle(this),this.setHorizontalScrollPercent(this.scrollbar.getScrollHandlePercent()),this.onScroll$.next(this.createScrollEvent()))}calculateTimelineXFromScrollPercent(e){e=this.getConstrainedScrollPercent(e);let t=this.getTimecodedGroupDimension(),r=this.getTimecodedContainerDimension();if(t.width>r.width){let s=new Z(r.width-t.width);return new Z(e).mul(s).div(100).toDecimalPlaces(2).toNumber()}else return 0}getZoomPercent(){let e=this.getTimecodedGroupDimension(),t=this.getTimecodedContainerDimension();return e.width>t.width?new Z(e.width).mul(100).div(t.width).round().toNumber():this.zoomBaseline}zoomTo(e){return e=_e.coerce.number().min(this.getZoomBaseline()).max(this.getZoomMax()).parse(e),this.zoomToEased(e)}zoomIn(){return new re(e=>{this.zoomStep("IN",this.timecodedGroup.getRelativePointerPosition().x),e.next(this.getZoomPercent()),e.complete()})}zoomOut(){return new re(e=>{this.zoomStep("OUT",this.timecodedGroup.getRelativePointerPosition().x),e.next(this.getZoomPercent()),e.complete()})}zoomToEased(e){return new re(t=>{e=this.getConstrainedZoomPercent(e);let r=this.getTimecodedGroupDimension().width,s=this.calculateWidthFromZoomRatioPercent(e);Js({layer:this.timecodedGroup.getLayer(),duration:F.TIMELINE_ZOOM_EASED_DURATION_MS,from:r,to:s,onUpdateHandler:(n,a)=>{this.zoomByWidth(a,this.resolveZoomFocus())},onCompleteHandler:(n,a)=>{t.next(this.getZoomPercent()),t.complete()}})})}zoomStep(e,t){let r=new Z(this.getTimecodedGroupDimension().width),s=(e==="IN"?r.mul(this.zoomScale):r.div(this.zoomScale)).round().toNumber();this.zoomByWidth(s,t)}zoomByPercent(e,t=!0){e=this.getConstrainedZoomPercent(e);let r=this.calculateWidthFromZoomRatioPercent(e);return this.zoomByWidth(r,this.resolveZoomFocus(),t),this.getZoomPercent()}zoomByWidth(e,t,r=!0){let s=this.getTimecodedGroupPosition().x,n=this.getTimecodedGroupDimension().width;e=this.getConstrainedWidth(e);let a=this.calculateNewPosition(e,t);this.hideThumbnailHover(),this.timecodedGroup.setAttrs({width:e,x:a}),this.timecodedGroupNodes.forEach(h=>{h.width(e)}),(this.getTimecodedGroupDimension().width!==n||this.getTimecodedGroupPosition().x!==s)&&(r?this.scrollbar.updateScrollHandle(this):this.playheadHover.toggleVisible(!1),this.setHorizontalScrollPercent(this.scrollbar.getScrollHandlePercent()),this.onZoom$.next(this.createZoomEvent()),this.onScroll$.next(this.createScrollEvent()))}calculateNewPosition(e,t=0){let r=this.getTimecodedGroupPosition().x,s=this.getTimecodedGroupDimension().width,n=this.getTimecodedContainerRect(),a=e>s?"IN":"OUT",o=r;if(e===n.width)o=0;else if(e>n.width){if(t>0){let h=new Z(t).div(s);if(h.greaterThanOrEqualTo(0)&&h.lessThanOrEqualTo(1)){let l=e-s,d=h.mul(l).abs().round().toNumber(),u=r+d*(a==="IN"?-1:1);o=u<0?u:0}}if(e>n.width){let h=n.x+n.width;o+e<=h&&(o=n.width-e)}}return o}resolveZoomFocus(){return this.videoController.isVideoLoaded()?this.resolvePlayheadSyncPosition():this.isSnappedStart()?0:this.isSnappedEnd()?this.getTimecodedGroupDimension().width:this.getTimecodedGroupDimension().width/2}calculateWidthFromZoomRatioPercent(e){return new Z(this.getTimecodedContainerDimension().width).mul(e).div(100).round().toNumber()}getConstrainedWidth(e){let t=this.getTimecodedContainerDimension();return e>=t.width?e<=this.maxTimecodedGroupWidth?e:this.maxTimecodedGroupWidth:t.width}getConstrainedZoomPercent(e){return e<this.zoomBaseline?this.zoomBaseline:e>this.zoomMax?this.zoomMax:e}getConstrainedScrollPercent(e){return e<0?0:e>100?100:e}playheadHoverMove(e){if(this.videoController.isVideoLoaded()&&this.playheadHover){let t=!1;if(!this.videoController.isPlaying()){let r=this.resolvePlayheadSyncPosition();e>r-this.playheadHoverSnapArea&&e<r+this.playheadHoverSnapArea&&(e=r,t=!0)}this.playheadHover.sync(e,t)}}resolvePlayheadSyncPosition(){return this.timeToTimelinePosition(this.videoController.getCurrentTime())}onVideoLoadedEvent(e){this.fireVideoEventBreaker(),this.clearContent(),this.syncVideoMetadata(),this.videoController.onVideoTimeChange$.pipe(k(this.videoEventBreaker$)).subscribe(t=>{this.syncVideoMetadata()}),this.videoController.onPlay$.pipe(k(this.videoEventBreaker$)).subscribe(t=>{this.updateScrollWithPlayhead()})}fireVideoEventBreaker(){Ge(this.videoEventBreaker$),this.videoEventBreaker$=new V}setThumbnailVttFile(e){this.thumbnailVttFile=e}syncVideoMetadata(){this.scrollWithPlayhead&&!this.isPlayheadInTimecodedView()&&!this.syncTimelineWithPlayheadInProgress&&(this.syncTimelineWithPlayheadInProgress=!0,this.syncTimelineWithPlayhead().subscribe(e=>{this.syncTimelineWithPlayheadInProgress=!1}))}addLane(e){if(this.timelineLanesMap.has(e.getId()))throw new Error(`TimelineLane with id=${e.getId()} already exist`);let t=this.timelineLanes.length<1,r={...F.POSITION_TOP_LEFT};t||(r.y=this.timelineLanes.map(s=>s.getRect().height).reduce((s,n)=>s+n,0)),e.setTimeline(this),e.setVideoController(this.videoController),e.setTimelinePosition(r),e.initCanvasNode(),this.timelineLanes.push(e),this.timelineLanesMap.set(e.getId(),e),this.bodyContentGroup.add(e.getCanvasNode()),this.settleLayout()}removeLane(e){if(!this.timelineLanesMap.has(e))throw new Error(`TimelineLane with id=${e} doesn't exist`);let t=this.timelineLanesMap.get(e);this.timelineLanes.splice(this.timelineLanes.findIndex(s=>s.getId()===e),1),this.timelineLanesMap.delete(e),t.clearContent(),t.destroy();let r={...F.POSITION_TOP_LEFT};this.timelineLanes.forEach(s=>{s.setTimelinePosition({...r}),r.y=r.y+s.getRect().height}),this.timelineLanes.forEach(s=>{s.onMeasurementsChange()}),this.settleLayout()}getScrollbar(){return this.scrollbar}addLanes(e){e.forEach(t=>this.addLane(t))}getLanes(){return[...this.timelineLanesMap.values()]}getLane(e){return this.timelineLanesMap.get(e)}getScrubberLane(){return this.getLane(La)}getMarkerLane(e){let t=this.getLane(e);return t instanceof Ws?t:void 0}getThumbnailLane(e){let t=this.getLane(e);return t instanceof Ks?t:void 0}getSubtitlesLane(e){let t=this.getLane(e);return t instanceof qs?t:void 0}getAudioTrackLane(e){let t=this.getLane(e);return t instanceof Fl?t:void 0}createMarkerLane(e){let t=new Ws(e);return this.addLane(t),t}createThumbnailLane(e){let t=new Ks(e);return this.addLane(t),t}createSubtitlesLane(e){let t=new qs(e);return this.addLane(t),t}isTimelineReady(){return this.videoController.isVideoLoaded()}addToTimecodedBaseGroup(e){this.timecodedBaseGroup.add(e)}addToTimecodedSurfaceGroup(e){this.timecodedSurfaceGroup.add(e)}addToTimecodedMarkersGroup(e){this.timecodedMarkersGroup.add(e)}addToTimecodedThumbnailsGroup(e){this.timecodedThumbnailsGroup.add(e)}addToTimecodedSubtitlesGroup(e){this.timecodedSubtitlesGroup.add(e)}addToTimecodedAudioGroup(e){this.timecodedAudioGroup.add(e)}constrainTimelinePosition(e){let t=this.getTimecodedGroupDimension();return e<0?0:e>t.width?t.width:e}timelinePositionToTime(e){let t=this.constrainTimelinePosition(e);return this.videoController.isVideoLoaded()?new Z(t).mul(this.videoController.getDuration()).div(this.getTimecodedGroupDimension().width).toNumber():0}timelinePositionToTimeFormatted(e){return this.videoController.isVideoLoaded()?this.videoController.formatTimestamp(this.timelinePositionToTime(e)):""}timelinePositionToFrame(e){return this.videoController.isVideoLoaded()?this.videoController.calculateTimeToFrame(this.timelinePositionToTime(e)):0}timeToTimelinePosition(e){return new Z(e).mul(this.getTimecodedGroupDimension().width).div(this.videoController.getDuration()).toNumber()}getConstrainedTimelineX(e){let t=this.getTimecodedGroupDimension(),r=this.getTimecodedContainerDimension();if(t.width<=r.width)return 0;{let s=r.width-t.width;return e<s?s:e>0?0:e}}getBodyGroupRect(){return{...this.bodyGroup.getPosition(),...this.bodyGroup.getSize()}}getLeftPanelRect(){return{...this.leftPanel.getPosition(),...this.leftPanel.getSize()}}getLeftPanelVisible(){return this.leftPanelVisible}getRightPanelRect(){return{...this.rightPanel.getSize(),...this.rightPanel.getPosition()}}getTimecodedContainerDimension(){return this.timecodedContainer.getSize()}getTimecodedContainerPosition(){return this.timecodedContainer.getPosition()}getTimecodedContainerRect(){return{...this.getTimecodedContainerDimension(),...this.getTimecodedContainerPosition()}}getTimecodedGroupDimension(){return this.timecodedGroup.getSize()}getTimecodedGroupPosition(){return this.timecodedGroup.getPosition()}getTimecodedGroupRect(){return{...this.timecodedGroup.getPosition(),...this.timecodedGroup.getSize()}}getTimecodedGroupHorizontalMeasurement(){return{x:this.timecodedGroup.x(),width:this.timecodedGroup.width()}}getRelativePointerPosition(){return this.timecodedGroup.getRelativePointerPosition()}getLayoutGroupDimension(){return this.layoutGroup.getSize()}getLayoutGroupPosition(){return this.layoutGroup.getPosition()}getRect(){return{...this.getLayoutGroupDimension(),...this.getLayoutGroupPosition()}}getVisiblePositionRange(){let e=Math.abs(this.timecodedGroup.x()),t=e+this.timecodedContainer.width();return{start:e,end:t}}isInVisiblePositionRange(e){let t=this.getVisiblePositionRange();return e>=t.start&&e<=t.end}isSnappedStart(){return this.getTimecodedGroupPosition().x===0}isSnappedEnd(){return this.getTimecodedContainerDimension().width-this.getTimecodedGroupDimension().width===this.getTimecodedGroupPosition().x}getVisibleTimeRange(){let e=this.getVisiblePositionRange(),t=this.timelinePositionToTime(e.start),r=this.timelinePositionToTime(e.end);return{start:t,end:r}}getZoomBaseline(){return this.zoomBaseline}getZoomMax(){return this.zoomMax}fetchThumbnailVttFile(){return this.thumbnailVttUrl?ls.create(this.thumbnailVttUrl,this.axiosConfig).pipe(ke(e=>(this.thumbnailVttFile=e,e)),yi((e,t)=>Se(void 0))):Se(void 0)}toggleLeftPanelVisible(e){this.leftPanelVisible=e,this.leftPanel.visible(e),this.settleLayout(),this.timelineLanes.forEach(t=>{t.onMeasurementsChange()}),this.headerTimecodeDisplay.setVisible(!e)}clearContent(){this.setThumbnailVttFile(void 0),this.timelineLanes.forEach(e=>{e.clearContent()}),this.zoomByPercent(this.zoomBaseline)}destroy(){this.timelineHTMLElement=void 0,this.videoController=void 0,this.thumbnailVttFile=void 0,pn(this.videoEventBreaker$);let e=[this.onScroll$,this.onZoom$];Vt(...e),bi(...e),[this.scrollbar,this.playheadHover,this.playhead,...this.timelineLanes,this.thumbnailHover,this.headerTimecodeDisplay].forEach(r=>{r&&r.destroy()}),super.destroy()}}class Qs{static timeToFrame(e,t){return t.mul(e).floor().toNumber()}static frameToTime(e,t){return new Z(e).dividedBy(t).toNumber()}}class ri{constructor(){this.resolveUserAgent()}static instance(){return ri._instance||(ri._instance=new ri),ri._instance}resolveUserAgent(){this._userAgent=window.navigator&&window.navigator.userAgent||"",this._isAndroid=/Android/i.test(this._userAgent),this._isFirefox=/Firefox/i.test(this._userAgent),this._isEdge=/Edg/i.test(this._userAgent),this._isChromium=/Chrome/i.test(this._userAgent)||/CriOS/i.test(this._userAgent),this._isChrome=!this.isEdge&&this.isChromium,this._isSafari=/Safari/i.test(this._userAgent)&&!this.isChrome&&!this.isAndroid&&!this.isEdge}get isSafari(){return this._isSafari}get isFirefox(){return this._isFirefox}get isEdge(){return this._isEdge}get isChromium(){return this._isChromium}get isChrome(){return this._isChrome}get isAndroid(){return this._isAndroid}}const tt=class{static formatVideoTimestamp(i,e){if(i<=0)return tt.VIDEO_ZERO_TIMESTAMP;const t=Math.floor(i/3600),r=Math.floor(i%3600/60),s=Math.floor(i%60);let n=new Z(Qs.timeToFrame(i,e)).mod(e).toNumber();return`${tt.padZero(t)}:${tt.padZero(r)}:${tt.padZero(s)}:${tt.padZero(n)}`}static padZero(i,e=2){return i.toString().padStart(e,"0")}};let en=tt;en.VIDEO_ZERO_TIMESTAMP=`${tt.padZero(0)}:${tt.padZero(0)}:${tt.padZero(0)}:${tt.padZero(0)}`;class Km{constructor(){this._state={playing:!1,paused:!0,waiting:!1,seeking:!1,buffering:!1,ended:!1},this.onChange$=new ti(this._state)}updateState(e){let t={...this._state,...e},r=this.compare(this._state,t)===0;this._state=t,r||this.onChange$.next(this._state)}compare(e,t){return e.playing===t.playing&&e.paused===t.paused&&e.waiting===t.waiting&&e.seeking===t.seeking&&e.buffering===t.buffering&&e.ended===t.ended?0:-1}get state(){return this._state}setPlaying(){this.updateState({playing:!0,paused:!1,waiting:!1,seeking:!1,buffering:!1,ended:!1})}setPaused(){this.updateState({playing:!1,paused:!0,waiting:!1,seeking:!1,buffering:!1,ended:!1})}setEnded(){this.updateState({playing:!1,paused:!0,waiting:!1,seeking:!1,buffering:!1,ended:!0})}set waiting(e){this.updateState({waiting:e})}set seeking(e){this.updateState({seeking:e,ended:!1})}set buffering(e){this.updateState({buffering:e})}}function Ra(i){let e;return typeof i=="string"?e=i:i instanceof st?(console.log(i),e=i.errors.map(t=>t.message).join(". ")):i instanceof Error?e=i.message:e="Unexpected error",e}function Jm(i){return{errorMap:(e,t)=>({message:i})}}const Be={PAUSE:"pause",WAITING:"waiting",PLAYING:"playing",TIMEUPDATE:"timeupdate",SEEKING:"seeking",SEEKED:"seeked",LOADEDDATA:"loadeddata",LOADEDMETEDATA:"loadedmetadata",ENDED:"ended",PROGRESS:"progress"};class Qm{constructor(e,t){if(this.browserProvider=ri.instance(),this.helpMenuGroups=[],this._isVideoLoaded=!1,this.frameDurationSpillOverCorrection=.001,this.syncLoopMaxIterations=20,this.seekInProgress=!1,this.videoStalledCheckIntervalMs=700,this.videoFrameCallback$=new ti(null),this.videoEventBreaker$=new V,this.onDestroy$=new V,this.seekBreaker$=new V,this.onVideoLoaded$=new ti(void 0),this.onVideoLoading$=new V,this.onPlay$=new V,this.onPause$=new V,this.onVideoTimeChange$=new V,this.onSeeking$=new V,this.onSeeked$=new V,this.onBuffering$=new V,this.onEnded$=new V,this.onAudioSwitched$=new V,this.onPlaybackState$=new V,this.onHelpMenuChange$=new ti(void 0),this.onVideoError$=new V,this.domController=e,this.crossorigin=t,this.videoElement=this.domController.videoElement,this.videoElement.crossOrigin=this.crossorigin,!this.videoElement)throw new Error("VideoController element not set");this.videoFrameCallback$.pipe(k(this.onDestroy$)).subscribe(r=>{r&&(this.seekInProgress||(this.isPlaying()?this.videoTimeChangeHandlerExecutor():this.isPaused()))})}loadVideo(e,t,r){try{return e=li.url()(e),t=_e.coerce.number().min(0).max(100).parse(t,Jm("Invalid frameRate")),this.onVideoLoading$.next({sourceUrl:e,frameRate:t}),this._isVideoLoaded=!1,this.video=void 0,this.detachVideoEventListeners(),this.videoLoad(e,t,r).pipe(ke(s=>{this.video=s,this.frameRateDecimal=new Z(this.video.frameRate),this.syncStepCurrentTimeMediaTime=0,this.playbackStateMachine=new Km,this.initEventHandlers(),this.startVideoFrameCallback(),this._isVideoLoaded=!0,this.onVideoLoaded$.next({video:this.video});let n=Number.parseFloat(this.getDuration().toFixed(3));return Number.isInteger(Number.parseFloat((this.getDuration()*this.video.frameRate).toFixed(1)))&&(n=Number.parseFloat((n-this.frameDurationSpillOverCorrection).toFixed(3)),this.video.setCorrectedDuration(n)),this.getHls().on(Ze.Events.FRAG_LOADED,(a,o)=>{o.frag.endList&&o.frag.type=="main"&&this.getCorrectedDuration()>o.frag.start+o.frag.duration&&this.video.setCorrectedDuration(Number.isInteger(o.frag.start+o.frag.duration*this.video.frameRate)?o.frag.start+o.frag.duration-this.frameDurationSpillOverCorrection:o.frag.start+o.frag.duration)}),s}),yi((s,n)=>{let a=Ra(s);return this.onVideoError$.next({type:"VIDEO_LOAD_ERROR",message:a}),ia(()=>new Error(a))}))}catch(s){let n=Ra(s);return this.onVideoError$.next({type:"VIDEO_LOAD_ERROR",message:n}),ia(()=>new Error(n))}}initEventHandlers(){be(this.videoElement,Be.PAUSE).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.getCurrentTime()>=this.getCorrectedDuration()?this.getTotalFrames():this.getCurrentFrame(),this.getCurrentTime()<this.getCorrectedDuration()?this.seekToFrame(this.getCurrentTime()>=this.getCorrectedDuration()?this.getTotalFrames():this.getCurrentFrame()).subscribe(t=>{this.videoTimeChangeHandlerExecutor(),this.onPause$.next({})}):this.syncVideoFrames({}).subscribe(t=>{this.videoTimeChangeHandlerExecutor(),this.onPause$.next({})})}),be(this.videoElement,Be.WAITING).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.waiting=!0}),be(this.videoElement,Be.PLAYING).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.setPlaying(),this.videoStalledCheckLastCurrentTime=void 0}),be(this.videoElement,Be.PAUSE).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.setPaused(),this.videoStalledCheckLastCurrentTime=void 0}),be(this.videoElement,Be.PROGRESS).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.onBuffering$.next({bufferedTimespans:this.getBufferedTimespans()})}),be(this.videoElement,Be.ENDED).pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.onEnded$.next({})}),this.playbackStateMachine.onChange$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.onPlaybackState$.next(e)}),this.onPlay$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.setPlaying(),this.videoStalledCheckLastCurrentTime=void 0}),this.onPause$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.setPaused(),this.videoStalledCheckLastCurrentTime=void 0}),this.onSeeking$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.seeking=!0}),this.onSeeked$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.seeking=!1}),this.onEnded$.pipe(k(this.videoEventBreaker$)).subscribe(e=>{this.playbackStateMachine.setEnded(),this.videoStalledCheckLastCurrentTime=void 0}),Xu(this.videoStalledCheckIntervalMs).pipe(k(this.videoEventBreaker$)).subscribe(e=>{let t=this.getCurrentTime();if(!this.videoStalledCheckLastCurrentTime){this.videoStalledCheckLastCurrentTime=t;return}if(this.playbackStateMachine.state.playing){let r=this.videoStalledCheckIntervalMs*.8/1e3*this.getPlaybackRate(),s=this.videoStalledCheckLastCurrentTime+r,n=t<s;this.playbackStateMachine.waiting=n,this.videoStalledCheckLastCurrentTime=t}})}getBufferedTimespans(){if(!this.isVideoLoaded())return[];let e=[],t=this.videoElement.buffered;for(let r=0;r<t.length;r++)e.push({start:t.start(r),end:t.end(r)});return e}startVideoFrameCallback(){let e=()=>{this.videoElement?this.videoFrameCallbackHandle=this.videoElement.requestVideoFrameCallback((r,s)=>{t({now:r,metadata:s})}):console.debug("Cannot call requestVideoFrameCallback, videoElement not found")},t=r=>{this.videoFrameCallback$.next(r),e()};e()}detachVideoEventListeners(){Ge(this.videoEventBreaker$),this.videoEventBreaker$=new V,this.videoElement&&this.videoFrameCallbackHandle&&this.videoElement.cancelVideoFrameCallback(this.videoFrameCallbackHandle)}syncVideoFrames(e){return console.debug("syncFrames - START",e),new re(t=>{let r=new ti(!1),s=new V,n=this.syncLoopMaxIterations;this.seekBreaker$.pipe(k(s)).subscribe(()=>{console.debug("%csyncFrames - seek breaker triggered","color: gray"),r.next(!0),a()});let a=()=>{Ge(s),t.next(!0),t.complete(),console.debug("%csyncFrames - END","color: gray")},o=h=>{r.pipe($e(1)).subscribe(l=>{l?console.debug("%csyncFrames - seek skipped, breaker already triggered","color: gray"):this._seekTimeFireAndForget(h)})};if(this.isPlaying())console.debug("%csyncFrames - SKIPPED: video is playing","color: gray"),a();else if(this.getCorrectedDuration()<=this.getCurrentTime())console.debug("%csyncFrames - SKIPPED: video exceeded duration","color: magenta"),a();else{let h=u=>{let c=this.getCurrentTime(),p=this.calculateTimeToFrame(c),f=u?u.metadata.mediaTime:void 0,m=f?this.calculateTimeToFrame(f):void 0;if(this.isPlaying())return console.debug("%csyncFrames - UNKNOWN: video is playing","color: gray"),!0;if(p===0)return console.debug(`%csyncFrames - OK: currentTimeFrame[${p}] === 0`,"color: green"),!0;if(e.seekToFrame){if(e.seekToFrame===p&&(p===m||!m))return console.debug(`%csyncFrames - OK: ((currentTimeFrame[${p}] === mediaTimeFrame[${m}]) || !mediaTimeFrame[${m}])`,"color: green"),!0}else if(p===m||!m)return console.debug(`%csyncFrames - OK: currentTimeFrame[${p}] === mediaTimeFrame[${m}]`,"color: green"),!0;return!1},l,d=u=>{let c=this.syncLoopMaxIterations-n;if(console.debug(`syncFrames.syncLoop - START (${c})`,{syncConditions:e,videoFrameCallbackData:u,dropped:this.videoElement.getVideoPlaybackQuality()}),this.isPlaying()){a();return}if(h(u)){a();return}let p=this.getCurrentTime(),f=this.calculateTimeToFrame(p),m=u?u.metadata.mediaTime:void 0,g=m?this.calculateTimeToFrame(m):void 0;if(n--<=0){console.debug(`%csyncFrames - TOO MANY SYNCs, EXITING.. : currentTime[${p}], mediaTime[${m}], currentTimeFrame[${f}], mediaTimeFrame[${g}]`,"color: red"),a();return}if(console.debug(`syncFrames - currentTime[${p}|${this.formatTimestamp(p)}], mediaTime[${m}|${this.formatTimestamp(m)}], currentTimeFrame[${f}], mediaTimeFrame[${g}], `),e.seekToFrame)if(l||(l=p),e.seekToFrame===f)if(f===g||!g)console.debug(`%csyncFrames - OK: ((currentTimeFrame[${f}] === mediaTimeFrame[${g}]) || !mediaTimeFrame[${g}])`,"color: green"),a();else{console.debug(`%csyncFrames - CORRECTION SEEK TO FRAME; currentTimeFrame[${f}] ${f>g?">":"<"} mediaTimeFrame[${g}]`,"color: red");let _=Math.abs(f-g);console.debug(`%csyncFrames - frameDiff: ${_}`,"color: orange");let w=this.syncStepCurrentTimeMediaTime*(f>g?1:-1);o(Z.add(p,w).toNumber())}else{console.debug(`%csyncFrames - CORRECTION SEEK TO FRAME; syncConditions.seekToFrame[${e.seekToFrame}] !== currentTimeFrame[${f}] | seekToFrameTimeBaseline=${l}`,"color: red");let _=Math.abs(e.seekToFrame-f),w=_*this.video.frameDuration,T=(e.seekToFrame>=f?Z.add(l,w):Z.sub(l,w)).toNumber();l=T,console.debug(`%csyncFrames - frameDiff: ${_}`,"color: orange"),console.debug(`%csyncFrames - frameCorrectionTime: ${w}`,"color: orange"),console.debug(`%csyncFrames - seekTo: ${T}`,"color: orange"),o(T)}else f===g||!g?(console.debug(`%csyncFrames - OK: currentTimeFrame[${f}] === mediaTimeFrame[${g}]`,"color: green"),a()):(console.debug(`%csyncFrames - CORRECTION; currentTimeFrame[${f}] ${f>g?">":"<"} mediaTimeFrame[${g}]`,"color: red"),c===0?o(p):f>g?o(Z.add(p,this.syncStepCurrentTimeMediaTime).toNumber()):o(m+this.syncStepCurrentTimeMediaTime));console.debug("syncFrames.syncLoop - END")};this.videoFrameCallback$.pipe(Ju((e.seekToFrame,0)),k(s)).subscribe(u=>{console.debug("syncFrames.syncLoop - videoFrameCallback$ trigger",u),d(u)})}})}seekTimeAndSync(e,t={}){return new re(r=>{this.seekInProgress&&(Ge(this.seekBreaker$),this.seekBreaker$=new V),this.seekInProgress=!0,isNaN(e)||(e=e<0?0:e>this.getDuration()?this.getDuration():e,be(this.videoElement,Be.SEEKING).pipe(k(this.seekBreaker$),$e(1)).subscribe(s=>{this.onSeeking$.next({newTime:e,currentTime:this.getCurrentTime()})}),be(this.videoElement,Be.SEEKED).pipe(k(this.seekBreaker$),$e(1)).subscribe(s=>{this.syncVideoFrames(t).subscribe(n=>{this.getCorrectedDuration()>this.getHTMLVideoElement().duration&&this.video.setCorrectedDuration(Number.isInteger(this.getHTMLVideoElement().duration*this.video.frameRate)?this.getHTMLVideoElement().duration-this.frameDurationSpillOverCorrection:this.getHTMLVideoElement().duration);let a=()=>{this.seekInProgress=!1,r.next(!0),r.complete(),this.videoTimeChangeHandlerExecutor()};this.getCurrentTime()>this.getCorrectedDuration()?this.seekTimeWithoutSync(this.getCorrectedDuration()).pipe(k(this.seekBreaker$),$e(1)).subscribe(()=>{this.onEnded$.next({}),a()}):(this.onSeeked$.next({currentTime:this.getCurrentTime()}),a())})}),console.debug(`Seeking to timestamp: ${e} ${this.formatTimestamp(e)}`),this.setCurrentTime(e))})}seekTimeWithoutSync(e){return new re(t=>{this.seekInProgress&&(Ge(this.seekBreaker$),this.seekBreaker$=new V),this.seekInProgress=!0,isNaN(e)||(e=e<0?0:e>this.getDuration()?this.getDuration():e,be(this.videoElement,Be.SEEKING).pipe(k(this.seekBreaker$),$e(1)).subscribe(r=>{this.onSeeking$.next({newTime:e,currentTime:this.getCurrentTime()})}),be(this.videoElement,Be.SEEKED).pipe(k(this.seekBreaker$),$e(1)).subscribe(r=>{this.onSeeked$.next({currentTime:this.getCurrentTime()}),this.seekInProgress=!1,t.next(!0),t.complete(),this.videoTimeChangeHandlerExecutor()}),console.debug(`Seeking to timestamp: ${e} ${this.formatTimestamp(e)}`),this.setCurrentTime(e))})}_seekTimeFireAndForget(e){if(!isNaN(e)){let t=this.getCurrentTime();e=e<0?0:e>this.getDuration()?this.getDuration():e;let r=e===t?"NONE":e>t?"FORWARD":"BACKWARD",s=Z.sub(t,e).abs();console.debug(`Seeking from currentTime[${t}] to newTime[${e}], direction: ${r} ${s.toNumber()}`),this.setCurrentTime(e)}}_seekTimeAndSyncNoEmitEvents(e){return this.isPlaying()?Se(!1):new re(t=>{isNaN(e)||(e=e<0?0:e>this.getDuration()?this.getDuration():e,be(this.videoElement,Be.SEEKED).pipe(ui()).subscribe(r=>{this.syncVideoFrames({}).subscribe(s=>{t.next(!0),t.complete(),this.videoTimeChangeHandlerExecutor()})}),console.debug(`Seeking ${e}`),this.setCurrentTime(e))})}seekFromCurrentTimeAndSync(e,t={}){let r=this.getCurrentTime();t.currentTime&&(r=t.currentTime);let s=Z.add(r,e).toNumber(),n;t.seekDirection?n=t.seekDirection:n=s===r?"NONE":s>r?"FORWARD":"BACKWARD";let a=Z.sub(r,s).abs().toNumber();return console.debug(`Seeking from currentTime ${r} to ${s}, direction: ${n} ${a}`),this.seekTimeAndSync(s,t)}setCurrentTime(e){this.videoElement.currentTime=e}getFrameRateDecimal(){return this.frameRateDecimal}_seekToFrame(e){if(!this.isPlaying()&&!isNaN(e)){if(console.debug(`Seeking to frame: ${e}`),e<=0)return this.seekTimeAndSync(0,{});{let t=this.calculateFrameToTime(e)+new Z(this.frameDurationSpillOverCorrection).toNumber(),r=this.calculateTimeToFrame(t);return r!==e&&e!=this.getCorrectedDuration()*this.getFrameRate()?(console.error(`Frame numbers don't match. Wanted: ${e}, calculated: ${r}`),Se(!1)):this.seekTimeAndSync(t,{seekToFrame:e,seekToTimestamp:t,currentTime:this.getCurrentTime()}).pipe(ke(s=>s))}}}_seekFromCurrentFrame(e){let t=this.getCurrentFrame(),r=t+e;if(console.debug(`seekFromCurrentFrame - Current frame: ${t}, wanted frame: ${r}`),t!==r){if(r<=0)return this._seekToFrame(0);if(r>=this.getTotalFrames()||r>=this.getCorrectedDuration()*this.getFrameRate()&&!this.playbackStateMachine.state.ended)return this._seekToFrame(this.getCorrectedDuration()*this.getFrameRate());if(r>=this.getTotalFrames()||r>=this.getCorrectedDuration()*this.getFrameRate()&&this.playbackStateMachine.state.ended)return Se(!1);{let s=this.calculateFrameToTime(e),n=t/this.getFrameRate()+this.frameDurationSpillOverCorrection;return this.seekFromCurrentTimeAndSync(s,{seekToFrame:r,currentTime:n,seekDirection:e>0?"FORWARD":"BACKWARD"}).pipe(ke(a=>a))}}else return Se(!0)}videoTimeChangeHandlerExecutor(){let e=this.getCurrentTime(),t=this.getCurrentFrame();this.onVideoTimeChange$.next({currentTime:e,frame:t})}getPlaybackState(){return this.playbackStateMachine.state}getVideo(){return this.isVideoLoaded()?this.video:void 0}getHTMLVideoElement(){return this.videoElement}calculateTimeToFrame(e){return Qs.timeToFrame(e,this.getFrameRateDecimal())}calculateFrameToTime(e){return Qs.frameToTime(e,this.getFrameRateDecimal())}play(){this.isVideoLoaded()&&!this.isPlaying()&&this.videoElement.play().then(()=>{this.onPlay$.next({})})}pause(){this.isVideoLoaded()&&this.isPlaying()&&this.videoElement.pause()}togglePlayPause(){this.isPlaying()?this.pause():this.play()}isPlaying(){return this.isVideoLoaded()&&this.videoElement.currentTime>0&&this.videoElement.currentTime<this.getDuration()&&!this.videoElement.paused&&!this.videoElement.ended&&this.videoElement.readyState>this.videoElement.HAVE_CURRENT_DATA}isPaused(){return!this.isPlaying()}isSeeking(){return this.seekInProgress}getCurrentTime(){return this.isVideoLoaded()?this.videoElement.currentTime:0}getPlaybackRate(){return this.isVideoLoaded()?this.videoElement.playbackRate:0}setPlaybackRate(e){if(this.isVideoLoaded()){try{e=_e.coerce.number().min(.1).max(16).default(1).parse(e)}catch{e=1}this.videoElement.playbackRate=e}}getVolume(){return this.isVideoLoaded()?this.videoElement.volume:0}setVolume(e){if(this.isVideoLoaded()){try{e=_e.coerce.number().min(0).max(1).default(1).parse(e)}catch{e=1}this.videoElement.volume=e}}getDuration(){return this.isVideoLoaded()?this.video.duration:0}getCorrectedDuration(){return this.isVideoLoaded()?this.video.correctedDuration:0}getFrameRate(){return this.isVideoLoaded()?this.video.frameRate:0}getTotalFrames(){return this.isVideoLoaded()?this.video.totalFrames:0}getCurrentFrame(){return this.isVideoLoaded()?this.calculateTimeToFrame(this.getCurrentTime()):0}seekToFrame(e){return!this.isVideoLoaded()||this.playbackStateMachine.state.ended&&e>=this.getCurrentFrame()?Se(!1):(e=_e.coerce.number().min(0).max(this.getTotalFrames()).parse(e),this._seekToFrame(e))}seekFromCurrentFrame(e){return this.isVideoLoaded()?(e=_e.coerce.number().parse(e),this._seekFromCurrentFrame(e)):Se(!1)}seekPreviousFrame(){return this.isVideoLoaded()?this.seekFromCurrentFrame(-1):Se(!1)}seekNextFrame(){return this.isVideoLoaded()?this.seekFromCurrentFrame(1):Se(!1)}seekToTimestamp(e){return!this.isVideoLoaded()||this.playbackStateMachine.state.ended&&e>=this.getCorrectedDuration()?Se(!1):(e=_e.coerce.number().parse(e),e>this.getCorrectedDuration()&&(e=this.getCorrectedDuration()),this.seekTimeAndSync(e,{seekToTimestamp:e,seekDirection:e===this.getCurrentTime()?"NONE":e>this.getCurrentTime()?"FORWARD":"BACKWARD"}))}formatTimestamp(e){return this.isVideoLoaded()?(e=_e.coerce.number().min(0).parse(e),en.formatVideoTimestamp(e,this.getFrameRateDecimal())):en.VIDEO_ZERO_TIMESTAMP}mute(){this.isVideoLoaded()&&(this.videoElement.muted=!0)}unmute(){this.isVideoLoaded()&&(this.videoElement.muted=!1)}isFullscreen(){return this.isVideoLoaded()?this.domController.isFullscreen():!1}toggleFullscreen(){this.isVideoLoaded()&&this.domController.toggleFullscreen(this.videoElement)}getAudioTracks(){throw new Error("unsupported")}getCurrentAudioTrack(){throw new Error("unsupported")}setAudioTrack(e){throw new Error("unsupported")}isVideoLoaded(){return this._isVideoLoaded}getHls(){throw new Error("Unsupported or video not loaded with Hls.js")}addHelpMenuGroup(e){this.helpMenuGroups.push(e),this.onHelpMenuChange$.next()}getHelpMenuGroups(){return this.helpMenuGroups}destroy(){pn(this.videoEventBreaker$,this.seekBreaker$),Vt(this.videoFrameCallback$);let e=[this.onVideoLoaded$,this.onVideoLoading$,this.onPlay$,this.onPause$,this.onVideoTimeChange$,this.onSeeking$,this.onSeeked$,this.onBuffering$,this.onEnded$,this.onAudioSwitched$,this.onPlaybackState$,this.onHelpMenuChange$,this.onVideoError$];Vt(...e),bi(...e);try{this.getHls()&&(this.getHls().removeAllListeners(),this.getHls().destroy())}catch(t){console.error(t)}Ge(this.onDestroy$),this.videoElement=null,this.domController=null,this._isVideoLoaded=!1,this.playbackStateMachine=null}}class eg{constructor(e,t,r,s){this._element=e,this._sourceUrl=t,this._frameRate=r,this._duration=s,this._totalFrames=new Z(this._duration).mul(this._frameRate).ceil().toNumber(),this._frameDuration=new Z(1).div(this._frameRate).toNumber()}get element(){return this._element}get sourceUrl(){return this._sourceUrl}get frameRate(){return this._frameRate}get duration(){return this._duration}get totalFrames(){return this._totalFrames}get frameDuration(){return this._frameDuration}get correctedDuration(){return this._correctedDuration}setCorrectedDuration(e){console.debug(`%cVideo duration correction: initialDuration:${this.duration} > updatedDuration:${e} `,"color: magenta"),this._correctedDuration=e}}class tg extends Qm{constructor(e,t){super(e,t),Ze.isSupported()?console.debug("video load with hls.js"):console.error("hls is not supported through MediaSource extensions");let r={...Ze.DefaultConfig,enableWorker:!1};this.hls=new Ze(r)}videoLoad(e,t,r){return new re(s=>{this.hls.on(Ze.Events.ERROR,function(h,l){l.type;let d=l.details;l.fatal,d.includes("audioTrackLoadError")||(s.error(`Error loading video. Hls error details: ${d}`),s.complete())});let n=new re(h=>{this.hls.once(Ze.Events.MEDIA_ATTACHED,function(l,d){console.debug("video element and hls.js are now bound together"),h.next(!0),h.complete()})}),a=new re(h=>{this.hls.once(Ze.Events.MANIFEST_PARSED,function(l,d){console.debug("manifest loaded, found "+d.levels.length+" quality level"),h.next(!0),h.complete()})}),o=be(this.videoElement,Be.LOADEDDATA).pipe(ui());$u([n,a,o]).pipe(ui()).subscribe(h=>{r=r&&_e.coerce.number().parse(r),r=r||this.videoElement.duration;let l=new eg(this.videoElement,e,t,r);s.next(l),s.complete()}),this.hls.loadSource(e),this.hls.attachMedia(this.videoElement)})}initEventHandlers(){super.initEventHandlers(),this.hls.on(Ze.Events.ERROR,function(e,t){t.type,t.details,t.fatal,console.error(e,t),t.details===Ze.ErrorDetails.BUFFER_STALLED_ERROR||t.details===Ze.ErrorDetails.BUFFER_APPEND_ERROR||(t.details,Ze.ErrorDetails.BUFFER_APPENDING_ERROR)})}getAudioTracks(){return this.isVideoLoaded?this.hls.audioTracks:null}getCurrentAudioTrack(){return this.getAudioTracks()[this.hls.audioTrack]}setAudioTrack(e){if(!this.isVideoLoaded)return null;let t=this.hls.audioTrack;this.hls.audioTrack=e;let r=this.hls.audioTrack;r>=0&&t!==r&&this.onAudioSwitched$.next({audioTrack:this.getCurrentAudioTrack()})}getHls(){return this.hls}}class ig{constructor(e){this.hidden=!0,this.id=e.id,this.src=e.src,this.default=e.default,this.label=e.label,this.language=e.language,this.cues=[]}}class rg extends ig{constructor(e){super(e)}}class xn{constructor(e){this.subtitlesTracks=new Map,this.onCreate$=new V,this.onRemove$=new V,this.onShow$=new V,this.onHide$=new V,this.videoController=e,this.videoController.onVideoLoaded$.pipe(We(t=>!!t)).subscribe(t=>{this.removeAllTracks()})}getDomTextTrack(e){if(this.videoController&&this.videoController.getHTMLVideoElement()){let t=this.videoController.getHTMLVideoElement().textTracks.getTrackById(e.id);if(t.kind==="subtitles")return t}}removeDomTextTrack(e){return this.getDomTextTrack(e)?(this.videoController.getHTMLVideoElement().querySelectorAll("track").forEach(r=>{r.getAttribute("id")===e.id&&r.parentElement.removeChild(r)}),!0):!1}static createHTMLTrackElement(e){let t=document.createElement("track");return t.kind="subtitles",t.id=e.id,t.label=e.label,t.srclang=e.language,t.src=e.src,t.default=e.default,t}createVttTrack(e){return this.videoController.isVideoLoaded?new re(t=>{let r=new rg({...e});this.subtitlesTracks.has(r.id)&&this.removeTrack(r.id),r.element=xn.createHTMLTrackElement(r),be(r.element,"load").pipe(ui()).subscribe(n=>{this.subtitlesTracks.set(r.id,r),t.next(r),t.complete(),this.onCreate$.next({textTrack:r})}),this.videoController.getHTMLVideoElement().appendChild(r.element);let s=this.getDomTextTrack(r);s.mode="hidden"}):Se(void 0)}getTracks(){if(this.videoController.isVideoLoaded)return[...this.subtitlesTracks.values()]}removeAllTracks(){this.videoController.isVideoLoaded&&this.subtitlesTracks.forEach((e,t)=>{this.removeTrack(e.id)})}removeTrack(e){if(!this.videoController.isVideoLoaded)return;let t=this.subtitlesTracks.get(e);t&&(this.subtitlesTracks.delete(e),this.removeDomTextTrack(t),this.onRemove$.next({}))}getCurrentTrack(){return this.currentTrack}showTrack(e=void 0){if(!this.videoController.isVideoLoaded||(e=e||(this.getCurrentTrack()?this.getCurrentTrack().id:void 0),!e))return;let t=this.subtitlesTracks.get(e);if(t){let r=this.getDomTextTrack(t);if(r){for(let s=0;s<this.videoController.getHTMLVideoElement().textTracks.length;s++){let n=this.videoController.getHTMLVideoElement().textTracks[s];n.mode="hidden"}r.mode="showing",t.hidden=!1,this.currentTrack=t,this.onShow$.next({})}}}hideTrack(e=void 0){if(!this.videoController.isVideoLoaded||(e=e||(this.getCurrentTrack()?this.getCurrentTrack().id:void 0),!e))return;let t=this.subtitlesTracks.get(e);if(t){let r=this.getDomTextTrack(t);r&&(r.mode="hidden",t.hidden=!0,this.onHide$.next({}))}}destroy(){this.removeAllTracks();let e=[this.onCreate$,this.onRemove$,this.onShow$,this.onHide$];Vt(...e),bi(...e),this.currentTrack=void 0,this.videoController=void 0}}var tn={},sg={get exports(){return tn},set exports(i){tn=i}};(function(i){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function s(h,l,d){this.fn=h,this.context=l,this.once=d||!1}function n(h,l,d,u,c){if(typeof d!="function")throw new TypeError("The listener must be a function");var p=new s(d,u||h,c),f=t?t+l:l;return h._events[f]?h._events[f].fn?h._events[f]=[h._events[f],p]:h._events[f].push(p):(h._events[f]=p,h._eventsCount++),h}function a(h,l){--h._eventsCount===0?h._events=new r:delete h._events[l]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],d,u;if(this._eventsCount===0)return l;for(u in d=this._events)e.call(d,u)&&l.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(d)):l},o.prototype.listeners=function(l){var d=t?t+l:l,u=this._events[d];if(!u)return[];if(u.fn)return[u.fn];for(var c=0,p=u.length,f=new Array(p);c<p;c++)f[c]=u[c].fn;return f},o.prototype.listenerCount=function(l){var d=t?t+l:l,u=this._events[d];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,d,u,c,p,f){var m=t?t+l:l;if(!this._events[m])return!1;var g=this._events[m],_=arguments.length,w,b;if(g.fn){switch(g.once&&this.removeListener(l,g.fn,void 0,!0),_){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,d),!0;case 3:return g.fn.call(g.context,d,u),!0;case 4:return g.fn.call(g.context,d,u,c),!0;case 5:return g.fn.call(g.context,d,u,c,p),!0;case 6:return g.fn.call(g.context,d,u,c,p,f),!0}for(b=1,w=new Array(_-1);b<_;b++)w[b-1]=arguments[b];g.fn.apply(g.context,w)}else{var T=g.length,L;for(b=0;b<T;b++)switch(g[b].once&&this.removeListener(l,g[b].fn,void 0,!0),_){case 1:g[b].fn.call(g[b].context);break;case 2:g[b].fn.call(g[b].context,d);break;case 3:g[b].fn.call(g[b].context,d,u);break;case 4:g[b].fn.call(g[b].context,d,u,c);break;default:if(!w)for(L=1,w=new Array(_-1);L<_;L++)w[L-1]=arguments[L];g[b].fn.apply(g[b].context,w)}}return!0},o.prototype.on=function(l,d,u){return n(this,l,d,u,!1)},o.prototype.once=function(l,d,u){return n(this,l,d,u,!0)},o.prototype.removeListener=function(l,d,u,c){var p=t?t+l:l;if(!this._events[p])return this;if(!d)return a(this,p),this;var f=this._events[p];if(f.fn)f.fn===d&&(!c||f.once)&&(!u||f.context===u)&&a(this,p);else{for(var m=0,g=[],_=f.length;m<_;m++)(f[m].fn!==d||c&&!f[m].once||u&&f[m].context!==u)&&g.push(f[m]);g.length?this._events[p]=g.length===1?g[0]:g:a(this,p)}return this},o.prototype.removeAllListeners=function(l){var d;return l?(d=t?t+l:l,this._events[d]&&a(this,d)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,i.exports=o})(sg);const ng={OMAKASE_SUBTITLES_HIDE:"omakaseSubtitlesHide",OMAKASE_TIMELINE_ZOOM:"omakaseTimelineZoom",OMAKASE_VIDEO_LOADED:"omakaseVideoLoaded",OMAKASE_VIDEO_PAUSE:"omakaseVideoPause",OMAKASE_VIDEO_PLAY:"omakaseVideoPlay",OMAKASE_VIDEO_SEEKED:"omakaseVideoSeeked",OMAKASE_VIDEO_SEEKING:"omakaseVideoSeeking",OMAKASE_VIDEO_BUFFERING:"omakaseVideoBuffering",OMAKASE_VIDEO_ENDED:"omakaseVideoEnded",OMAKASE_VIDEO_TIME_CHANGE:"omakaseVideoTimeChange",OMAKASE_VIDEO_AUDIO_SWITCHED:"omakaseVideoAudioSwitched",OMAKASE_AUDIO_SWITCHED:"omakaseAudioSwitched",OMAKASE_SUBTITLES_CREATE:"omakaseSubtitlesCreate",OMAKASE_SUBTITLES_REMOVE:"omakaseSubtitlesRemove",OMAKASE_SUBTITLES_SHOW:"omakaseSubtitlesShow",OMAKASE_TIMELINE_SCROLL:"omakaseTimelineScroll"};class ag{constructor(e){this.onAudioSwitched$=new V,this.videoController=e}getAudioTracks(){return this.videoController.getAudioTracks()}getCurrentAudioTrack(){return this.videoController.getCurrentAudioTrack()}setAudioTrack(e){let t=this.getCurrentAudioTrack();this.videoController.setAudioTrack(e);let r=this.getCurrentAudioTrack();t!==r&&this.onAudioSwitched$.next({audioTrack:r})}destroy(){}}class Pi{static isFullscreenEnabled(){const e=document;return e.fullscreenEnabled||e.webkitFullscreenEnabled||!!e.webkitCancelFullScreen||e.mozFullScreenEnabled||e.msFullscreenEnabled||!1}static isFullscreen(){const e=document;return!!(e.fullscreenElement||e.webkitFullscreenElement||e.webkitCurrentFullScreenElement||e.mozFullScreenElement||e.msFullscreenElement)}static requestFullscreen(e,t){const r=e??document.documentElement,s=r.requestFullscreen||r.webkitRequestFullscreen||r.webkitRequestFullScreen||r.mozRequestFullScreen||r.msRequestFullscreen;if(!s)throw new Error("Unsupported");return s.call(r,t)}static exitFullscreen(){const e=document,t=e.exitFullscreen||e.webkitExitFullscreen||e.webkitCancelFullScreen||e.mozCancelFullScreen||e.msExitFullscreen;if(!t)throw new Error("Unsupported");return t.call(e)}}const fe={player:"omakase-player",playerWrapper:"omakase-player-wrapper",video:"omakase-video",videoControls:"omakase-video-controls",buttonPlay:"omakase-button-play",buttonPause:"omakase-button-pause",buttonLoading:"omakase-button-loading",buttonError:"omakase-button-error",buttonReplay:"omakase-button-replay",buttonHelp:"omakase-help-button",help:"omakase-help",helpMenu:"omakase-help-menu",errorMessage:"omakase-error-message"};class og{constructor(e){this._playerHTMLElementId=e,this.divPlayer=this.getElementById(this._playerHTMLElementId),this.createDom()}createDom(){this.divPlayer.classList.add(`${fe.player}`),this.divPlayer.innerHTML=`<div class="${fe.playerWrapper}">
48
48
  <video class="${fe.video}"></video>
49
49
 
50
50
  <div class="${fe.help} d-none">