@streamlayer/react 1.18.6 → 1.18.7

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.
@@ -220,4 +220,4 @@ ${wr(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),
220
220
  `.split("").map(i=>i.charCodeAt(0)));class a2 extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class o2 extends _l{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.loadVttJs=e.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return at();const e=this.subtitlesTrack_.cues,t=e[0].startTime,r=e[e.length-1].startTime;return at([[t,r]])}initSegmentForMap(e,t=!1){if(!e)return null;const r=_a(e);let n=this.initSegments_[r];if(t&&!n&&e.bytes){const s=uh.byteLength+e.bytes.byteLength,a=new Uint8Array(s);a.set(e.bytes),a.set(uh,e.bytes.byteLength),this.initSegments_[r]=n={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:a}}return n||e}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}track(e){return typeof e>"u"?this.subtitlesTrack_:(this.subtitlesTrack_=e,this.state==="INIT"&&this.couldBeginLoading_()&&this.init_(),this.subtitlesTrack_)}remove(e,t){Nn(e,t,this.subtitlesTrack_)}fillBuffer_(){const e=this.chooseNextRequest_();if(e){if(this.syncController_.timestampOffsetForTimeline(e.timeline)===null){const t=()=>{this.state="READY",this.paused()||this.monitorBuffer_()};this.syncController_.one("timestampoffset",t),this.state="WAITING_ON_TIMELINE";return}this.loadSegment_(e)}}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(e){for(;e&&e.segment.empty;){if(e.mediaIndex+1>=e.playlist.segments.length){e=null;break}e=this.generateSegmentInfo_({playlist:e.playlist,mediaIndex:e.mediaIndex+1,startOfSegment:e.startOfSegment+e.duration,isSyncRequest:e.isSyncRequest})}return e}stopForError(e){this.error(e),this.state="READY",this.pause(),this.trigger("error")}segmentRequestFinished_(e,t,r){if(!this.subtitlesTrack_){this.state="READY";return}if(this.saveTransferStats_(t.stats),!this.pendingSegment_){this.state="READY",this.mediaRequestsAborted+=1;return}if(e){e.code===ai.TIMEOUT&&this.handleTimeout_(),e.code===ai.ABORTED?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,this.stopForError(e);return}const n=this.pendingSegment_,s=r.mp4VttCues&&r.mp4VttCues.length;s&&(n.mp4VttCues=r.mp4VttCues),this.saveBandwidthRelatedStats_(n.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");const a=n.segment;if(a.map&&(a.map.bytes=t.map.bytes),n.bytes=t.bytes,typeof x.WebVTT!="function"&&typeof this.loadVttJs=="function"){this.state="WAITING_ON_VTTJS",this.loadVttJs().then(()=>this.segmentRequestFinished_(e,t,r),()=>this.stopForError({message:"Error loading vtt.js"}));return}a.requested=!0;try{this.parseVTTCues_(n)}catch(l){this.stopForError({message:l.message,metadata:{errorType:F.Error.StreamingVttParserError,error:l}});return}if(s||this.updateTimeMapping_(n,this.syncController_.timelines[n.timeline],this.playlist_),n.cues.length?n.timingInfo={start:n.cues[0].startTime,end:n.cues[n.cues.length-1].endTime}:n.timingInfo={start:n.startOfSegment,end:n.startOfSegment+n.duration},n.isSyncRequest){this.trigger("syncinfoupdate"),this.pendingSegment_=null,this.state="READY";return}n.byteLength=n.bytes.byteLength,this.mediaSecondsLoaded+=a.duration,n.cues.forEach(l=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new x.VTTCue(l.startTime,l.endTime,l.text):l)}),Vw(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(e,t){const r=e&&e.type==="vtt",n=t&&t.type==="text";r&&n&&super.handleData_(e,t)}updateTimingInfoEnd_(){}parseMp4VttCues_(e){const t=this.sourceUpdater_.videoTimestampOffset()===null?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();e.mp4VttCues.forEach(r=>{const n=r.start+t,s=r.end+t,a=new x.VTTCue(n,s,r.cueText);r.settings&&r.settings.split(" ").forEach(l=>{const u=l.split(":"),p=u[0],m=u[1];a[p]=isNaN(m)?m:Number(m)}),e.cues.push(a)})}parseVTTCues_(e){let t,r=!1;if(typeof x.WebVTT!="function")throw new a2;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues){this.parseMp4VttCues_(e);return}typeof x.TextDecoder=="function"?t=new x.TextDecoder("utf8"):(t=x.WebVTT.StringDecoder(),r=!0);const n=new x.WebVTT.Parser(x,x.vttjs,t);if(n.oncue=e.cues.push.bind(e.cues),n.ontimestampmap=a=>{e.timestampmap=a},n.onparsingerror=a=>{F.log.warn("Error encountered when parsing cues: "+a.message)},e.segment.map){let a=e.segment.map.bytes;r&&(a=lh(a)),n.parse(a)}let s=e.bytes;r&&(s=lh(s)),n.parse(s),n.flush()}updateTimeMapping_(e,t,r){const n=e.segment;if(!t)return;if(!e.cues.length){n.empty=!0;return}const{MPEGTS:s,LOCAL:a}=e.timestampmap,l=s/tr.ONE_SECOND_IN_TS-a+t.mapping;if(e.cues.forEach(u=>{const p=u.endTime-u.startTime,m=this.handleRollover_(u.startTime+l,t.time);u.startTime=Math.max(m,0),u.endTime=Math.max(m+p,0)}),!r.syncInfo){const u=e.cues[0].startTime,p=e.cues[e.cues.length-1].startTime;r.syncInfo={mediaSequence:r.mediaSequence+e.mediaIndex,time:Math.min(u,p-n.duration)}}}handleRollover_(e,t){if(t===null)return e;let r=e*tr.ONE_SECOND_IN_TS;const n=t*tr.ONE_SECOND_IN_TS;let s;for(n<r?s=-8589934592:s=8589934592;Math.abs(r-n)>4294967296;)r+=s;return r/tr.ONE_SECOND_IN_TS}}const l2=function(i,e){const t=i.cues;for(let r=0;r<t.length;r++){const n=t[r];if(e>=n.adStartTime&&e<=n.adEndTime)return n}return null},u2=function(i,e,t=0){if(!i.segments)return;let r=t,n;for(let s=0;s<i.segments.length;s++){const a=i.segments[s];if(n||(n=l2(e,r+a.duration/2)),n){if("cueIn"in a){n.endTime=r,n.adEndTime=r,r+=a.duration,n=null;continue}if(r<n.endTime){r+=a.duration;continue}n.endTime+=a.duration}else if("cueOut"in a&&(n=new x.VTTCue(r,r+a.duration,a.cueOut),n.adStartTime=r,n.adEndTime=r+parseFloat(a.cueOut),e.addCue(n)),"cueOutCont"in a){const[l,u]=a.cueOutCont.split("/").map(parseFloat);n=new x.VTTCue(r,r+a.duration,""),n.adStartTime=r-l,n.adEndTime=n.adStartTime+u,e.addCue(n)}r+=a.duration}};class ch{constructor({start:e,end:t,segmentIndex:r,partIndex:n=null,appended:s=!1}){this.start_=e,this.end_=t,this.segmentIndex_=r,this.partIndex_=n,this.appended_=s}isInRange(e){return e>=this.start&&e<this.end}markAppended(){this.appended_=!0}resetAppendedStatus(){this.appended_=!1}get isAppended(){return this.appended_}get start(){return this.start_}get end(){return this.end_}get segmentIndex(){return this.segmentIndex_}get partIndex(){return this.partIndex_}}class c2{constructor(e,t=[]){this.segmentSyncInfo_=e,this.partsSyncInfo_=t}get segmentSyncInfo(){return this.segmentSyncInfo_}get partsSyncInfo(){return this.partsSyncInfo_}get hasPartsSyncInfo(){return this.partsSyncInfo_.length>0}resetAppendStatus(){this.segmentSyncInfo_.resetAppendedStatus(),this.partsSyncInfo_.forEach(e=>e.resetAppendedStatus())}}class tf{constructor(){this.storage_=new Map,this.diagnostics_="",this.isReliable_=!1,this.start_=-1/0,this.end_=1/0}get start(){return this.start_}get end(){return this.end_}get diagnostics(){return this.diagnostics_}get isReliable(){return this.isReliable_}resetAppendedStatus(){this.storage_.forEach(e=>e.resetAppendStatus())}update(e,t){const{mediaSequence:r,segments:n}=e;if(this.isReliable_=this.isReliablePlaylist_(r,n),!!this.isReliable_)return this.updateStorage_(n,r,this.calculateBaseTime_(r,n,t))}getSyncInfoForTime(e){for(const{segmentSyncInfo:t,partsSyncInfo:r}of this.storage_.values())if(r.length){for(const n of r)if(n.isInRange(e))return n}else if(t.isInRange(e))return t;return null}getSyncInfoForMediaSequence(e){return this.storage_.get(e)}updateStorage_(e,t,r){const n=new Map;let s=`
221
221
  `,a=r,l=t;this.start_=a,e.forEach((u,p)=>{const m=this.storage_.get(l),_=a,E=_+u.duration,S=!!(m&&m.segmentSyncInfo&&m.segmentSyncInfo.isAppended),C=new ch({start:_,end:E,appended:S,segmentIndex:p});u.syncInfo=C;let v=a;const L=(u.parts||[]).map((D,U)=>{const O=v,B=v+D.duration,P=!!(m&&m.partsSyncInfo&&m.partsSyncInfo[U]&&m.partsSyncInfo[U].isAppended),$=new ch({start:O,end:B,appended:P,segmentIndex:p,partIndex:U});return v=B,s+=`Media Sequence: ${l}.${U} | Range: ${O} --> ${B} | Appended: ${P}
222
222
  `,D.syncInfo=$,$});n.set(l,new c2(C,L)),s+=`${Qg(u.resolvedUri)} | Media Sequence: ${l} | Range: ${_} --> ${E} | Appended: ${S}
223
- `,l++,a=E}),this.end_=a,this.storage_=n,this.diagnostics_=s}calculateBaseTime_(e,t,r){if(!this.storage_.size)return 0;if(this.storage_.has(e))return this.storage_.get(e).segmentSyncInfo.start;const n=Math.min(...this.storage_.keys());if(e<n){const s=n-e;let a=this.storage_.get(n).segmentSyncInfo.start;for(let l=0;l<s;l++){const u=t[l];a-=u.duration}return a}return r}isReliablePlaylist_(e,t){return e!=null&&Array.isArray(t)&&t.length}}class dh extends tf{constructor(e){super(),this.parent_=e}calculateBaseTime_(e,t,r){if(!this.storage_.size){const n=this.parent_.getSyncInfoForMediaSequence(e);return n?n.segmentSyncInfo.start:0}return super.calculateBaseTime_(e,t,r)}}const d2=86400,Vo=[{name:"VOD",run:(i,e,t,r,n)=>t!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(i,e,t,r,n,s)=>{const a=i.getMediaSequenceSync(s);if(!a||!a.isReliable)return null;const l=a.getSyncInfoForTime(n);return l?{time:l.start,partIndex:l.partIndex,segmentIndex:l.segmentIndex}:null}},{name:"ProgramDateTime",run:(i,e,t,r,n)=>{if(!Object.keys(i.timelineToDatetimeMappings).length)return null;let s=null,a=null;const l=ul(e);n=n||0;for(let u=0;u<l.length;u++){const p=e.endList||n===0?u:l.length-(u+1),m=l[p],_=m.segment,E=i.timelineToDatetimeMappings[_.timeline];if(!E||!_.dateTimeObject)continue;let S=_.dateTimeObject.getTime()/1e3+E;if(_.parts&&typeof m.partIndex=="number")for(let v=0;v<m.partIndex;v++)S+=_.parts[v].duration;const C=Math.abs(n-S);if(a!==null&&(C===0||a<C))break;a=C,s={time:S,segmentIndex:m.segmentIndex,partIndex:m.partIndex}}return s}},{name:"Segment",run:(i,e,t,r,n)=>{let s=null,a=null;n=n||0;const l=ul(e);for(let u=0;u<l.length;u++){const p=e.endList||n===0?u:l.length-(u+1),m=l[p],_=m.segment,E=m.part&&m.part.start||_&&_.start;if(_.timeline===r&&typeof E<"u"){const S=Math.abs(n-E);if(a!==null&&a<S)break;(!s||a===null||a>=S)&&(a=S,s={time:E,segmentIndex:m.segmentIndex,partIndex:m.partIndex})}}return s}},{name:"Discontinuity",run:(i,e,t,r,n)=>{let s=null;if(n=n||0,e.discontinuityStarts&&e.discontinuityStarts.length){let a=null;for(let l=0;l<e.discontinuityStarts.length;l++){const u=e.discontinuityStarts[l],p=e.discontinuitySequence+l+1,m=i.discontinuities[p];if(m){const _=Math.abs(n-m.time);if(a!==null&&a<_)break;(!s||a===null||a>=_)&&(a=_,s={time:m.time,segmentIndex:u,partIndex:null})}}}return s}},{name:"Playlist",run:(i,e,t,r,n)=>e.syncInfo?{time:e.syncInfo.time,segmentIndex:e.syncInfo.mediaSequence-e.mediaSequence,partIndex:null}:null}];class h2 extends F.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new tf,r=new dh(t),n=new dh(t);this.mediaSequenceStorage_={main:t,audio:r,vtt:n},this.logger_=jt("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,r,n,s){if(t!==1/0)return Vo.find(({name:l})=>l==="VOD").run(this,e,t);const a=this.runStrategies_(e,t,r,n,s);if(!a.length)return null;for(const l of a){const{syncPoint:u,strategy:p}=l,{segmentIndex:m,time:_}=u;if(m<0)continue;const E=e.segments[m],S=_,C=S+E.duration;if(this.logger_(`Strategy: ${p}. Current time: ${n}. selected segment: ${m}. Time: [${S} -> ${C}]}`),n>=S&&n<C)return this.logger_("Found sync point with exact match: ",u),u}return this.selectSyncPoint_(a,{key:"time",value:n})}getExpiredTime(e,t){if(!e||!e.segments)return null;const r=this.runStrategies_(e,t,e.discontinuitySequence,0);if(!r.length)return null;const n=this.selectSyncPoint_(r,{key:"segmentIndex",value:0});return n.segmentIndex>0&&(n.time*=-1),Math.abs(n.time+jn({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))}runStrategies_(e,t,r,n,s){const a=[];for(let l=0;l<Vo.length;l++){const u=Vo[l],p=u.run(this,e,t,r,n,s);p&&(p.strategy=u.name,a.push({strategy:u.name,syncPoint:p}))}return a}selectSyncPoint_(e,t){let r=e[0].syncPoint,n=Math.abs(e[0].syncPoint[t.key]-t.value),s=e[0].strategy;for(let a=1;a<e.length;a++){const l=Math.abs(e[a].syncPoint[t.key]-t.value);l<n&&(n=l,r=e[a].syncPoint,s=e[a].strategy)}return this.logger_(`syncPoint for [${t.key}: ${t.value}] chosen with strategy [${s}]: [time:${r.time}, segmentIndex:${r.segmentIndex}`+(typeof r.partIndex=="number"?`,partIndex:${r.partIndex}`:"")+"]"),r}saveExpiredSegmentInfo(e,t){const r=t.mediaSequence-e.mediaSequence;if(r>d2){F.log.warn(`Not saving expired segment info. Media sequence gap ${r} is too large.`);return}for(let n=r-1;n>=0;n--){const s=e.segments[n];if(s&&typeof s.start<"u"){t.syncInfo={mediaSequence:e.mediaSequence+n,time:s.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){const t=e.segments[0],r=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-r}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){const r=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),n=e.segment;r&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:n.start}));const s=n.dateTimeObject;n.discontinuity&&t&&s&&(this.timelineToDatetimeMappings[n.timeline]=-(s.getTime()/1e3))}timestampOffsetForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].time}mappingForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,r){const n=e.segment,s=e.part;let a=this.timelines[e.timeline],l,u;if(typeof e.timestampOffset=="number")a={time:e.startOfSegment,mapping:e.startOfSegment-t.start},r&&(this.timelines[e.timeline]=a,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${a.time}] [mapping: ${a.mapping}]`)),l=e.startOfSegment,u=t.end+a.mapping;else if(a)l=t.start+a.mapping,u=t.end+a.mapping;else return!1;return s&&(s.start=l,s.end=u),(!n.start||l<n.start)&&(n.start=l),n.end=u,!0}saveDiscontinuitySyncInfo_(e){const t=e.playlist,r=e.segment;if(r.discontinuity)this.discontinuities[r.timeline]={time:r.start,accuracy:0};else if(t.discontinuityStarts&&t.discontinuityStarts.length)for(let n=0;n<t.discontinuityStarts.length;n++){const s=t.discontinuityStarts[n],a=t.discontinuitySequence+n+1,l=s-e.mediaIndex,u=Math.abs(l);if(!this.discontinuities[a]||this.discontinuities[a].accuracy>u){let p;l<0?p=r.start-jn({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:s}):p=r.end+jn({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:s}),this.discontinuities[a]={time:p,accuracy:u}}}}dispose(){this.trigger("dispose"),this.off()}}class p2 extends F.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange({type:e,from:t,to:r}){return typeof t=="number"&&typeof r=="number"&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:r},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:r}){if(typeof t=="number"&&typeof r=="number"){this.lastTimelineChanges_[e]={type:e,from:t,to:r},delete this.pendingTimelineChanges_[e];const n={timelineChangeInfo:{from:t,to:r}};this.trigger({type:"timelinechange",metadata:n})}return this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const m2=Fg(jg(function(){var i=function(){function v(){this.listeners={}}var L=v.prototype;return L.on=function(D,U){this.listeners[D]||(this.listeners[D]=[]),this.listeners[D].push(U)},L.off=function(D,U){if(!this.listeners[D])return!1;var O=this.listeners[D].indexOf(U);return this.listeners[D]=this.listeners[D].slice(0),this.listeners[D].splice(O,1),O>-1},L.trigger=function(D){var U=this.listeners[D];if(U)if(arguments.length===2)for(var O=U.length,B=0;B<O;++B)U[B].call(this,arguments[1]);else for(var P=Array.prototype.slice.call(arguments,1),$=U.length,Q=0;Q<$;++Q)U[Q].apply(this,P)},L.dispose=function(){this.listeners={}},L.pipe=function(D){this.on("data",function(U){D.push(U)})},v}();/*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */function e(v){return v.subarray(0,v.byteLength-v[v.byteLength-1])}/*! @name aes-decrypter @version 4.0.2 @license Apache-2.0 */const t=function(){const v=[[[],[],[],[],[]],[[],[],[],[],[]]],L=v[0],D=v[1],U=L[4],O=D[4];let B,P,$;const Q=[],K=[];let ie,me,oe,ge,ee,ue;for(B=0;B<256;B++)K[(Q[B]=B<<1^(B>>7)*283)^B]=B;for(P=$=0;!U[P];P^=ie||1,$=K[$]||1)for(ge=$^$<<1^$<<2^$<<3^$<<4,ge=ge>>8^ge&255^99,U[P]=ge,O[ge]=P,oe=Q[me=Q[ie=Q[P]]],ue=oe*16843009^me*65537^ie*257^P*16843008,ee=Q[ge]*257^ge*16843008,B=0;B<4;B++)L[B][P]=ee=ee<<24^ee>>>8,D[B][ge]=ue=ue<<24^ue>>>8;for(B=0;B<5;B++)L[B]=L[B].slice(0),D[B]=D[B].slice(0);return v};let r=null;class n{constructor(L){r||(r=t()),this._tables=[[r[0][0].slice(),r[0][1].slice(),r[0][2].slice(),r[0][3].slice(),r[0][4].slice()],[r[1][0].slice(),r[1][1].slice(),r[1][2].slice(),r[1][3].slice(),r[1][4].slice()]];let D,U,O;const B=this._tables[0][4],P=this._tables[1],$=L.length;let Q=1;if($!==4&&$!==6&&$!==8)throw new Error("Invalid aes key size");const K=L.slice(0),ie=[];for(this._key=[K,ie],D=$;D<4*$+28;D++)O=K[D-1],(D%$===0||$===8&&D%$===4)&&(O=B[O>>>24]<<24^B[O>>16&255]<<16^B[O>>8&255]<<8^B[O&255],D%$===0&&(O=O<<8^O>>>24^Q<<24,Q=Q<<1^(Q>>7)*283)),K[D]=K[D-$]^O;for(U=0;D;U++,D--)O=K[U&3?D:D-4],D<=4||U<4?ie[U]=O:ie[U]=P[0][B[O>>>24]]^P[1][B[O>>16&255]]^P[2][B[O>>8&255]]^P[3][B[O&255]]}decrypt(L,D,U,O,B,P){const $=this._key[1];let Q=L^$[0],K=O^$[1],ie=U^$[2],me=D^$[3],oe,ge,ee;const ue=$.length/4-2;let te,de=4;const be=this._tables[1],je=be[0],Ye=be[1],ve=be[2],ye=be[3],kt=be[4];for(te=0;te<ue;te++)oe=je[Q>>>24]^Ye[K>>16&255]^ve[ie>>8&255]^ye[me&255]^$[de],ge=je[K>>>24]^Ye[ie>>16&255]^ve[me>>8&255]^ye[Q&255]^$[de+1],ee=je[ie>>>24]^Ye[me>>16&255]^ve[Q>>8&255]^ye[K&255]^$[de+2],me=je[me>>>24]^Ye[Q>>16&255]^ve[K>>8&255]^ye[ie&255]^$[de+3],de+=4,Q=oe,K=ge,ie=ee;for(te=0;te<4;te++)B[(3&-te)+P]=kt[Q>>>24]<<24^kt[K>>16&255]<<16^kt[ie>>8&255]<<8^kt[me&255]^$[de++],oe=Q,Q=K,K=ie,ie=me,me=oe}}class s extends i{constructor(){super(i),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(L){this.jobs.push(L),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const a=function(v){return v<<24|(v&65280)<<8|(v&16711680)>>8|v>>>24},l=function(v,L,D){const U=new Int32Array(v.buffer,v.byteOffset,v.byteLength>>2),O=new n(Array.prototype.slice.call(L)),B=new Uint8Array(v.byteLength),P=new Int32Array(B.buffer);let $,Q,K,ie,me,oe,ge,ee,ue;for($=D[0],Q=D[1],K=D[2],ie=D[3],ue=0;ue<U.length;ue+=4)me=a(U[ue]),oe=a(U[ue+1]),ge=a(U[ue+2]),ee=a(U[ue+3]),O.decrypt(me,oe,ge,ee,P,ue),P[ue]=a(P[ue]^$),P[ue+1]=a(P[ue+1]^Q),P[ue+2]=a(P[ue+2]^K),P[ue+3]=a(P[ue+3]^ie),$=me,Q=oe,K=ge,ie=ee;return B};class u{constructor(L,D,U,O){const B=u.STEP,P=new Int32Array(L.buffer),$=new Uint8Array(L.byteLength);let Q=0;for(this.asyncStream_=new s,this.asyncStream_.push(this.decryptChunk_(P.subarray(Q,Q+B),D,U,$)),Q=B;Q<P.length;Q+=B)U=new Uint32Array([a(P[Q-4]),a(P[Q-3]),a(P[Q-2]),a(P[Q-1])]),this.asyncStream_.push(this.decryptChunk_(P.subarray(Q,Q+B),D,U,$));this.asyncStream_.push(function(){O(null,e($))})}static get STEP(){return 32e3}decryptChunk_(L,D,U,O){return function(){const B=l(L,D,U);O.set(B,L.byteOffset)}}}var p=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Zs<"u"?Zs:typeof self<"u"?self:{},m;typeof window<"u"?m=window:typeof p<"u"?m=p:typeof self<"u"?m=self:m={};var _=m,E=function(v){return ArrayBuffer.isView==="function"?ArrayBuffer.isView(v):v&&v.buffer instanceof ArrayBuffer},S=_.BigInt||Number;S("0x1"),S("0x100"),S("0x10000"),S("0x1000000"),S("0x100000000"),S("0x10000000000"),S("0x1000000000000"),S("0x100000000000000"),S("0x10000000000000000"),function(){var v=new Uint16Array([65484]),L=new Uint8Array(v.buffer,v.byteOffset,v.byteLength);return L[0]===255?"big":L[0]===204?"little":"unknown"}();const C=function(v){const L={};return Object.keys(v).forEach(D=>{const U=v[D];E(U)?L[D]={bytes:U.buffer,byteOffset:U.byteOffset,byteLength:U.byteLength}:L[D]=U}),L};self.onmessage=function(v){const L=v.data,D=new Uint8Array(L.encrypted.bytes,L.encrypted.byteOffset,L.encrypted.byteLength),U=new Uint32Array(L.key.bytes,L.key.byteOffset,L.key.byteLength/4),O=new Uint32Array(L.iv.bytes,L.iv.byteOffset,L.iv.byteLength/4);new u(D,U,O,function(B,P){self.postMessage(C({source:L.source,decrypted:P}),[P.buffer])})}}));var g2=Bg(m2);const f2=i=>{let e=i.default?"main":"alternative";return i.characteristics&&i.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},rf=(i,e)=>{i.abort(),i.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},vl=(i,e)=>{e.activePlaylistLoader=i,i.load()},y2=(i,e)=>()=>{const{segmentLoaders:{[i]:t,main:r},mediaTypes:{[i]:n}}=e,s=n.activeTrack(),a=n.getActiveGroup(),l=n.activePlaylistLoader,u=n.lastGroup_;if(!(a&&u&&a.id===u.id)&&(n.lastGroup_=a,n.lastTrack_=s,rf(t,n),!(!a||a.isMainPlaylist))){if(!a.playlistLoader){l&&r.resetEverything();return}t.resyncLoader(),vl(a.playlistLoader,n)}},_2=(i,e)=>()=>{const{segmentLoaders:{[i]:t},mediaTypes:{[i]:r}}=e;r.lastGroup_=null,t.abort(),t.pause()},b2=(i,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[i]:r,main:n},mediaTypes:{[i]:s}}=e,a=s.activeTrack(),l=s.getActiveGroup(),u=s.activePlaylistLoader,p=s.lastTrack_;if(!(p&&a&&p.id===a.id)&&(s.lastGroup_=l,s.lastTrack_=a,rf(r,s),!!l)){if(l.isMainPlaylist){if(!a||!p||a.id===p.id)return;const m=e.vhs.playlistController_,_=m.selectPlaylist();if(m.media()===_)return;s.logger_(`track change. Switching main audio from ${p.id} to ${a.id}`),t.pause(),n.resetEverything(),m.fastQualityChange_(_);return}if(i==="AUDIO"){if(!l.playlistLoader){n.setAudio(!0),n.resetEverything();return}r.setAudio(!0),n.setAudio(!1)}if(u===l.playlistLoader){vl(l.playlistLoader,s);return}r.track&&r.track(a),r.resetEverything(),vl(l.playlistLoader,s)}},Ta={AUDIO:(i,e)=>()=>{const{mediaTypes:{[i]:t},excludePlaylist:r}=e,n=t.activeTrack(),s=t.activeGroup(),a=(s.filter(u=>u.default)[0]||s[0]).id,l=t.tracks[a];if(n===l){r({error:{message:"Problem encountered loading the default audio track."}});return}F.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const u in t.tracks)t.tracks[u].enabled=t.tracks[u]===l;t.onTrackChanged()},SUBTITLES:(i,e)=>()=>{const{mediaTypes:{[i]:t}}=e;F.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const r=t.activeTrack();r&&(r.mode="disabled"),t.onTrackChanged()}},hh={AUDIO:(i,e,t)=>{if(!e)return;const{tech:r,requestOptions:n,segmentLoaders:{[i]:s}}=t;e.on("loadedmetadata",()=>{const a=e.media();s.playlist(a,n),(!r.paused()||a.endList&&r.preload()!=="none")&&s.load()}),e.on("loadedplaylist",()=>{s.playlist(e.media(),n),r.paused()||s.load()}),e.on("error",Ta[i](i,t))},SUBTITLES:(i,e,t)=>{const{tech:r,requestOptions:n,segmentLoaders:{[i]:s},mediaTypes:{[i]:a}}=t;e.on("loadedmetadata",()=>{const l=e.media();s.playlist(l,n),s.track(a.activeTrack()),(!r.paused()||l.endList&&r.preload()!=="none")&&s.load()}),e.on("loadedplaylist",()=>{s.playlist(e.media(),n),r.paused()||s.load()}),e.on("error",Ta[i](i,t))}},v2={AUDIO:(i,e)=>{const{vhs:t,sourceType:r,segmentLoaders:{[i]:n},requestOptions:s,main:{mediaGroups:a},mediaTypes:{[i]:{groups:l,tracks:u,logger_:p}},mainPlaylistLoader:m}=e,_=as(m.main);(!a[i]||Object.keys(a[i]).length===0)&&(a[i]={main:{default:{default:!0}}},_&&(a[i].main.default.playlists=m.main.playlists));for(const E in a[i]){l[E]||(l[E]=[]);for(const S in a[i][E]){let C=a[i][E][S],v;if(_?(p(`AUDIO group '${E}' label '${S}' is a main playlist`),C.isMainPlaylist=!0,v=null):r==="vhs-json"&&C.playlists?v=new Ar(C.playlists[0],t,s):C.resolvedUri?v=new Ar(C.resolvedUri,t,s):C.playlists&&r==="dash"?v=new gl(C.playlists[0],t,s,m):v=null,C=_e({id:S,playlistLoader:v},C),hh[i](i,C.playlistLoader,e),l[E].push(C),typeof u[S]>"u"){const L=new F.AudioTrack({id:S,kind:f2(C),enabled:!1,language:C.language,default:C.default,label:S});u[S]=L}}}n.on("error",Ta[i](i,e))},SUBTITLES:(i,e)=>{const{tech:t,vhs:r,sourceType:n,segmentLoaders:{[i]:s},requestOptions:a,main:{mediaGroups:l},mediaTypes:{[i]:{groups:u,tracks:p}},mainPlaylistLoader:m}=e;for(const _ in l[i]){u[_]||(u[_]=[]);for(const E in l[i][_]){if(!r.options_.useForcedSubtitles&&l[i][_][E].forced)continue;let S=l[i][_][E],C;if(n==="hls")C=new Ar(S.resolvedUri,r,a);else if(n==="dash"){if(!S.playlists.filter(v=>v.excludeUntil!==1/0).length)return;C=new gl(S.playlists[0],r,a,m)}else n==="vhs-json"&&(C=new Ar(S.playlists?S.playlists[0]:S.resolvedUri,r,a));if(S=_e({id:E,playlistLoader:C},S),hh[i](i,S.playlistLoader,e),u[_].push(S),typeof p[E]>"u"){const v=t.addRemoteTextTrack({id:E,kind:"subtitles",default:S.default&&S.autoselect,language:S.language,label:E},!1).track;p[E]=v}}}s.on("error",Ta[i](i,e))},"CLOSED-CAPTIONS":(i,e)=>{const{tech:t,main:{mediaGroups:r},mediaTypes:{[i]:{groups:n,tracks:s}}}=e;for(const a in r[i]){n[a]||(n[a]=[]);for(const l in r[i][a]){const u=r[i][a][l];if(!/^(?:CC|SERVICE)/.test(u.instreamId))continue;const p=t.options_.vhs&&t.options_.vhs.captionServices||{};let m={label:l,language:u.language,instreamId:u.instreamId,default:u.default&&u.autoselect};if(p[m.instreamId]&&(m=_e(m,p[m.instreamId])),m.default===void 0&&delete m.default,n[a].push(_e({id:l},u)),typeof s[l]>"u"){const _=t.addRemoteTextTrack({id:m.instreamId,kind:"captions",default:m.default,language:m.language,label:m.label},!1).track;s[l]=_}}}}},nf=(i,e)=>{for(let t=0;t<i.length;t++)if(ku(e,i[t])||i[t].playlists&&nf(i[t].playlists,e))return!0;return!1},T2=(i,e)=>t=>{const{mainPlaylistLoader:r,mediaTypes:{[i]:{groups:n}}}=e,s=r.media();if(!s)return null;let a=null;s.attributes[i]&&(a=n[s.attributes[i]]);const l=Object.keys(n);if(!a)if(i==="AUDIO"&&l.length>1&&as(e.main))for(let u=0;u<l.length;u++){const p=n[l[u]];if(nf(p,s)){a=p;break}}else n.main?a=n.main:l.length===1&&(a=n[l[0]]);return typeof t>"u"?a:t===null||!a?null:a.filter(u=>u.id===t.id)[0]||null},S2={AUDIO:(i,e)=>()=>{const{mediaTypes:{[i]:{tracks:t}}}=e;for(const r in t)if(t[r].enabled)return t[r];return null},SUBTITLES:(i,e)=>()=>{const{mediaTypes:{[i]:{tracks:t}}}=e;for(const r in t)if(t[r].mode==="showing"||t[r].mode==="hidden")return t[r];return null}},E2=(i,{mediaTypes:e})=>()=>{const t=e[i].activeTrack();return t?e[i].activeGroup(t):null},w2=i=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(p=>{v2[p](p,i)});const{mediaTypes:e,mainPlaylistLoader:t,tech:r,vhs:n,segmentLoaders:{["AUDIO"]:s,main:a}}=i;["AUDIO","SUBTITLES"].forEach(p=>{e[p].activeGroup=T2(p,i),e[p].activeTrack=S2[p](p,i),e[p].onGroupChanged=y2(p,i),e[p].onGroupChanging=_2(p,i),e[p].onTrackChanged=b2(p,i),e[p].getActiveGroup=E2(p,i)});const l=e.AUDIO.activeGroup();if(l){const p=(l.filter(m=>m.default)[0]||l[0]).id;e.AUDIO.tracks[p].enabled=!0,e.AUDIO.onGroupChanged(),e.AUDIO.onTrackChanged(),e.AUDIO.getActiveGroup().playlistLoader?(a.setAudio(!1),s.setAudio(!0)):a.setAudio(!0)}t.on("mediachange",()=>{["AUDIO","SUBTITLES"].forEach(p=>e[p].onGroupChanged())}),t.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(p=>e[p].onGroupChanging())});const u=()=>{e.AUDIO.onTrackChanged(),r.trigger({type:"usage",name:"vhs-audio-change"})};r.audioTracks().addEventListener("change",u),r.remoteTextTracks().addEventListener("change",e.SUBTITLES.onTrackChanged),n.on("dispose",()=>{r.audioTracks().removeEventListener("change",u),r.remoteTextTracks().removeEventListener("change",e.SUBTITLES.onTrackChanged)}),r.clearTracks("audio");for(const p in e.AUDIO.tracks)r.audioTracks().addTrack(e.AUDIO.tracks[p])},k2=()=>{const i={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{i[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:fi,activeTrack:fi,getActiveGroup:fi,onGroupChanged:fi,onTrackChanged:fi,lastTrack_:null,logger_:jt(`MediaGroups[${e}]`)}}),i};class ph{constructor(){this.priority_=[],this.pathwayClones_=new Map}set version(e){e===1&&(this.version_=e)}set ttl(e){this.ttl_=e||300}set reloadUri(e){e&&(this.reloadUri_=vt(this.reloadUri_,e))}set priority(e){e&&e.length&&(this.priority_=e)}set pathwayClones(e){e&&e.length&&(this.pathwayClones_=new Map(e.map(t=>[t.ID,t])))}get version(){return this.version_}get ttl(){return this.ttl_}get reloadUri(){return this.reloadUri_}get priority(){return this.priority_}get pathwayClones(){return this.pathwayClones_}}class C2 extends F.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new ph,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=jt("Content Steering"),this.xhr_=e,this.getBandwidth_=t}assignTagProperties(e,t){this.manifestType_=t.serverUri?"HLS":"DASH";const r=t.serverUri||t.serverURL;if(!r){this.logger_(`steering manifest URL is ${r}, cannot request steering manifest.`),this.trigger("error");return}if(r.startsWith("data:")){this.decodeDataUriManifest_(r.substring(r.indexOf(",")+1));return}this.steeringManifest.reloadUri=vt(e,r),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering")}requestSteeringManifest(e){const t=this.steeringManifest.reloadUri;if(!t)return;const r=e?t:this.getRequestURI(t);if(!r){this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),this.dispose();return}const n={contentSteeringInfo:{uri:r}};this.trigger({type:"contentsteeringloadstart",metadata:n}),this.request_=this.xhr_({uri:r,requestType:"content-steering-manifest"},(s,a)=>{if(s){if(a.status===410){this.logger_(`manifest request 410 ${s}.`),this.logger_(`There will be no more content steering requests to ${r} this session.`),this.excludedSteeringManifestURLs.add(r);return}if(a.status===429){const p=a.responseHeaders["retry-after"];this.logger_(`manifest request 429 ${s}.`),this.logger_(`content steering will retry in ${p} seconds.`),this.startTTLTimeout_(parseInt(p,10));return}this.logger_(`manifest failed to load ${s}.`),this.startTTLTimeout_();return}this.trigger({type:"contentsteeringloadcomplete",metadata:n});let l;try{l=JSON.parse(this.request_.responseText)}catch(p){const m={errorType:F.Error.StreamingContentSteeringParserError,error:p};this.trigger({type:"error",metadata:m})}this.assignSteeringProperties_(l);const u={contentSteeringInfo:n.contentSteeringInfo,contentSteeringManifest:{version:this.steeringManifest.version,reloadUri:this.steeringManifest.reloadUri,priority:this.steeringManifest.priority}};this.trigger({type:"contentsteeringparsed",metadata:u}),this.startTTLTimeout_()})}setProxyServerUrl_(e){const t=new x.URL(e),r=new x.URL(this.proxyServerUrl_);return r.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(r.toString())}decodeDataUriManifest_(e){const t=JSON.parse(x.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new x.URL(e),r=this.getPathway(),n=this.getBandwidth_();if(r){const s=`_${this.manifestType_}_pathway`;t.searchParams.set(s,r)}if(n){const s=`_${this.manifestType_}_throughput`;t.searchParams.set(s,n)}return t.toString()}assignSteeringProperties_(e){if(this.steeringManifest.version=e.VERSION,!this.steeringManifest.version){this.logger_(`manifest version is ${e.VERSION}, which is not supported.`),this.trigger("error");return}this.steeringManifest.ttl=e.TTL,this.steeringManifest.reloadUri=e["RELOAD-URI"],this.steeringManifest.priority=e["PATHWAY-PRIORITY"]||e["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=e["PATHWAY-CLONES"],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_("There are no available pathways for content steering. Ending content steering."),this.trigger("error"),this.dispose());const t=(r=>{for(const n of r)if(this.availablePathways_.has(n))return n;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==t&&(this.currentPathway=t,this.trigger("content-steering"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(e){if(!e)return null;const t=n=>this.excludedSteeringManifestURLs.has(n);if(this.proxyServerUrl_){const n=this.setProxyServerUrl_(e);if(!t(n))return n}const r=this.setSteeringParams_(e);return t(r)?null:r}startTTLTimeout_(e=this.steeringManifest.ttl){const t=e*1e3;this.ttlTimeout_=x.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){x.clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off("content-steering"),this.off("error"),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new ph}addAvailablePathway(e){e&&this.availablePathways_.add(e)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(e){return this.availablePathways_.delete(e)}didDASHTagChange(e,t){return!t&&this.steeringManifest.reloadUri||t&&(vt(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}}const I2=(i,e)=>{let t=null;return(...r)=>{clearTimeout(t),t=setTimeout(()=>{i.apply(null,r)},e)}},A2=10;let Oi;const x2=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],L2=function(i){return this.audioSegmentLoader_[i]+this.mainSegmentLoader_[i]},D2=function({currentPlaylist:i,buffered:e,currentTime:t,nextPlaylist:r,bufferLowWaterLine:n,bufferHighWaterLine:s,duration:a,bufferBasedABR:l,log:u}){if(!r)return F.log.warn("We received no playlist to switch to. Please check your stream."),!1;const p=`allowing switch ${i&&i.id||"null"} -> ${r.id}`;if(!i)return u(`${p} as current playlist is not set`),!0;if(r.id===i.id)return!1;const m=!!Ir(e,t).length;if(!i.endList)return!m&&typeof i.partTargetDuration=="number"?(u(`not ${p} as current playlist is live llhls, but currentTime isn't in buffered.`),!1):(u(`${p} as current playlist is live`),!0);const _=Su(e,t),E=l?Je.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:Je.MAX_BUFFER_LOW_WATER_LINE;if(a<E)return u(`${p} as duration < max low water line (${a} < ${E})`),!0;const S=r.attributes.BANDWIDTH,C=i.attributes.BANDWIDTH;if(S<C&&(!l||_<s)){let v=`${p} as next bandwidth < current bandwidth (${S} < ${C})`;return l&&(v+=` and forwardBuffer < bufferHighWaterLine (${_} < ${s})`),u(v),!0}if((!l||S>C)&&_>=n){let v=`${p} as forwardBuffer >= bufferLowWaterLine (${_} >= ${n})`;return l&&(v+=` and next bandwidth > current bandwidth (${S} > ${C})`),u(v),!0}return u(`not ${p} as no switching criteria met`),!1};class P2 extends F.EventTarget{constructor(e){super(),this.fastQualityChange_=I2(this.fastQualityChange_.bind(this),100);const{src:t,withCredentials:r,tech:n,bandwidth:s,externVhs:a,useCueTags:l,playlistExclusionDuration:u,enableLowInitialPlaylist:p,sourceType:m,cacheEncryptionKeys:_,bufferBasedABR:E,leastPixelDiffSelector:S,captionServices:C,experimentalUseMMS:v}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:L}=e;(L===null||typeof L>"u")&&(L=1/0),Oi=a,this.bufferBasedABR=!!E,this.leastPixelDiffSelector=!!S,this.withCredentials=r,this.tech_=n,this.vhs_=n.vhs,this.player_=e.player_,this.sourceType_=m,this.useCueTags_=l,this.playlistExclusionDuration=u,this.maxPlaylistRetries=L,this.enableLowInitialPlaylist=p,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:r,maxPlaylistRetries:L,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=k2(),v&&x.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new x.ManagedMediaSource,this.usingManagedMediaSource_=!0,F.log("Using ManagedMediaSource")):x.MediaSource&&(this.mediaSource=new x.MediaSource),this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.load=this.load.bind(this),this.pause=this.pause.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.mediaSource.addEventListener("startstreaming",this.load),this.mediaSource.addEventListener("endstreaming",this.pause),this.seekable_=at(),this.hasPlayed_=!1,this.syncController_=new h2(e),this.segmentMetadataTrack_=n.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.decrypter_=new g2,this.sourceUpdater_=new ef(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new p2,this.keyStatusMap_=new Map;const D={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:C,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:s,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:_,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_=this.sourceType_==="dash"?new gl(t,this.vhs_,_e(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new Ar(t,this.vhs_,_e(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new _l(_e(D,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new _l(_e(D,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new o2(_e(D,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((B,P)=>{function $(){n.off("vttjserror",Q),B()}function Q(){n.off("vttjsloaded",$),P()}n.one("vttjsloaded",$),n.one("vttjserror",Q),n.addWebVttScript_()})}),e);const U=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new C2(this.vhs_.xhr,U),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_())),x2.forEach(B=>{this[B+"_"]=L2.bind(this,B)}),this.logger_=jt("pc"),this.triggeredFmp4Usage=!1,this.tech_.preload()==="none"?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;const O=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(O,()=>{const B=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-B,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return e===-1||t===-1?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e="abr"){const t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,r){const n=this.media(),s=n&&(n.id||n.uri),a=e&&(e.id||e.uri);if(s&&s!==a){this.logger_(`switch media ${s} -> ${a} from ${t}`);const l={renditionInfo:{id:a,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:"renditionselected",metadata:l}),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,r)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{const t=this.mediaTypes_[e],r=t?t.activeGroup():null,n=this.contentSteeringController_.getPathway();if(r&&n){const s=(r.length?r[0].playlists:r.playlists).filter(a=>a.attributes.serviceLocation===n);s.length&&this.mediaTypes_[e].activePlaylistLoader.media(s[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=x.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(x.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const e=this.main(),t=e&&e.playlists||[];if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return t;const r=e.mediaGroups.AUDIO,n=Object.keys(r);let s;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)s=this.mediaTypes_.AUDIO.activeTrack();else{const l=r.main||n.length&&r[n[0]];for(const u in l)if(l[u].default){s={label:u};break}}if(!s)return t;const a=[];for(const l in r)if(r[l][s.label]){const u=r[l][s.label];if(u.playlists&&u.playlists.length)a.push.apply(a,u.playlists);else if(u.uri)a.push(u);else if(e.playlists.length)for(let p=0;p<e.playlists.length;p++){const m=e.playlists[p];m.attributes&&m.attributes.AUDIO&&m.attributes.AUDIO===l&&a.push(m)}}return a.length?a:t}setupMainPlaylistLoaderListeners_(){this.mainPlaylistLoader_.on("loadedmetadata",()=>{const e=this.mainPlaylistLoader_.media(),t=e.targetDuration*1.5*1e3;cl(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,e.endList&&this.tech_.preload()!=="none"&&(this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.mainSegmentLoader_.load()),w2({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),e),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger("selectedinitialmedia"):this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",()=>{this.trigger("selectedinitialmedia")})}),this.mainPlaylistLoader_.on("loadedplaylist",()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let e=this.mainPlaylistLoader_.media();if(!e){this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_();let t;if(this.enableLowInitialPlaylist&&(t=this.selectInitialPlaylist()),t||(t=this.selectPlaylist()),!t||!this.shouldSwitchToMedia_(t)||(this.initialMedia_=t,this.switchMedia_(this.initialMedia_,"initial"),!(this.sourceType_==="vhs-json"&&this.initialMedia_.segments)))return;e=this.initialMedia_}this.handleUpdatedMediaPlaylist(e)}),this.mainPlaylistLoader_.on("error",()=>{const e=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:e.playlist,error:e})}),this.mainPlaylistLoader_.on("mediachanging",()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()}),this.mainPlaylistLoader_.on("mediachange",()=>{const e=this.mainPlaylistLoader_.media(),t=e.targetDuration*1.5*1e3;cl(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,this.sourceType_==="dash"&&this.mainPlaylistLoader_.isPaused&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})}),this.mainPlaylistLoader_.on("playlistunchanged",()=>{const e=this.mainPlaylistLoader_.media();e.lastExcludeReason_!=="playlist-unchanged"&&this.stuckAtPlaylistEnd_(e)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))}),this.mainPlaylistLoader_.on("renditiondisabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})}),this.mainPlaylistLoader_.on("renditionenabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-enabled"})}),["manifestrequeststart","manifestrequestcomplete","manifestparsestart","manifestparsecomplete","playlistrequeststart","playlistrequestcomplete","playlistparsestart","playlistparsecomplete","renditiondisabled","renditionenabled"].forEach(e=>{this.mainPlaylistLoader_.on(e,t=>{this.player_.trigger(Ge({},t))})})}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!e.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){const r=e.mediaGroups||{};let n=!0;const s=Object.keys(r.AUDIO);for(const a in r.AUDIO)for(const l in r.AUDIO[a])r.AUDIO[a][l].uri||(n=!1);n&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(r.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),Oi.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),s.length&&Object.keys(r.AUDIO[s[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(e){const t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,r=this.tech_.currentTime(),n=this.bufferLowWaterLine(),s=this.bufferHighWaterLine(),a=this.tech_.buffered();return D2({buffered:a,currentTime:r,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:n,bufferHighWaterLine:s,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")}),this.mainSegmentLoader_.on("timeout",()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()}),this.bufferBasedABR||this.mainSegmentLoader_.on("progress",()=>{this.trigger("progress")}),this.mainSegmentLoader_.on("error",()=>{const t=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:t.playlist,error:t})}),this.mainSegmentLoader_.on("appenderror",()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.mainSegmentLoader_.on("timestampoffset",()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})}),this.audioSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.audioSegmentLoader_.on("appenderror",()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("ended",()=>{this.logger_("main segment loader ended"),this.onEndOfStream()}),this.timelineChangeController_.on("audioTimelineBehind",()=>{const t=this.audioSegmentLoader_.pendingSegment_;if(!t||!t.segment||!t.segment.syncInfo)return;const r=t.segment.syncInfo.end+.01;this.tech_.setCurrentTime(r)}),this.timelineChangeController_.on("fixBadTimelineChange",()=>{this.logger_("Fix bad timeline change. Restarting al segment loaders..."),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}),this.mainSegmentLoader_.on("earlyabort",t=>{this.bufferBasedABR||(this.delegateLoaders_("all",["abort"]),this.excludePlaylist({error:{message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},playlistExclusionDuration:A2}))});const e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const t=this.getCodecsOrExclude_();t&&this.sourceUpdater_.addOrChangeSourceBuffers(t)};this.mainSegmentLoader_.on("trackinfo",e),this.audioSegmentLoader_.on("trackinfo",e),this.mainSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("ended",()=>{this.logger_("audioSegmentLoader ended"),this.onEndOfStream()}),["segmentselected","segmentloadstart","segmentloaded","segmentkeyloadstart","segmentkeyloadcomplete","segmentdecryptionstart","segmentdecryptioncomplete","segmenttransmuxingstart","segmenttransmuxingcomplete","segmenttransmuxingtrackinfoavailable","segmenttransmuxingtiminginfoavailable","segmentappendstart","appendsdone","bandwidthupdated","timelinechange","codecschange"].forEach(t=>{this.mainSegmentLoader_.on(t,r=>{this.player_.trigger(Ge({},r))}),this.audioSegmentLoader_.on(t,r=>{this.player_.trigger(Ge({},r))}),this.subtitleSegmentLoader_.on(t,r=>{this.player_.trigger(Ge({},r))})})}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}pause(){this.mainSegmentLoader_.pause(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.pause(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.pause()}fastQualityChange_(e=this.selectPlaylist()){if(e&&e===this.mainPlaylistLoader_.media()){this.logger_("skipping fastQualityChange because new media is same as old");return}this.switchMedia_(e,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();const e=this.tech_.seekable();if(this.tech_.duration()===1/0&&this.tech_.currentTime()<e.start(0))return this.tech_.setCurrentTime(e.end(e.length-1))}setupFirstPlay(){const e=this.mainPlaylistLoader_.media();if(!e||this.tech_.paused()||this.hasPlayed_)return!1;if(!e.endList||e.start){const t=this.seekable();if(!t.length)return!1;const r=t.end(0);let n=r;if(e.start){const s=e.start.timeOffset;s<0?n=Math.max(r+s,t.start(0)):n=Math.min(r,s)}this.trigger("firstplay"),this.tech_.setCurrentTime(n)}return this.hasPlayed_=!0,this.load(),!0}handleSourceOpen_(){if(this.tryToCreateSourceBuffers_(),this.tech_.autoplay()){const e=this.tech_.play();typeof e<"u"&&typeof e.then=="function"&&e.then(null,t=>{})}this.trigger("sourceopen")}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;const e=this.inbandTextTracks_.metadataTrack_.cues;if(!e||!e.length)return;const t=this.duration();e[e.length-1].endTime=isNaN(t)||Math.abs(t)===1/0?Number.MAX_VALUE:t}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let e=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){const t=this.mainSegmentLoader_.getCurrentMediaInfo_();!t||t.hasVideo?e=e&&this.audioSegmentLoader_.ended_:e=this.audioSegmentLoader_.ended_}e&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(e){if(!this.seekable().length)return!1;const t=this.syncController_.getExpiredTime(e,this.duration());if(t===null)return!1;const r=Oi.Playlist.playlistEnd(e,t),n=this.tech_.currentTime(),s=this.tech_.buffered();if(!s.length)return r-n<=si;const a=s.end(s.length-1);return a-n<=si&&r-a<=si}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:r}){if(e=e||this.mainPlaylistLoader_.media(),r=r||t.playlistExclusionDuration||this.playlistExclusionDuration,!e){this.error=t,this.mediaSource.readyState!=="open"?this.trigger("error"):this.sourceUpdater_.endOfStream("network");return}e.playlistErrors_++;const n=this.mainPlaylistLoader_.main.playlists,s=n.filter(Ya),a=s.length===1&&s[0]===e;if(n.length===1&&r!==1/0)return F.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(a);if(a){if(this.main().contentSteering){const C=this.pathwayAttribute_(e),v=this.contentSteeringController_.steeringManifest.ttl*1e3;this.contentSteeringController_.excludePathway(C),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(C)},v);return}let S=!1;n.forEach(C=>{if(C===e)return;const v=C.excludeUntil;typeof v<"u"&&v!==1/0&&(S=!0,delete C.excludeUntil)}),S&&(F.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),this.tech_.trigger("retryplaylist"))}let l;e.playlistErrors_>this.maxPlaylistRetries?l=1/0:l=Date.now()+r*1e3,e.excludeUntil=l,t.reason&&(e.lastExcludeReason_=t.reason),this.tech_.trigger("excludeplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});const u=this.selectPlaylist();if(!u){this.error="Playback cannot continue. No available working or supported playlists.",this.trigger("error");return}const p=t.internal?this.logger_:F.log.warn,m=t.message?" "+t.message:"";p(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${m} Switching to playlist ${u.id}.`),u.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),u.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);const _=u.targetDuration/2*1e3||5*1e3,E=typeof u.lastRequest=="number"&&Date.now()-u.lastRequest<=_;return this.switchMedia_(u,"exclude",a||E)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(e,t){const r=[],n=e==="all";(n||e==="main")&&r.push(this.mainPlaylistLoader_);const s=[];(n||e==="audio")&&s.push("AUDIO"),(n||e==="subtitle")&&(s.push("CLOSED-CAPTIONS"),s.push("SUBTITLES")),s.forEach(a=>{const l=this.mediaTypes_[a]&&this.mediaTypes_[a].activePlaylistLoader;l&&r.push(l)}),["main","audio","subtitle"].forEach(a=>{const l=this[`${a}SegmentLoader_`];l&&(e===a||e==="all")&&r.push(l)}),r.forEach(a=>t.forEach(l=>{typeof a[l]=="function"&&a[l]()}))}setCurrentTime(e){const t=Ir(this.tech_.buffered(),e);if(!(this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media())||!this.mainPlaylistLoader_.media().segments)return 0;if(t&&t.length)return e;this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}duration(){if(!this.mainPlaylistLoader_)return 0;const e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:Oi.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}getSeekableRange_(e,t){const r=e.media();if(!r)return null;const n=this.syncController_.getMediaSequenceSync(t);if(n&&n.isReliable){const l=n.start,u=n.end;if(!isFinite(l)||!isFinite(u))return null;const p=Oi.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,r),m=Math.max(0,u-p);return m<l?null:at([[l,m]])}const s=this.syncController_.getExpiredTime(r,this.duration());if(s===null)return null;const a=Oi.Playlist.seekable(r,s,Oi.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,r));return a.length?a:null}computeFinalSeekable_(e,t){if(!t)return e;const r=e.start(0),n=e.end(0),s=t.start(0),a=t.end(0);return s>n||r>a?e:at([[Math.max(r,s),Math.min(n,a)]])}onSyncInfoUpdate_(){if(!this.mainPlaylistLoader_)return;const e=this.getSeekableRange_(this.mainPlaylistLoader_,"main");if(!e)return;let t;if(this.mediaTypes_.AUDIO.activePlaylistLoader&&(t=this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader,"audio"),!t))return;const r=this.seekable_;if(this.seekable_=this.computeFinalSeekable_(e,t),!this.seekable_||r&&r.length&&this.seekable_.length&&r.start(0)===this.seekable_.start(0)&&r.end(0)===this.seekable_.end(0))return;this.logger_(`seekable updated [${mg(this.seekable_)}]`);const n={seekableRanges:this.seekable_};this.trigger({type:"seekablerangeschanged",metadata:n}),this.tech_.trigger("seekablechanged")}updateDuration(e){if(this.updateDuration_&&(this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.updateDuration_=null),this.mediaSource.readyState!=="open"){this.updateDuration_=this.updateDuration.bind(this,e),this.mediaSource.addEventListener("sourceopen",this.updateDuration_);return}if(e){const n=this.seekable();if(!n.length)return;(isNaN(this.mediaSource.duration)||this.mediaSource.duration<n.end(n.length-1))&&this.sourceUpdater_.setDuration(n.end(n.length-1));return}const t=this.tech_.buffered();let r=Oi.Playlist.duration(this.mainPlaylistLoader_.media());t.length>0&&(r=Math.max(r,t.end(t.length-1))),this.mediaSource.duration!==r&&this.sourceUpdater_.setDuration(r)}dispose(){this.trigger("dispose"),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach(e=>{const t=this.mediaTypes_[e].groups;for(const r in t)t[r].forEach(n=>{n.playlistLoader&&n.playlistLoader.dispose()})}),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){const e=!!this.mediaTypes_.AUDIO.activePlaylistLoader,t=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),r=e?!!this.audioSegmentLoader_.getCurrentMediaInfo_():!0;return!(!t||!r)}getCodecsOrExclude_(){const e={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},t=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();e.video=e.main;const r=$n(this.main(),t),n={},s=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(n.video=r.video||e.main.videoCodec||ST),e.main.isMuxed&&(n.video+=`,${r.audio||e.main.audioCodec||ld}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||s)&&(n.audio=r.audio||e.main.audioCodec||e.audio.audioCodec||ld,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!n.audio&&!n.video){this.excludePlaylist({playlistToExclude:t,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});return}const a=(p,m)=>p?Un(m,this.usingManagedMediaSource_):Io(m),l={};let u;if(["video","audio"].forEach(function(p){if(n.hasOwnProperty(p)&&!a(e[p].isFmp4,n[p])){const m=e[p].isFmp4?"browser":"muxer";l[m]=l[m]||[],l[m].push(n[p]),p==="audio"&&(u=m)}}),s&&u&&t.attributes.AUDIO){const p=t.attributes.AUDIO;this.main().playlists.forEach(m=>{(m.attributes&&m.attributes.AUDIO)===p&&m!==t&&(m.excludeUntil=1/0)}),this.logger_(`excluding audio group ${p} as ${u} does not support codec(s): "${n.audio}"`)}if(Object.keys(l).length){const p=Object.keys(l).reduce((m,_)=>(m&&(m+=", "),m+=`${_} does not support codec(s): "${l[_].join(",")}"`,m),"")+".";this.excludePlaylist({playlistToExclude:t,error:{internal:!0,message:p},playlistExclusionDuration:1/0});return}if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const p=[];if(["video","audio"].forEach(m=>{const _=(ei(this.sourceUpdater_.codecs[m]||"")[0]||{}).type,E=(ei(n[m]||"")[0]||{}).type;_&&E&&_.toLowerCase()!==E.toLowerCase()&&p.push(`"${this.sourceUpdater_.codecs[m]}" -> "${n[m]}"`)}),p.length){this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${p.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0});return}}return n}tryToCreateSourceBuffers_(){if(this.mediaSource.readyState!=="open"||this.sourceUpdater_.hasCreatedSourceBuffers()||!this.areMediaTypesKnown_())return;const e=this.getCodecsOrExclude_();if(!e)return;this.sourceUpdater_.createSourceBuffers(e);const t=[e.video,e.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(t)}excludeUnsupportedVariants_(){const e=this.main().playlists,t=[];Object.keys(e).forEach(r=>{const n=e[r];if(t.indexOf(n.id)!==-1)return;t.push(n.id);const s=$n(this.main,n),a=[];s.audio&&!Io(s.audio)&&!Un(s.audio,this.usingManagedMediaSource_)&&a.push(`audio codec ${s.audio}`),s.video&&!Io(s.video)&&!Un(s.video,this.usingManagedMediaSource_)&&a.push(`video codec ${s.video}`),s.text&&s.text==="stpp.ttml.im1t"&&a.push(`text codec ${s.text}`),a.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id} for unsupported: ${a.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],r=this.main().playlists,n=ba(ei(e)),s=eh(n),a=n.video&&ei(n.video)[0]||null,l=n.audio&&ei(n.audio)[0]||null;Object.keys(r).forEach(u=>{const p=r[u];if(t.indexOf(p.id)!==-1||p.excludeUntil===1/0)return;t.push(p.id);const m=[],_=$n(this.mainPlaylistLoader_.main,p),E=eh(_);if(!(!_.audio&&!_.video)){if(E!==s&&m.push(`codec count "${E}" !== "${s}"`),!this.sourceUpdater_.canChangeType()){const S=_.video&&ei(_.video)[0]||null,C=_.audio&&ei(_.audio)[0]||null;S&&a&&S.type.toLowerCase()!==a.type.toLowerCase()&&m.push(`video codec "${S.type}" !== "${a.type}"`),C&&l&&C.type.toLowerCase()!==l.type.toLowerCase()&&m.push(`audio codec "${C.type}" !== "${l.type}"`)}m.length&&(p.excludeUntil=1/0,this.logger_(`excluding ${p.id}: ${m.join(" && ")}`))}})}updateAdCues_(e){let t=0;const r=this.seekable();r.length&&(t=r.start(0)),u2(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=Je.GOAL_BUFFER_LENGTH,r=Je.GOAL_BUFFER_LENGTH_RATE,n=Math.max(t,Je.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*r,n)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=Je.BUFFER_LOW_WATER_LINE,r=Je.BUFFER_LOW_WATER_LINE_RATE,n=Math.max(t,Je.MAX_BUFFER_LOW_WATER_LINE),s=Math.max(t,Je.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*r,this.bufferBasedABR?s:n)}bufferHighWaterLine(){return Je.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){rh(this.inbandTextTracks_,"com.apple.streaming",this.tech_),qw({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,r){const n=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();rh(this.inbandTextTracks_,e,this.tech_),Fw({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:n,videoDuration:r})}pathwayAttribute_(e){return e.attributes["PATHWAY-ID"]||e.attributes.serviceLocation}initContentSteeringController_(){const e=this.main();if(e.contentSteering){for(const t of e.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(t));if(this.contentSteeringController_.assignTagProperties(e.uri,e.contentSteering),this.contentSteeringController_.queryBeforeStart){this.contentSteeringController_.requestSteeringManifest(!0);return}this.tech_.one("canplay",()=>{this.contentSteeringController_.requestSteeringManifest()})}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on("content-steering",this.excludeThenChangePathway_.bind(this)),["contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach(e=>{this.contentSteeringController_.on(e,t=>{this.trigger(Ge({},t))})}),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const e=this.main();(this.contentSteeringController_.didDASHTagChange(e.uri,e.contentSteering)||(()=>{const t=this.contentSteeringController_.getAvailablePathways(),r=[];for(const n of e.playlists){const s=n.attributes.serviceLocation;if(s&&(r.push(s),!t.has(s)))return!0}return!!(!r.length&&t.size)})())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){const e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();const t=this.main().playlists,r=new Set;let n=!1;Object.keys(t).forEach(s=>{const a=t[s],l=this.pathwayAttribute_(a),u=l&&e!==l;a.excludeUntil===1/0&&a.lastExcludeReason_==="content-steering"&&!u&&(delete a.excludeUntil,delete a.lastExcludeReason_,n=!0);const p=!a.excludeUntil&&a.excludeUntil!==1/0;!r.has(a.id)&&u&&p&&(r.add(a.id),a.excludeUntil=1/0,a.lastExcludeReason_="content-steering",this.logger_(`excluding ${a.id} for ${a.lastExcludeReason_}`))}),this.contentSteeringController_.manifestType_==="DASH"&&Object.keys(this.mediaTypes_).forEach(s=>{const a=this.mediaTypes_[s];if(a.activePlaylistLoader){const l=a.activePlaylistLoader.media_;l&&l.attributes.serviceLocation!==e&&(n=!0)}}),n&&this.changeSegmentPathway_()}handlePathwayClones_(){const e=this.main().playlists,t=this.contentSteeringController_.currentPathwayClones,r=this.contentSteeringController_.nextPathwayClones;if(t&&t.size||r&&r.size){for(const[n,s]of t.entries())r.get(n)||(this.mainPlaylistLoader_.updateOrDeleteClone(s),this.contentSteeringController_.excludePathway(n));for(const[n,s]of r.entries()){const a=t.get(n);if(!a){e.filter(l=>l.attributes["PATHWAY-ID"]===s["BASE-ID"]).forEach(l=>{this.mainPlaylistLoader_.addClonePathway(s,l)}),this.contentSteeringController_.addAvailablePathway(n);continue}this.equalPathwayClones_(a,s)||(this.mainPlaylistLoader_.updateOrDeleteClone(s,!0),this.contentSteeringController_.addAvailablePathway(n))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...r])))}}equalPathwayClones_(e,t){if(e["BASE-ID"]!==t["BASE-ID"]||e.ID!==t.ID||e["URI-REPLACEMENT"].HOST!==t["URI-REPLACEMENT"].HOST)return!1;const r=e["URI-REPLACEMENT"].PARAMS,n=t["URI-REPLACEMENT"].PARAMS;for(const s in r)if(r[s]!==n[s])return!1;for(const s in n)if(r[s]!==n[s])return!1;return!0}changeSegmentPathway_(){const e=this.selectPlaylist();this.pauseLoading(),this.contentSteeringController_.manifestType_==="DASH"&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0;const t="non-usable";this.mainPlaylistLoader_.main.playlists.forEach(r=>{const n=this.mainPlaylistLoader_.getKeyIdSet(r);!n||!n.size||n.forEach(s=>{const a="usable",l=this.keyStatusMap_.has(s)&&this.keyStatusMap_.get(s)===a,u=r.lastExcludeReason_===t&&r.excludeUntil===1/0;l?l&&u&&(delete r.excludeUntil,delete r.lastExcludeReason_,this.logger_(`enabling playlist ${r.id} because key ID ${s} is ${a}`)):(r.excludeUntil!==1/0&&r.lastExcludeReason_!==t&&(r.excludeUntil=1/0,r.lastExcludeReason_=t,this.logger_(`excluding playlist ${r.id} because the key ID ${s} doesn't exist in the keyStatusMap or is not ${a}`)),e++)})}),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(r=>{const n=r&&r.attributes&&r.attributes.RESOLUTION&&r.attributes.RESOLUTION.height<720,s=r.excludeUntil===1/0&&r.lastExcludeReason_===t;n&&s&&(delete r.excludeUntil,F.log.warn(`enabling non-HD playlist ${r.id} because all playlists were excluded due to ${t} key IDs`))})}addKeyStatus_(e,t){const r=(typeof e=="string"?e:s2(e)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${t}' with key ID ${r} added to the keyStatusMap`),this.keyStatusMap_.set(r,t)}updatePlaylistByKeyStatus(e,t){this.addKeyStatus_(e,t),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}}const R2=(i,e,t)=>r=>{const n=i.main.playlists[e],s=wu(n),a=Ya(n);if(typeof r>"u")return a;r?delete n.disabled:n.disabled=!0;const l={renditionInfo:{id:e,bandwidth:n.attributes.BANDWIDTH,resolution:n.attributes.RESOLUTION,codecs:n.attributes.CODECS},cause:"fast-quality"};return r!==a&&!s&&(r?(t(n),i.trigger({type:"renditionenabled",metadata:l})):i.trigger({type:"renditiondisabled",metadata:l})),r};class N2{constructor(e,t,r){const{playlistController_:n}=e,s=n.fastQualityChange_.bind(n);if(t.attributes){const a=t.attributes.RESOLUTION;this.width=a&&a.width,this.height=a&&a.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=$n(n.main(),t),this.playlist=t,this.id=r,this.enabled=R2(e.playlists,t.id,s)}}const O2=function(i){i.representations=()=>{const e=i.playlistController_.main(),t=as(e)?i.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(r=>!wu(r)).map((r,n)=>new N2(i,r,r.id)):[]}},mh=["seeking","seeked","pause","playing","error"];class U2 extends F.EventTarget{constructor(e){super(),this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.playedRanges_=[],this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=jt("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),r=()=>this.monitorCurrentTime_(),n=()=>this.techWaiting_(),s=()=>this.resetTimeUpdate_(),a=this.playlistController_,l=["main","subtitle","audio"],u={};l.forEach(m=>{u[m]={reset:()=>this.resetSegmentDownloads_(m),updateend:()=>this.checkSegmentDownloads_(m)},a[`${m}SegmentLoader_`].on("appendsdone",u[m].updateend),a[`${m}SegmentLoader_`].on("playlistupdate",u[m].reset),this.tech_.on(["seeked","seeking"],u[m].reset)});const p=m=>{["main","audio"].forEach(_=>{a[`${_}SegmentLoader_`][m]("appended",this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),p("off"))},this.clearSeekingAppendCheck_=()=>p("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),p("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",n),this.tech_.on(mh,s),this.tech_.on("canplay",r),this.tech_.one("play",t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",n),this.tech_.off(mh,s),this.tech_.off("canplay",r),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),l.forEach(m=>{a[`${m}SegmentLoader_`].off("appendsdone",u[m].updateend),a[`${m}SegmentLoader_`].off("playlistupdate",u[m].reset),this.tech_.off(["seeked","seeking"],u[m].reset)}),this.checkCurrentTimeTimeout_&&x.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&x.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=x.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(e){const t=this.playlistController_[`${e}SegmentLoader_`];this[`${e}StalledDownloads_`]>0&&this.logger_(`resetting possible stalled download count for ${e} loader`),this[`${e}StalledDownloads_`]=0,this[`${e}Buffered_`]=t.buffered_()}checkSegmentDownloads_(e){const t=this.playlistController_,r=t[`${e}SegmentLoader_`],n=r.buffered_(),s=vE(this[`${e}Buffered_`],n);if(this[`${e}Buffered_`]=n,s){const a={bufferedRanges:n};t.trigger({type:"bufferedrangeschanged",metadata:a}),this.resetSegmentDownloads_(e);return}this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:r.playlist_&&r.playlist_.id,buffered:ir(n)}),!(this[`${e}StalledDownloads_`]<10)&&(this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:"usage",name:`vhs-${e}-download-exclusion`}),e!=="subtitle"&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0}))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;const e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+si>=t.end(t.length-1)))return this.techWaiting_();if(this.consecutiveUpdates>=5&&e===this.lastRecordedTime)this.consecutiveUpdates++,this.waiting_();else if(e===this.lastRecordedTime)this.consecutiveUpdates++;else{this.playedRanges_.push(at([this.lastRecordedTime,e]));const r={playedRanges:this.playedRanges_};this.playlistController_.trigger({type:"playedrangeschanged",metadata:r}),this.consecutiveUpdates=0,this.lastRecordedTime=e}}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;const e=this.seekable(),t=this.tech_.currentTime(),r=this.afterSeekableWindow_(e,t,this.media(),this.allowSeeksWithinUnsafeLiveWindow);let n;if(r&&(n=e.end(e.length-1)),this.beforeSeekableWindow_(e,t)){const S=e.start(0);n=S+(S===e.end(0)?0:si)}if(typeof n<"u")return this.logger_(`Trying to seek outside of seekable at time ${t} with seekable range ${mg(e)}. Seeking to ${n}.`),this.tech_.setCurrentTime(n),!0;const s=this.playlistController_.sourceUpdater_,a=this.tech_.buffered(),l=s.audioBuffer?s.audioBuffered():null,u=s.videoBuffer?s.videoBuffered():null,p=this.media(),m=p.partTargetDuration?p.partTargetDuration:(p.targetDuration-ni)*2,_=[l,u];for(let S=0;S<_.length;S++)if(_[S]&&Su(_[S],t)<m)return!1;const E=js(a,t);return E.length===0?!1:(n=E.start(0)+si,this.logger_(`Buffered region starts (${E.start(0)}) just beyond seek point (${t}). Seeking to ${n}.`),this.tech_.setCurrentTime(n),!0)}waiting_(){if(this.techWaiting_())return;const e=this.tech_.currentTime(),t=this.tech_.buffered(),r=Ir(t,e);if(r.length&&e+3<=r.end(0)){this.resetTimeUpdate_(),this.tech_.setCurrentTime(e),this.logger_(`Stopped at ${e} while inside a buffered region [${r.start(0)} -> ${r.end(0)}]. Attempting to resume playback by seeking to the current time.`),this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"});return}}techWaiting_(){const e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){const a=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${a}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(a),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}const r=this.tech_.vhs.playlistController_.sourceUpdater_,n=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:r.audioBuffered(),videoBuffered:r.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;const s=js(n,t);return s.length>0?(this.logger_(`Stopped at ${t} and seeking to ${s.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0):!1}afterSeekableWindow_(e,t,r,n=!1){if(!e.length)return!1;let s=e.end(e.length-1)+si;const a=!r.endList,l=typeof r.partTargetDuration=="number";return a&&(l||n)&&(s=e.end(e.length-1)+r.targetDuration*3),t>s}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t<e.start(0)-this.liveRangeSafeTimeDelta)}videoUnderflow_({videoBuffered:e,audioBuffered:t,currentTime:r}){if(!e)return;let n;if(e.length&&t.length){const s=Ir(e,r-3),a=Ir(e,r),l=Ir(t,r);l.length&&!a.length&&s.length&&(n={start:s.end(0),end:l.end(0)})}else js(e,r).length||(n=this.gapFromVideoUnderflow_(e,r));return n?(this.logger_(`Encountered a gap in video from ${n.start} to ${n.end}. Seeking to current time ${r}`),!0):!1}skipTheGap_(e){const t=this.tech_.buffered(),r=this.tech_.currentTime(),n=js(t,r);if(this.resetTimeUpdate_(),n.length===0||r!==e)return;this.logger_("skipTheGap_:","currentTime:",r,"scheduled currentTime:",e,"nextRange start:",n.start(0)),this.tech_.setCurrentTime(n.start(0)+ni);const s={gapInfo:{from:r,to:n.start(0)}};this.playlistController_.trigger({type:"gapjumped",metadata:s}),this.tech_.trigger({type:"usage",name:"vhs-gap-skip"})}gapFromVideoUnderflow_(e,t){const r=yE(e);for(let n=0;n<r.length;n++){const s=r.start(n),a=r.end(n);if(t-s<4&&t-s>2)return{start:s,end:a}}return null}}const M2={errorInterval:30,getSource(i){const e=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return i(e)}},sf=function(i,e){let t=0,r=0;const n=_e(M2,e);i.ready(()=>{i.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const s=function(){r&&i.currentTime(r)},a=function(m){m!=null&&(r=i.duration()!==1/0&&i.currentTime()||0,i.one("loadedmetadata",s),i.src(m),i.trigger({type:"usage",name:"vhs-error-reload"}),i.play())},l=function(){if(Date.now()-t<n.errorInterval*1e3){i.trigger({type:"usage",name:"vhs-error-reload-canceled"});return}if(!n.getSource||typeof n.getSource!="function"){F.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!");return}return t=Date.now(),n.getSource.call(i,a)},u=function(){i.off("loadedmetadata",s),i.off("error",l),i.off("dispose",u)},p=function(m){u(),sf(i,m)};i.on("error",l),i.on("dispose",u),i.reloadSourceOnError=p},B2=function(i){sf(this,i)};var af="3.16.2",F2="7.1.0",j2="1.3.1",$2="7.2.0",q2="4.0.2";const Be={PlaylistLoader:Ar,Playlist:Tt,utils:HE,STANDARD_PLAYLIST_SELECTOR:ih,INITIAL_PLAYLIST_SELECTOR:Nw,lastBandwidthSelector:ih,movingAverageBandwidthSelector:Pw,comparePlaylistBandwidth:Iu,comparePlaylistResolution:Dw,xhr:Dg()};Object.keys(Je).forEach(i=>{Object.defineProperty(Be,i,{get(){return F.log.warn(`using Vhs.${i} is UNSAFE be sure you know what you are doing`),Je[i]},set(e){if(F.log.warn(`using Vhs.${i} is UNSAFE be sure you know what you are doing`),typeof e!="number"||e<0){F.log.warn(`value of Vhs.${i} must be greater than or equal to 0`);return}Je[i]=e}})});const of="videojs-vhs",lf=function(i,e){const t=e.media();let r=-1;for(let n=0;n<i.length;n++)if(i[n].id===t.id){r=n;break}i.selectedIndex_=r,i.trigger({selectedIndex:r,type:"change"})},V2=function(i,e){e.representations().forEach(t=>{i.addQualityLevel(t)}),lf(i,e.playlists)};Be.canPlaySource=function(){return F.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const H2=(i,e,t)=>{if(!i)return i;let r={};e&&e.attributes&&e.attributes.CODECS&&(r=ba(ei(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(r.audio=t.attributes.CODECS);const n=jr(r.video),s=jr(r.audio),a={};for(const l in i)a[l]={},s&&(a[l].audioContentType=s),n&&(a[l].videoContentType=n),e.contentProtection&&e.contentProtection[l]&&e.contentProtection[l].pssh&&(a[l].pssh=e.contentProtection[l].pssh),typeof i[l]=="string"&&(a[l].url=i[l]);return _e(i,a)},z2=(i,e)=>i.reduce((t,r)=>{if(!r.contentProtection)return t;const n=e.reduce((s,a)=>{const l=r.contentProtection[a];return l&&l.pssh&&(s[a]={pssh:l.pssh}),s},{});return Object.keys(n).length&&t.push(n),t},[]),W2=({player:i,sourceKeySystems:e,audioMedia:t,mainPlaylists:r})=>{if(!i.eme.initializeMediaKeys)return Promise.resolve();const n=t?r.concat([t]):r,s=z2(n,Object.keys(e)),a=[],l=[];return s.forEach(u=>{l.push(new Promise((p,m)=>{i.tech_.one("keysessioncreated",p)})),a.push(new Promise((p,m)=>{i.eme.initializeMediaKeys({keySystems:u},_=>{if(_){m(_);return}p()})}))}),Promise.race([Promise.all(a),Promise.race(l)])},G2=({player:i,sourceKeySystems:e,media:t,audioMedia:r})=>{const n=H2(e,t,r);return n?(i.currentSource().keySystems=n,n&&!i.eme?(F.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0):!1},uf=()=>{if(!x.localStorage)return null;const i=x.localStorage.getItem(of);if(!i)return null;try{return JSON.parse(i)}catch{return null}},X2=i=>{if(!x.localStorage)return!1;let e=uf();e=e?_e(e,i):i;try{x.localStorage.setItem(of,JSON.stringify(e))}catch{return!1}return e},K2=i=>i.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(i.substring(i.indexOf(",")+1)):i,cf=(i,e)=>{i._requestCallbackSet||(i._requestCallbackSet=new Set),i._requestCallbackSet.add(e)},df=(i,e)=>{i._responseCallbackSet||(i._responseCallbackSet=new Set),i._responseCallbackSet.add(e)},hf=(i,e)=>{i._requestCallbackSet&&(i._requestCallbackSet.delete(e),i._requestCallbackSet.size||delete i._requestCallbackSet)},pf=(i,e)=>{i._responseCallbackSet&&(i._responseCallbackSet.delete(e),i._responseCallbackSet.size||delete i._responseCallbackSet)};Be.supportsNativeHls=function(){if(!X||!X.createElement)return!1;const i=X.createElement("video");return F.getTech("Html5").isSupported()?["application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"].some(function(e){return/maybe|probably/i.test(i.canPlayType(e))}):!1}();Be.supportsNativeDash=function(){return!X||!X.createElement||!F.getTech("Html5").isSupported()?!1:/maybe|probably/i.test(X.createElement("video").canPlayType("application/dash+xml"))}();Be.supportsTypeNatively=i=>i==="hls"?Be.supportsNativeHls:i==="dash"?Be.supportsNativeDash:!1;Be.isSupported=function(){return F.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};Be.xhr.onRequest=function(i){cf(Be.xhr,i)};Be.xhr.onResponse=function(i){df(Be.xhr,i)};Be.xhr.offRequest=function(i){hf(Be.xhr,i)};Be.xhr.offResponse=function(i){pf(Be.xhr,i)};const Y2=F.getComponent("Component");class mf extends Y2{constructor(e,t,r){if(super(t,r.vhs),typeof r.initialBandwidth=="number"&&(this.options_.bandwidth=r.initialBandwidth),this.logger_=jt("VhsHandler"),t.options_&&t.options_.playerId){const n=F.getPlayer(t.options_.playerId);this.player_=n}if(this.tech_=t,this.source_=e,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&t.overrideNativeAudioTracks&&t.overrideNativeVideoTracks)t.overrideNativeAudioTracks(!0),t.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(t.featuresNativeVideoTracks||t.featuresNativeAudioTracks))throw new Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on(X,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],n=>{const s=X.fullscreenElement||X.webkitFullscreenElement||X.mozFullScreenElement||X.msFullscreenElement;s&&s.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()}),this.on(this.tech_,"seeking",function(){if(this.ignoreNextSeekingEvent_){this.ignoreNextSeekingEvent_=!1;return}this.setCurrentTime(this.tech_.currentTime())}),this.on(this.tech_,"error",function(){this.tech_.error()&&this.playlistController_&&this.playlistController_.pauseLoading()}),this.on(this.tech_,"play",this.play)}setOptions_(e={}){if(this.options_=_e(this.options_,e),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions!==!1,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.useBandwidthFromLocalStorage=typeof this.source_.useBandwidthFromLocalStorage<"u"?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=this.options_.useNetworkInformationApi||!1,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=this.options_.llhls!==!1,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,typeof this.options_.playlistExclusionDuration!="number"&&(this.options_.playlistExclusionDuration=60),typeof this.options_.bandwidth!="number"&&this.options_.useBandwidthFromLocalStorage){const r=uf();r&&r.bandwidth&&(this.options_.bandwidth=r.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),r&&r.throughput&&(this.options_.throughput=r.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"}))}typeof this.options_.bandwidth!="number"&&(this.options_.bandwidth=Je.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===Je.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","customPixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR","liveRangeSafeTimeDelta","llhls","useForcedSubtitles","useNetworkInformationApi","useDtsForTimestampOffset","exactManifestTimings","leastPixelDiffSelector"].forEach(r=>{typeof this.source_[r]<"u"&&(this.options_[r]=this.source_[r])}),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio;const t=this.options_.customPixelRatio;typeof t=="number"&&t>=0&&(this.customPixelRatio=t)}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=K2(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=Be,this.options_.sourceType=Rp(t),this.options_.seekTo=s=>{this.tech_.setCurrentTime(s)},this.options_.player_=this.player_,this.playlistController_=new P2(this.options_);const r=_e({liveRangeSafeTimeDelta:si},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new U2(r),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{const s=F.players[this.tech_.options_.playerId];let a=this.playlistController_.error;typeof a=="object"&&!a.code?a.code=3:typeof a=="string"&&(a={message:a,code:3}),s.error(a)});const n=this.options_.bufferBasedABR?Be.movingAverageBandwidthSelector(.55):Be.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):n.bind(this),this.playlistController_.selectInitialPlaylist=Be.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPlaylist},set(s){this.playlistController_.selectPlaylist=s.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(s){this.playlistController_.mainSegmentLoader_.throughput.rate=s,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let s=this.playlistController_.mainSegmentLoader_.bandwidth;const a=x.navigator.connection||x.navigator.mozConnection||x.navigator.webkitConnection,l=1e7;if(this.options_.useNetworkInformationApi&&a){const u=a.downlink*1e3*1e3;u>=l&&s>=l?s=Math.max(s,u):s=u}return s},set(s){this.playlistController_.mainSegmentLoader_.bandwidth=s,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){const s=1/(this.bandwidth||1);let a;return this.throughput>0?a=1/this.throughput:a=0,Math.floor(1/(s+a))},set(){F.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playlistController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>ir(this.tech_.buffered()),enumerable:!0},currentTime:{get:()=>this.tech_.currentTime(),enumerable:!0},currentSource:{get:()=>this.tech_.currentSource_,enumerable:!0},currentTech:{get:()=>this.tech_.name_,enumerable:!0},duration:{get:()=>this.tech_.duration(),enumerable:!0},main:{get:()=>this.playlists.main,enumerable:!0},playerDimensions:{get:()=>this.tech_.currentDimensions(),enumerable:!0},seekable:{get:()=>ir(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one("canplay",this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on("bandwidthupdate",()=>{this.options_.useBandwidthFromLocalStorage&&X2({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{O2(this)}),this.playlistController_.sourceUpdater_.on("createdsourcebuffers",()=>{this.setupEme_()}),this.on(this.playlistController_,"progress",function(){this.tech_.trigger("progress")}),this.on(this.playlistController_,"firstplay",function(){this.ignoreNextSeekingEvent_=!0}),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=x.URL.createObjectURL(this.playlistController_.mediaSource),(F.browser.IS_ANY_SAFARI||F.browser.IS_IOS)&&this.options_.overrideNative&&this.options_.sourceType==="hls"&&typeof this.tech_.addSourceElement=="function"?(this.tech_.addSourceElement(this.mediaSourceUrl_),this.tech_.addSourceElement(this.source_.src)):this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),W2({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:e&&e.media(),mainPlaylists:this.playlists.main.playlists}).then(()=>{this.logger_("created EME key session"),this.playlistController_.sourceUpdater_.initializedEme()}).catch(t=>{this.logger_("error while creating EME key session",t),this.player_.error({message:"Failed to initialize media keys for EME",code:3})})}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=G2({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});if(this.player_.tech_.on("keystatuschange",r=>{this.playlistController_.updatePlaylistByKeyStatus(r.keyId,r.status)}),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),!t){this.playlistController_.sourceUpdater_.initializedEme();return}this.createKeySessions_()}setupQualityLevels_(){const e=F.players[this.tech_.options_.playerId];!e||!e.qualityLevels||this.qualityLevels_||(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{V2(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{lf(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":af,"mux.js":F2,"mpd-parser":j2,"m3u8-parser":$2,"aes-decrypter":q2}}version(){return this.constructor.version()}canChangeType(){return ef.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(e){this.playlistController_.setCurrentTime(e)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&x.URL.revokeObjectURL&&(x.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return QE({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,r=!0,n=2){return Ug({programTime:e,playlist:this.playlistController_.media(),retryCount:n,pauseAfterSeek:r,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{cf(this.xhr,e)},this.xhr.onResponse=e=>{df(this.xhr,e)},this.xhr.offRequest=e=>{hf(this.xhr,e)},this.xhr.offResponse=e=>{pf(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}attachStreamingEventListeners_(){const e=["seekablerangeschanged","bufferedrangeschanged","contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"],t=["gapjumped","playedrangeschanged"];e.forEach(r=>{this.playlistController_.on(r,n=>{this.player_.trigger(Ge({},n))})}),t.forEach(r=>{this.playbackWatcher_.on(r,n=>{this.player_.trigger(Ge({},n))})})}}const Sa={name:"videojs-http-streaming",VERSION:af,canHandleSource(i,e={}){const t=_e(F.options,e);return!t.vhs.experimentalUseMMS&&!Un("avc1.4d400d,mp4a.40.2",!1)?!1:Sa.canPlayType(i.type,t)},handleSource(i,e,t={}){const r=_e(F.options,t);return e.vhs=new mf(i,e,r),e.vhs.xhr=Dg(),e.vhs.setupXhrHooks_(),e.vhs.src(i.src,i.type),e.vhs},canPlayType(i,e){const t=Rp(i);if(!t)return"";const r=Sa.getOverrideNative(e);return!Be.supportsTypeNatively(t)||r?"maybe":""},getOverrideNative(i={}){const{vhs:e={}}=i,t=!(F.browser.IS_ANY_SAFARI||F.browser.IS_IOS),{overrideNative:r=t}=e;return r}},Q2=()=>Un("avc1.4d400d,mp4a.40.2",!0);Q2()&&F.getTech("Html5").registerSourceHandler(Sa,0);F.VhsHandler=mf;F.VhsSourceHandler=Sa;F.Vhs=Be;F.use||F.registerComponent("Vhs",Be);F.options.vhs=F.options.vhs||{};(!F.getPlugin||!F.getPlugin("reloadSourceOnError"))&&F.registerPlugin("reloadSourceOnError",B2);const J2=i=>{const e=Se.useRef();return Se.useEffect(()=>{if(!e.current&&i.current){const t=document.createElement("video-js");t.classList.add("vjs-big-play-centered"),i.current.appendChild(t),e.current=F(t,{controls:!1,playsinline:!0})}return()=>{e.current&&(e.current.dispose(),e.current=void 0)}},[]),e},gf={time:0,adCount:0,adPosition:0,skipDelay:0,playing:!1,paused:!1,reset:()=>{},whyThisAd:null,hasAdUrl:!1,adAction:i=>{},playMuted:!1,muted:!1,autoplay:!0},Re=G.i(gf),gh=i=>{if(!i)return 0;const e=i.duration(),t=i.currentTime();return e===void 0||isNaN(e)||t===void 0||isNaN(t)?0:Math.round(e-t)},Z2=(i,e)=>{const t=Ib(i,e),r=J2(i),n=Se.useRef(),s=Se.useRef(!1),a=Se.useRef(!1),l=Se.useCallback(()=>{if(a.current)return;const S=t.get().nonceManager;if(S&&s.current)try{S.sendPlaybackEnd()}catch(C){console.warn("[PAL] sendPlaybackEnd failed",C)}a.current=!0},[t]),u=Se.useCallback(()=>{l(),r.current&&(r.current.pause(),r.current.src(void 0)),n.current=void 0,Re.set({...gf,reset:u})},[r,l]);Se.useEffect(()=>{Re.setKey("reset",u)},[u]);const p=Se.useCallback(()=>{var S,C,v;const{adPosition:L,adCount:D}=Re.get();if(r.current){if(L<D){const U=L+1,{ads:O,muted:B,autoplay:P,nonceManager:$}=t.get(),Q=O[U-1];if(Q){(S=n.current)==null||S.complete(),n.current=new _b(null,Q.ad,Q.creative),n.current.on("clickthrough",K=>{if($)try{$.sendAdClick()}catch(ie){console.warn("[PAL] sendAdClick failed",ie)}window.open(K,"_blank")}),Re.setKey("adPosition",U),Re.setKey("playMuted",B),Re.setKey("skipDelay",Q.creative.skipDelay||0),Re.setKey("time",0),Re.setKey("adAction",K=>{n.current&&n.current.click(null,{CLICKPOS:[K.clientX,K.clientY]})}),Re.setKey("whyThisAd",Q.creative.icons.find(K=>K.program==="GoogleWhyThisAd")||null),Re.setKey("hasAdUrl",!!((C=Q.creative.videoClickThroughURLTemplate)!=null&&C.url)),r.current.src(Q.mediaFileUrl),Re.setKey("playing",!0),L===0?(Re.setKey("muted",B),Re.setKey("autoplay",P),B&&r.current.muted(!0),P?r.current.play():(r.current.pause(),Re.setKey("paused",!0))):r.current.play();return}}(v=n.current)==null||v.complete(),u()}},[r,u,t]),m=Se.useCallback(()=>{if(!r.current)return;const S=r.current.muted();r.current.muted(!S),Re.setKey("muted",!S),n.current&&n.current.setMuted(!S)},[r]),_=Se.useCallback(()=>{r.current&&(r.current.paused()?(r.current.play(),n.current&&n.current.setPaused(!1)):(r.current.pause(),n.current&&n.current.setPaused(!0)))},[r]),E=Se.useCallback(()=>{r.current&&(n.current&&n.current.skip(),p())},[p,r]);return Se.useEffect(()=>{const S=r.current;if(!S)return()=>{};const C=P=>{if(Re.setKey("playing",!0),Re.setKey("paused",!1),Re.setKey("time",gh(P.target.player)),!s.current){const $=t.get().nonceManager;if($)try{$.sendPlaybackStart(),s.current=!0,a.current=!1}catch(Q){console.warn("[PAL] sendPlaybackStart failed",Q)}}},v=()=>{var P;(P=n.current)==null||P.complete(),p()},L=P=>{Re.setKey("muted",P.target.player.muted())},D=()=>{Re.setKey("paused",!0)},U=P=>{P.target.tagName==="VIDEO"&&(Re.get().autoplay||_())},O=P=>{Re.setKey("time",gh(P.target.player)),n.current&&n.current.setProgress(P.target.player.currentTime())},B=()=>{u()};return S.on("play",C),S.on("ended",v),S.on("muted",L),S.on("pause",D),S.on("click",U),S.on("timeupdate",O),S.on("error",B),()=>{S.off("play",C),S.off("ended",v),S.off("muted",L),S.off("pause",D),S.off("click",U),S.off("timeupdate",O),S.off("error",B)}},[_,p,r,u,t]),Se.useEffect(()=>t.subscribe(S=>{S&&(s.current=!1,a.current=!1,Re.setKey("adCount",S.ads.length),Re.setKey("adPosition",0),p())}),[t,r,p]),Se.useEffect(()=>()=>{u()},[u]),[Re,m,_,E,n]},ek=({promotion:i,onClose:e,promotionId:t,externalAd:r,skipAutoClose:n})=>{var s,a,l,u,p;const m=Se.useRef(null),[_,E,S,C]=Z2(m,r==null?void 0:r.url),{time:v,adCount:L,adPosition:D,skipDelay:U,playing:O,paused:B,reset:P,muted:$,playMuted:Q,autoplay:K,whyThisAd:ie,hasAdUrl:me,adAction:oe}=G.useStore(_),ge=((s=i.sponsor)==null?void 0:s.logo)&&i.logoMode===ce.PromotionLogoMode.CENTER;return W.jsxs(kh,{className:"PromoOverlay",children:[W.jsxs(Ch,{children:[W.jsx(Ih,{className:G.cx_default(!ge&&Ah),children:W.jsx(Lh,{style:{transform:"scale(1.5)"},children:"Ad"})}),W.jsxs(eb,{children:[W.jsx(z0,{time:v,adCount:L,adPosition:D}),!!U&&O&&W.jsx(G.y,{timerClassName:"SkipTimerCount",className:"ClosePromoIcon",close:()=>{C()},duration:U,isPlaying:!B,skipIcon:!0}),n&&W.jsx(G.y,{className:"ClosePromoIcon",close:()=>{P(),e==null||e()}})]})]}),W.jsx(xh,{className:G.cx_default(Sc,O&&Ec,!O&&wc),children:W.jsxs(Z0,{ref:m,children:[ie&&W.jsx(G0,{whyThisAd:ie}),W.jsxs(X0,{style:(ie==null?void 0:ie.xPosition)==="right"?{left:"8px"}:{right:"8px"},children:[Q&&W.jsx(Y0,{className:G.cx_default(!$&&"muted"),onClick:()=>E()}),B&&!K&&W.jsx(J0,{onClick:()=>S()})]})]})}),me&&W.jsx(Dh,{className:G.cx_default(Sc,O&&Ec,!O&&wc),children:W.jsx(Ph,{as:"button",onClick:oe,style:{backgroundColor:((l=(a=i.banner)==null?void 0:a.ctaButton)==null?void 0:l.color)||"#009dc4",color:((p=(u=i.banner)==null?void 0:u.ctaButton)==null?void 0:p.textColor)||"#fff"},"data-a":"button","data-promo-id":t,"data-promo-type":i.type,target:"_blank",children:"Show more"})})]})},fh=i=>{var e,t,r,n,s,a,l,u,p,m,_,E,S,C,v,L,D,U,O,B,P,$,Q,K,ie,me,oe,ge,ee,ue;const{promotion:te,open:de,advertisementPaused:be,togglePause:je,controlVideo:Ye,skipAutoClose:ve,promotionId:ye,onClose:kt,markAsViewed:Pt,externalAd:xe,isEventFired:pe,fireEvent:$e,muted:dr}=i,wi=te.type===ce.PromotionType.INGAME_IAB11_LBAR||te.type===ce.PromotionType.INGAME_IAB11||te.type===ce.PromotionType.INGAME_IAB11_SIDEBAR,ki=((e=te.sponsor)==null?void 0:e.logo)&&te.logoMode===ce.PromotionLogoMode.CENTER,qi=!!((r=(t=te.banner)==null?void 0:t.video)!=null&&r.url),Ct=te.autoPlayVideo===ce.AutoPlayVideo.ENABLED,Ci=te.playVideoMuted===ce.PlayVideoMuted.ENABLED;if(Se.useEffect(()=>{je==null||je(qi||Ct),de==null||de()},[]),Se.useEffect(()=>{ye&&te.type&&Pt&&Pt()},[ye,te.type,Pt]),Se.useEffect(()=>()=>{Ye==null||Ye({muted:!1})},[Ye]),xe)return W.jsx(ek,{...i,externalAd:xe});let Kt=(n=te.banner)==null?void 0:n.url;Kt&&Kt.indexOf("http")!==0&&(Kt=`https://${Kt}`);let Vi=!0;return qi&&(!be||!Ct?Vi=!0:Vi=!1),W.jsxs(kh,{className:"PromoOverlay",children:[W.jsxs("div",{children:[W.jsxs(Ch,{children:[W.jsxs(Ih,{className:G.cx_default(!ki&&Ah),children:[((s=te.sponsor)==null?void 0:s.logo)&&te.logoMode===ce.PromotionLogoMode.LEFT&&W.jsx(bc,{className:"PromoSponsorLogo",src:(a=te.sponsor)==null?void 0:a.logo,alt:"promo"}),W.jsxs(B0,{style:{paddingLeft:(l=te.sponsor)!=null&&l.logo&&te.logoMode===ce.PromotionLogoMode.LEFT?"0px":"8px"},children:[((u=te.sponsor)==null?void 0:u.logo)&&te.logoMode===ce.PromotionLogoMode.LEFT&&W.jsx(N0,{children:(p=te.sponsor)==null?void 0:p.name}),W.jsxs(F0,{className:"SponsorText",children:[W.jsx(Lh,{children:"AD"}),W.jsx(j0,{children:"SPONSORED"})]})]})]}),W.jsx(G.y,{className:"ClosePromoIcon",close:kt,autoClose:(m=te.closeTimer)==null?void 0:m.auto,duration:ve?0:(_=te.closeTimer)==null?void 0:_.seconds,isPlaying:Vi})]}),W.jsxs(xh,{children:[ki&&W.jsx(bc,{className:U0,src:(E=te.sponsor)==null?void 0:E.logo,alt:"promo"}),W.jsx(vc,{children:(C=(S=te.banner)==null?void 0:S.video)!=null&&C.url?W.jsx(G.Pe,{source:(L=(v=te.banner)==null?void 0:v.video)==null?void 0:L.url,poster:(U=(D=te.banner)==null?void 0:D.video)==null?void 0:U.thumbnailUrl,aspectRatio:wi?"1/1":"2/1",onRender:()=>{pe!=null&&pe("video-rendered")||(G.eventBus.emit("advertisement",{action:"videoRendered",payload:{id:ye,type:te.type}}),$e==null||$e("video-rendered"))},onQuartile:$t=>{pe!=null&&pe(`video-quartile-${$t}`)||(G.eventBus.emit("advertisement",{action:"quartileCompleted",payload:{id:ye,type:te.type,quartile:$t}}),$e==null||$e(`video-quartile-${$t}`))},onMute:$t=>{const qt=$t?"muted":"unmuted";pe!=null&&pe(qt)||(G.eventBus.emit("advertisement",{action:$t?"videoMuted":"videoUnmuted",payload:{id:ye,type:te.type}}),$e==null||$e(qt))},onPause:()=>{Ct&&(je==null||je(!0))},onReplay:()=>{pe!=null&&pe("replayed")||(G.eventBus.emit("advertisement",{action:"videoReplayed",payload:{id:ye,type:te.type}}),$e==null||$e("replayed"))},onPlay:()=>{pe!=null&&pe("played")||(G.eventBus.emit("advertisement",{action:"videoPlay",payload:{id:ye,type:te.type}}),$e==null||$e("played")),je==null||je(!1),pe!=null&&pe("played")&&pe!=null&&pe("ended")&&!(pe!=null&&pe("replayed"))&&(G.eventBus.emit("advertisement",{action:"videoReplayed",payload:{id:ye,type:te.type}}),$e==null||$e("replayed"))},onEnd:()=>{pe!=null&&pe("ended")||(G.eventBus.emit("advertisement",{action:"videoEnd",payload:{id:ye,type:te.type}}),$e==null||$e("ended"))},controlVideo:Ye,autoPlay:Ct,playMuted:Ci,muted:dr}):(O=te.banner)!=null&&O.imageUrl?W.jsx(O0,{style:wi?{aspectRatio:"1/1"}:{},src:(B=te.banner)==null?void 0:B.imageUrl,alt:"promo"}):null}),!wi&&W.jsxs(vc,{children:[((P=te.banner)==null?void 0:P.title)&&W.jsx($0,{className:G.cx_default("AdvTitle",ki&&q0),children:($=te.banner)==null?void 0:$.title}),((Q=te.banner)==null?void 0:Q.body)&&W.jsx(M0,{className:"AdvDescription",children:(K=te.banner)==null?void 0:K.body})]})]})]}),te.buttonType===ce.PromotionButtonType.BASIC&&W.jsx(Dh,{children:W.jsx(Ph,{href:Kt,style:{backgroundColor:((me=(ie=te.banner)==null?void 0:ie.ctaButton)==null?void 0:me.color)||"#009dc4",color:((ge=(oe=te.banner)==null?void 0:oe.ctaButton)==null?void 0:ge.textColor)||"#fff"},"data-a":"button","data-promo-id":ye,"data-promo-type":te.type,target:"_blank",children:(ue=(ee=te.banner)==null?void 0:ee.ctaButton)==null?void 0:ue.label})})]})},tk=G.styled_default("div")({name:"SidebarContainer",class:"s1abskp8",propsAsIs:!1}),ik=({children:i,direction:e,style:t,className:r,hiding:n})=>W.jsx(Tl,{direction:e,style:t,hiding:n,className:r,children:W.jsx(tk,{children:i})}),yh=i=>(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB11_LBAR||(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB21_LBAR,rk=i=>(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB11_SIDEBAR||(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB21_SIDEBAR,nk=i=>(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB11||(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB21,sk=({advertisement:i,close:e,skipTypeCheck:t,skipAutoClose:r,layoutMode:n="side-by-side",sidebar:s,isNotification:a,banner:l,markAsViewed:u,open:p,externalAd:m,controlVideo:_,advertisementPaused:E,togglePause:S,isEventFired:C,fireEvent:v,muted:L})=>i.promotion?a&&i.notification?W.jsx(P0,{open:()=>p==null?void 0:p({fromNotification:!0}),notification:i.notification,promotionId:i.question.id,close:e}):!s&&!l&&(t||nk(i.promotion))?W.jsx(R0,{className:"PromoOverlayContainer",children:W.jsx(fh,{markAsViewed:u,promotionId:i.question.id,promotion:i.promotion,onClose:e,open:p,skipAutoClose:r,externalAd:m,controlVideo:_,advertisementPaused:E,togglePause:S,isEventFired:C,fireEvent:v,muted:L})}):s&&(t||yh(i.promotion)||rk(i.promotion)||m)?W.jsx(ik,{className:"PromoSidebarContainer",direction:s,hiding:!1,children:W.jsx(fh,{markAsViewed:u,promotionId:i.question.id,promotion:i.promotion,externalAd:m,onClose:e,open:p,controlVideo:_,skipAutoClose:r,advertisementPaused:E,togglePause:S,isEventFired:C,fireEvent:v,muted:L})}):l&&yh(i.promotion)?W.jsx(vh,{promotionId:i.question.id,hiding:!1,promotion:i.promotion,direction:l,isEventFired:C,fireEvent:v}):null:null,_h=G.styled_default("div")({name:"AdvertisementUIWrap",class:"aa6pjif",propsAsIs:!1}),ak=i=>{const e=i.target;if(e instanceof HTMLAnchorElement&&e.target==="_blank"){const t=e.getAttribute("data-promo-id")||"",r=e.getAttribute("data-promo-type")||ce.PromotionType.UNSET;e.getAttribute("data-a")==="button"&&G.eventBus.emit("advertisement",{action:"buttonSelect",payload:{id:t,type:r}}),e.getAttribute("data-a")==="banner"&&G.eventBus.emit("advertisement",{action:"bannerSelect",payload:{id:t,type:r}})}},ok=({gamification:i,advertisement:e,layoutMode:t,skipAutoClose:r,skipTypeCheck:n,sidebar:s,banner:a,notification:l,isMobileScreen:u,persistent:p,containerId:m,externalAd:_,controlVideo:E,muted:S})=>{var C,v,L,D,U,O,B,P,$,Q,K,ie,me,oe,ge,ee,ue,te,de,be,je;const Ye=Se.useRef(null),ve=G.useStore(e.$store),ye=G.useStore(i.openedQuestion.$store);G.b(Ye,{enabled:!!ve.data,event:"click",listener:ak});const kt=((L=(v=(C=ve.data)==null?void 0:C.question)==null?void 0:v.backgroundImage)==null?void 0:L.landscapeUrl)||((U=(D=ve.data)==null?void 0:D.promotion)==null?void 0:U.backgroundImageLandscapeUrl),Pt=((P=(B=(O=ve.data)==null?void 0:O.question)==null?void 0:B.backgroundImage)==null?void 0:P.portraitUrl)||((Q=($=ve.data)==null?void 0:$.promotion)==null?void 0:Q.backgroundImagePortraitUrl),xe=G.y$1({containerId:m,landscapeUrl:kt,portraitUrl:Pt});if(((K=ye==null?void 0:ye.attributes)==null?void 0:K.adUnit)===ce.AdUnit.STANDART&&(oe=(me=(ie=ye==null?void 0:ye.attributes)==null?void 0:ie.adPromotion)==null?void 0:me.banner)!=null&&oe.imageUrl)return a?W.jsx(_h,{ref:Ye,style:{height:"100%"},className:G.cx_default("SL-AdvertisementUIWrap",u&&"mobile-view"),children:W.jsx(q_,{cardId:ye.id,promotion:{...(ge=ye==null?void 0:ye.attributes)==null?void 0:ge.adPromotion,adUnit:(ee=ye==null?void 0:ye.attributes)==null?void 0:ee.adUnit}})}):null;const pe=!a&&!s;if(ve.data===void 0||!p&&ve.isViewed)return null;const $e=((de=(te=(ue=ve==null?void 0:ve.data)==null?void 0:ue.notification)==null?void 0:te.promotion)==null?void 0:de.mode)===ce.NotificationPromotionMode.LOWER_THIRD;return W.jsxs(_h,{ref:Ye,style:{height:pe?"auto":"100%"},className:G.cx_default("SL-AdvertisementUIWrap",u&&"mobile-view",$e&&"SL-AdvertisementUIWrap--lower-third"),children:[!l&&xe,W.jsx(sk,{skipTypeCheck:n,sidebar:s,banner:a,advertisement:ve.data,advertisementPaused:!!ve.isPaused,togglePause:ve.togglePause,isEventFired:ve.isEventFired,toggleMute:ve.toggleMute,fireEvent:ve.fireEvent,close:ve.close,externalAd:_?ve.externalAd:void 0,markAsViewed:(be=i.advertisement)==null?void 0:be.markAsViewed,open:(je=i.advertisement)==null?void 0:je.open,layoutMode:t,isNotification:l,skipAutoClose:r,controlVideo:E,muted:S})]})},ff=({sdk:i,sidebar:e,externalAd:t,banner:r,skipAutoClose:n,skipTypeCheck:s,layoutMode:a,isMobileScreen:l,persistent:u,notification:p,muted:m})=>{const _=G.useStore(i.featuresList.getStore()),[E,S]=Se.useState(!t),C=G.useStore(i.options);if(Se.useEffect(()=>{if(t){const L=document.createElement("script");L.async=!0,L.src="https://imasdk.googleapis.com/pal/sdkloader/pal.js",document.body.appendChild(L),L.onload=()=>{S(!0)}}},[t]),e&&r)return W.jsx("div",{style:{color:"red"},children:"define either sidebar or banner, not both."});if(r&&t)return W.jsx("div",{style:{color:"red"},children:"externalAd is not supported with banner"});if(!_)return null;const v=i.getFeature(ce.SdkOverlayType.GAMES);return!v||t&&!E?null:W.jsx(ok,{gamification:v,advertisement:v.advertisement,sidebar:e,banner:r,layoutMode:a,isMobileScreen:l,persistent:u,notification:p,skipTypeCheck:s,skipAutoClose:n,externalAd:t,controlVideo:i.controlVideoPlayer,containerId:C.containerId,muted:m})},lk=({event:i,sidebar:e,banner:t,isMobileScreen:r,skipAutoClose:n,persistent:s,theme:a,notification:l,skipTypeCheck:u,externalAd:p,muted:m=!1})=>{const _=G.useStreamLayer(),E=G.useStreamLayerUI(),S=G.useStreamLayerTheme();return _?p&&!E.promotionExternalAd?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):!p&&E.promotionExternalAd?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):e&&!E.promotionSidebar?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):t&&!E.promotionBanner?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):l&&!E.promotionNotification?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):!t&&!e&&!l&&!E.promotionOverlay&&!u?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):W.jsxs("div",{className:"StreamLayerSDK",children:[W.jsx(G.h,{customTheme:a??S.theme,themeMode:S.themeMode,children:W.jsx(ff,{sdk:_,sidebar:e,banner:t,isMobileScreen:r,persistent:s,notification:l,skipTypeCheck:u,skipAutoClose:n,layoutMode:"side-by-side",externalAd:p,muted:m})}),i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i})]}):null};exports.StreamLayerSDKAdvertisement=lk;exports.StreamLayerSDKAdvertisementUI=ff;
223
+ `,l++,a=E}),this.end_=a,this.storage_=n,this.diagnostics_=s}calculateBaseTime_(e,t,r){if(!this.storage_.size)return 0;if(this.storage_.has(e))return this.storage_.get(e).segmentSyncInfo.start;const n=Math.min(...this.storage_.keys());if(e<n){const s=n-e;let a=this.storage_.get(n).segmentSyncInfo.start;for(let l=0;l<s;l++){const u=t[l];a-=u.duration}return a}return r}isReliablePlaylist_(e,t){return e!=null&&Array.isArray(t)&&t.length}}class dh extends tf{constructor(e){super(),this.parent_=e}calculateBaseTime_(e,t,r){if(!this.storage_.size){const n=this.parent_.getSyncInfoForMediaSequence(e);return n?n.segmentSyncInfo.start:0}return super.calculateBaseTime_(e,t,r)}}const d2=86400,Vo=[{name:"VOD",run:(i,e,t,r,n)=>t!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(i,e,t,r,n,s)=>{const a=i.getMediaSequenceSync(s);if(!a||!a.isReliable)return null;const l=a.getSyncInfoForTime(n);return l?{time:l.start,partIndex:l.partIndex,segmentIndex:l.segmentIndex}:null}},{name:"ProgramDateTime",run:(i,e,t,r,n)=>{if(!Object.keys(i.timelineToDatetimeMappings).length)return null;let s=null,a=null;const l=ul(e);n=n||0;for(let u=0;u<l.length;u++){const p=e.endList||n===0?u:l.length-(u+1),m=l[p],_=m.segment,E=i.timelineToDatetimeMappings[_.timeline];if(!E||!_.dateTimeObject)continue;let S=_.dateTimeObject.getTime()/1e3+E;if(_.parts&&typeof m.partIndex=="number")for(let v=0;v<m.partIndex;v++)S+=_.parts[v].duration;const C=Math.abs(n-S);if(a!==null&&(C===0||a<C))break;a=C,s={time:S,segmentIndex:m.segmentIndex,partIndex:m.partIndex}}return s}},{name:"Segment",run:(i,e,t,r,n)=>{let s=null,a=null;n=n||0;const l=ul(e);for(let u=0;u<l.length;u++){const p=e.endList||n===0?u:l.length-(u+1),m=l[p],_=m.segment,E=m.part&&m.part.start||_&&_.start;if(_.timeline===r&&typeof E<"u"){const S=Math.abs(n-E);if(a!==null&&a<S)break;(!s||a===null||a>=S)&&(a=S,s={time:E,segmentIndex:m.segmentIndex,partIndex:m.partIndex})}}return s}},{name:"Discontinuity",run:(i,e,t,r,n)=>{let s=null;if(n=n||0,e.discontinuityStarts&&e.discontinuityStarts.length){let a=null;for(let l=0;l<e.discontinuityStarts.length;l++){const u=e.discontinuityStarts[l],p=e.discontinuitySequence+l+1,m=i.discontinuities[p];if(m){const _=Math.abs(n-m.time);if(a!==null&&a<_)break;(!s||a===null||a>=_)&&(a=_,s={time:m.time,segmentIndex:u,partIndex:null})}}}return s}},{name:"Playlist",run:(i,e,t,r,n)=>e.syncInfo?{time:e.syncInfo.time,segmentIndex:e.syncInfo.mediaSequence-e.mediaSequence,partIndex:null}:null}];class h2 extends F.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new tf,r=new dh(t),n=new dh(t);this.mediaSequenceStorage_={main:t,audio:r,vtt:n},this.logger_=jt("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,r,n,s){if(t!==1/0)return Vo.find(({name:l})=>l==="VOD").run(this,e,t);const a=this.runStrategies_(e,t,r,n,s);if(!a.length)return null;for(const l of a){const{syncPoint:u,strategy:p}=l,{segmentIndex:m,time:_}=u;if(m<0)continue;const E=e.segments[m],S=_,C=S+E.duration;if(this.logger_(`Strategy: ${p}. Current time: ${n}. selected segment: ${m}. Time: [${S} -> ${C}]}`),n>=S&&n<C)return this.logger_("Found sync point with exact match: ",u),u}return this.selectSyncPoint_(a,{key:"time",value:n})}getExpiredTime(e,t){if(!e||!e.segments)return null;const r=this.runStrategies_(e,t,e.discontinuitySequence,0);if(!r.length)return null;const n=this.selectSyncPoint_(r,{key:"segmentIndex",value:0});return n.segmentIndex>0&&(n.time*=-1),Math.abs(n.time+jn({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:n.segmentIndex,endIndex:0}))}runStrategies_(e,t,r,n,s){const a=[];for(let l=0;l<Vo.length;l++){const u=Vo[l],p=u.run(this,e,t,r,n,s);p&&(p.strategy=u.name,a.push({strategy:u.name,syncPoint:p}))}return a}selectSyncPoint_(e,t){let r=e[0].syncPoint,n=Math.abs(e[0].syncPoint[t.key]-t.value),s=e[0].strategy;for(let a=1;a<e.length;a++){const l=Math.abs(e[a].syncPoint[t.key]-t.value);l<n&&(n=l,r=e[a].syncPoint,s=e[a].strategy)}return this.logger_(`syncPoint for [${t.key}: ${t.value}] chosen with strategy [${s}]: [time:${r.time}, segmentIndex:${r.segmentIndex}`+(typeof r.partIndex=="number"?`,partIndex:${r.partIndex}`:"")+"]"),r}saveExpiredSegmentInfo(e,t){const r=t.mediaSequence-e.mediaSequence;if(r>d2){F.log.warn(`Not saving expired segment info. Media sequence gap ${r} is too large.`);return}for(let n=r-1;n>=0;n--){const s=e.segments[n];if(s&&typeof s.start<"u"){t.syncInfo={mediaSequence:e.mediaSequence+n,time:s.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){const t=e.segments[0],r=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-r}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){const r=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),n=e.segment;r&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:n.start}));const s=n.dateTimeObject;n.discontinuity&&t&&s&&(this.timelineToDatetimeMappings[n.timeline]=-(s.getTime()/1e3))}timestampOffsetForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].time}mappingForTimeline(e){return typeof this.timelines[e]>"u"?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,r){const n=e.segment,s=e.part;let a=this.timelines[e.timeline],l,u;if(typeof e.timestampOffset=="number")a={time:e.startOfSegment,mapping:e.startOfSegment-t.start},r&&(this.timelines[e.timeline]=a,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${a.time}] [mapping: ${a.mapping}]`)),l=e.startOfSegment,u=t.end+a.mapping;else if(a)l=t.start+a.mapping,u=t.end+a.mapping;else return!1;return s&&(s.start=l,s.end=u),(!n.start||l<n.start)&&(n.start=l),n.end=u,!0}saveDiscontinuitySyncInfo_(e){const t=e.playlist,r=e.segment;if(r.discontinuity)this.discontinuities[r.timeline]={time:r.start,accuracy:0};else if(t.discontinuityStarts&&t.discontinuityStarts.length)for(let n=0;n<t.discontinuityStarts.length;n++){const s=t.discontinuityStarts[n],a=t.discontinuitySequence+n+1,l=s-e.mediaIndex,u=Math.abs(l);if(!this.discontinuities[a]||this.discontinuities[a].accuracy>u){let p;l<0?p=r.start-jn({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:s}):p=r.end+jn({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:s}),this.discontinuities[a]={time:p,accuracy:u}}}}dispose(){this.trigger("dispose"),this.off()}}class p2 extends F.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange({type:e,from:t,to:r}){return typeof t=="number"&&typeof r=="number"&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:r},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:r}){if(typeof t=="number"&&typeof r=="number"){this.lastTimelineChanges_[e]={type:e,from:t,to:r},delete this.pendingTimelineChanges_[e];const n={timelineChangeInfo:{from:t,to:r}};this.trigger({type:"timelinechange",metadata:n})}return this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const m2=Fg(jg(function(){var i=function(){function v(){this.listeners={}}var L=v.prototype;return L.on=function(D,U){this.listeners[D]||(this.listeners[D]=[]),this.listeners[D].push(U)},L.off=function(D,U){if(!this.listeners[D])return!1;var O=this.listeners[D].indexOf(U);return this.listeners[D]=this.listeners[D].slice(0),this.listeners[D].splice(O,1),O>-1},L.trigger=function(D){var U=this.listeners[D];if(U)if(arguments.length===2)for(var O=U.length,B=0;B<O;++B)U[B].call(this,arguments[1]);else for(var P=Array.prototype.slice.call(arguments,1),$=U.length,Q=0;Q<$;++Q)U[Q].apply(this,P)},L.dispose=function(){this.listeners={}},L.pipe=function(D){this.on("data",function(U){D.push(U)})},v}();/*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */function e(v){return v.subarray(0,v.byteLength-v[v.byteLength-1])}/*! @name aes-decrypter @version 4.0.2 @license Apache-2.0 */const t=function(){const v=[[[],[],[],[],[]],[[],[],[],[],[]]],L=v[0],D=v[1],U=L[4],O=D[4];let B,P,$;const Q=[],K=[];let ie,me,oe,ge,ee,ue;for(B=0;B<256;B++)K[(Q[B]=B<<1^(B>>7)*283)^B]=B;for(P=$=0;!U[P];P^=ie||1,$=K[$]||1)for(ge=$^$<<1^$<<2^$<<3^$<<4,ge=ge>>8^ge&255^99,U[P]=ge,O[ge]=P,oe=Q[me=Q[ie=Q[P]]],ue=oe*16843009^me*65537^ie*257^P*16843008,ee=Q[ge]*257^ge*16843008,B=0;B<4;B++)L[B][P]=ee=ee<<24^ee>>>8,D[B][ge]=ue=ue<<24^ue>>>8;for(B=0;B<5;B++)L[B]=L[B].slice(0),D[B]=D[B].slice(0);return v};let r=null;class n{constructor(L){r||(r=t()),this._tables=[[r[0][0].slice(),r[0][1].slice(),r[0][2].slice(),r[0][3].slice(),r[0][4].slice()],[r[1][0].slice(),r[1][1].slice(),r[1][2].slice(),r[1][3].slice(),r[1][4].slice()]];let D,U,O;const B=this._tables[0][4],P=this._tables[1],$=L.length;let Q=1;if($!==4&&$!==6&&$!==8)throw new Error("Invalid aes key size");const K=L.slice(0),ie=[];for(this._key=[K,ie],D=$;D<4*$+28;D++)O=K[D-1],(D%$===0||$===8&&D%$===4)&&(O=B[O>>>24]<<24^B[O>>16&255]<<16^B[O>>8&255]<<8^B[O&255],D%$===0&&(O=O<<8^O>>>24^Q<<24,Q=Q<<1^(Q>>7)*283)),K[D]=K[D-$]^O;for(U=0;D;U++,D--)O=K[U&3?D:D-4],D<=4||U<4?ie[U]=O:ie[U]=P[0][B[O>>>24]]^P[1][B[O>>16&255]]^P[2][B[O>>8&255]]^P[3][B[O&255]]}decrypt(L,D,U,O,B,P){const $=this._key[1];let Q=L^$[0],K=O^$[1],ie=U^$[2],me=D^$[3],oe,ge,ee;const ue=$.length/4-2;let te,de=4;const be=this._tables[1],je=be[0],Ye=be[1],ve=be[2],ye=be[3],kt=be[4];for(te=0;te<ue;te++)oe=je[Q>>>24]^Ye[K>>16&255]^ve[ie>>8&255]^ye[me&255]^$[de],ge=je[K>>>24]^Ye[ie>>16&255]^ve[me>>8&255]^ye[Q&255]^$[de+1],ee=je[ie>>>24]^Ye[me>>16&255]^ve[Q>>8&255]^ye[K&255]^$[de+2],me=je[me>>>24]^Ye[Q>>16&255]^ve[K>>8&255]^ye[ie&255]^$[de+3],de+=4,Q=oe,K=ge,ie=ee;for(te=0;te<4;te++)B[(3&-te)+P]=kt[Q>>>24]<<24^kt[K>>16&255]<<16^kt[ie>>8&255]<<8^kt[me&255]^$[de++],oe=Q,Q=K,K=ie,ie=me,me=oe}}class s extends i{constructor(){super(i),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(L){this.jobs.push(L),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const a=function(v){return v<<24|(v&65280)<<8|(v&16711680)>>8|v>>>24},l=function(v,L,D){const U=new Int32Array(v.buffer,v.byteOffset,v.byteLength>>2),O=new n(Array.prototype.slice.call(L)),B=new Uint8Array(v.byteLength),P=new Int32Array(B.buffer);let $,Q,K,ie,me,oe,ge,ee,ue;for($=D[0],Q=D[1],K=D[2],ie=D[3],ue=0;ue<U.length;ue+=4)me=a(U[ue]),oe=a(U[ue+1]),ge=a(U[ue+2]),ee=a(U[ue+3]),O.decrypt(me,oe,ge,ee,P,ue),P[ue]=a(P[ue]^$),P[ue+1]=a(P[ue+1]^Q),P[ue+2]=a(P[ue+2]^K),P[ue+3]=a(P[ue+3]^ie),$=me,Q=oe,K=ge,ie=ee;return B};class u{constructor(L,D,U,O){const B=u.STEP,P=new Int32Array(L.buffer),$=new Uint8Array(L.byteLength);let Q=0;for(this.asyncStream_=new s,this.asyncStream_.push(this.decryptChunk_(P.subarray(Q,Q+B),D,U,$)),Q=B;Q<P.length;Q+=B)U=new Uint32Array([a(P[Q-4]),a(P[Q-3]),a(P[Q-2]),a(P[Q-1])]),this.asyncStream_.push(this.decryptChunk_(P.subarray(Q,Q+B),D,U,$));this.asyncStream_.push(function(){O(null,e($))})}static get STEP(){return 32e3}decryptChunk_(L,D,U,O){return function(){const B=l(L,D,U);O.set(B,L.byteOffset)}}}var p=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Zs<"u"?Zs:typeof self<"u"?self:{},m;typeof window<"u"?m=window:typeof p<"u"?m=p:typeof self<"u"?m=self:m={};var _=m,E=function(v){return ArrayBuffer.isView==="function"?ArrayBuffer.isView(v):v&&v.buffer instanceof ArrayBuffer},S=_.BigInt||Number;S("0x1"),S("0x100"),S("0x10000"),S("0x1000000"),S("0x100000000"),S("0x10000000000"),S("0x1000000000000"),S("0x100000000000000"),S("0x10000000000000000"),function(){var v=new Uint16Array([65484]),L=new Uint8Array(v.buffer,v.byteOffset,v.byteLength);return L[0]===255?"big":L[0]===204?"little":"unknown"}();const C=function(v){const L={};return Object.keys(v).forEach(D=>{const U=v[D];E(U)?L[D]={bytes:U.buffer,byteOffset:U.byteOffset,byteLength:U.byteLength}:L[D]=U}),L};self.onmessage=function(v){const L=v.data,D=new Uint8Array(L.encrypted.bytes,L.encrypted.byteOffset,L.encrypted.byteLength),U=new Uint32Array(L.key.bytes,L.key.byteOffset,L.key.byteLength/4),O=new Uint32Array(L.iv.bytes,L.iv.byteOffset,L.iv.byteLength/4);new u(D,U,O,function(B,P){self.postMessage(C({source:L.source,decrypted:P}),[P.buffer])})}}));var g2=Bg(m2);const f2=i=>{let e=i.default?"main":"alternative";return i.characteristics&&i.characteristics.indexOf("public.accessibility.describes-video")>=0&&(e="main-desc"),e},rf=(i,e)=>{i.abort(),i.pause(),e&&e.activePlaylistLoader&&(e.activePlaylistLoader.pause(),e.activePlaylistLoader=null)},vl=(i,e)=>{e.activePlaylistLoader=i,i.load()},y2=(i,e)=>()=>{const{segmentLoaders:{[i]:t,main:r},mediaTypes:{[i]:n}}=e,s=n.activeTrack(),a=n.getActiveGroup(),l=n.activePlaylistLoader,u=n.lastGroup_;if(!(a&&u&&a.id===u.id)&&(n.lastGroup_=a,n.lastTrack_=s,rf(t,n),!(!a||a.isMainPlaylist))){if(!a.playlistLoader){l&&r.resetEverything();return}t.resyncLoader(),vl(a.playlistLoader,n)}},_2=(i,e)=>()=>{const{segmentLoaders:{[i]:t},mediaTypes:{[i]:r}}=e;r.lastGroup_=null,t.abort(),t.pause()},b2=(i,e)=>()=>{const{mainPlaylistLoader:t,segmentLoaders:{[i]:r,main:n},mediaTypes:{[i]:s}}=e,a=s.activeTrack(),l=s.getActiveGroup(),u=s.activePlaylistLoader,p=s.lastTrack_;if(!(p&&a&&p.id===a.id)&&(s.lastGroup_=l,s.lastTrack_=a,rf(r,s),!!l)){if(l.isMainPlaylist){if(!a||!p||a.id===p.id)return;const m=e.vhs.playlistController_,_=m.selectPlaylist();if(m.media()===_)return;s.logger_(`track change. Switching main audio from ${p.id} to ${a.id}`),t.pause(),n.resetEverything(),m.fastQualityChange_(_);return}if(i==="AUDIO"){if(!l.playlistLoader){n.setAudio(!0),n.resetEverything();return}r.setAudio(!0),n.setAudio(!1)}if(u===l.playlistLoader){vl(l.playlistLoader,s);return}r.track&&r.track(a),r.resetEverything(),vl(l.playlistLoader,s)}},Ta={AUDIO:(i,e)=>()=>{const{mediaTypes:{[i]:t},excludePlaylist:r}=e,n=t.activeTrack(),s=t.activeGroup(),a=(s.filter(u=>u.default)[0]||s[0]).id,l=t.tracks[a];if(n===l){r({error:{message:"Problem encountered loading the default audio track."}});return}F.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const u in t.tracks)t.tracks[u].enabled=t.tracks[u]===l;t.onTrackChanged()},SUBTITLES:(i,e)=>()=>{const{mediaTypes:{[i]:t}}=e;F.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const r=t.activeTrack();r&&(r.mode="disabled"),t.onTrackChanged()}},hh={AUDIO:(i,e,t)=>{if(!e)return;const{tech:r,requestOptions:n,segmentLoaders:{[i]:s}}=t;e.on("loadedmetadata",()=>{const a=e.media();s.playlist(a,n),(!r.paused()||a.endList&&r.preload()!=="none")&&s.load()}),e.on("loadedplaylist",()=>{s.playlist(e.media(),n),r.paused()||s.load()}),e.on("error",Ta[i](i,t))},SUBTITLES:(i,e,t)=>{const{tech:r,requestOptions:n,segmentLoaders:{[i]:s},mediaTypes:{[i]:a}}=t;e.on("loadedmetadata",()=>{const l=e.media();s.playlist(l,n),s.track(a.activeTrack()),(!r.paused()||l.endList&&r.preload()!=="none")&&s.load()}),e.on("loadedplaylist",()=>{s.playlist(e.media(),n),r.paused()||s.load()}),e.on("error",Ta[i](i,t))}},v2={AUDIO:(i,e)=>{const{vhs:t,sourceType:r,segmentLoaders:{[i]:n},requestOptions:s,main:{mediaGroups:a},mediaTypes:{[i]:{groups:l,tracks:u,logger_:p}},mainPlaylistLoader:m}=e,_=as(m.main);(!a[i]||Object.keys(a[i]).length===0)&&(a[i]={main:{default:{default:!0}}},_&&(a[i].main.default.playlists=m.main.playlists));for(const E in a[i]){l[E]||(l[E]=[]);for(const S in a[i][E]){let C=a[i][E][S],v;if(_?(p(`AUDIO group '${E}' label '${S}' is a main playlist`),C.isMainPlaylist=!0,v=null):r==="vhs-json"&&C.playlists?v=new Ar(C.playlists[0],t,s):C.resolvedUri?v=new Ar(C.resolvedUri,t,s):C.playlists&&r==="dash"?v=new gl(C.playlists[0],t,s,m):v=null,C=_e({id:S,playlistLoader:v},C),hh[i](i,C.playlistLoader,e),l[E].push(C),typeof u[S]>"u"){const L=new F.AudioTrack({id:S,kind:f2(C),enabled:!1,language:C.language,default:C.default,label:S});u[S]=L}}}n.on("error",Ta[i](i,e))},SUBTITLES:(i,e)=>{const{tech:t,vhs:r,sourceType:n,segmentLoaders:{[i]:s},requestOptions:a,main:{mediaGroups:l},mediaTypes:{[i]:{groups:u,tracks:p}},mainPlaylistLoader:m}=e;for(const _ in l[i]){u[_]||(u[_]=[]);for(const E in l[i][_]){if(!r.options_.useForcedSubtitles&&l[i][_][E].forced)continue;let S=l[i][_][E],C;if(n==="hls")C=new Ar(S.resolvedUri,r,a);else if(n==="dash"){if(!S.playlists.filter(v=>v.excludeUntil!==1/0).length)return;C=new gl(S.playlists[0],r,a,m)}else n==="vhs-json"&&(C=new Ar(S.playlists?S.playlists[0]:S.resolvedUri,r,a));if(S=_e({id:E,playlistLoader:C},S),hh[i](i,S.playlistLoader,e),u[_].push(S),typeof p[E]>"u"){const v=t.addRemoteTextTrack({id:E,kind:"subtitles",default:S.default&&S.autoselect,language:S.language,label:E},!1).track;p[E]=v}}}s.on("error",Ta[i](i,e))},"CLOSED-CAPTIONS":(i,e)=>{const{tech:t,main:{mediaGroups:r},mediaTypes:{[i]:{groups:n,tracks:s}}}=e;for(const a in r[i]){n[a]||(n[a]=[]);for(const l in r[i][a]){const u=r[i][a][l];if(!/^(?:CC|SERVICE)/.test(u.instreamId))continue;const p=t.options_.vhs&&t.options_.vhs.captionServices||{};let m={label:l,language:u.language,instreamId:u.instreamId,default:u.default&&u.autoselect};if(p[m.instreamId]&&(m=_e(m,p[m.instreamId])),m.default===void 0&&delete m.default,n[a].push(_e({id:l},u)),typeof s[l]>"u"){const _=t.addRemoteTextTrack({id:m.instreamId,kind:"captions",default:m.default,language:m.language,label:m.label},!1).track;s[l]=_}}}}},nf=(i,e)=>{for(let t=0;t<i.length;t++)if(ku(e,i[t])||i[t].playlists&&nf(i[t].playlists,e))return!0;return!1},T2=(i,e)=>t=>{const{mainPlaylistLoader:r,mediaTypes:{[i]:{groups:n}}}=e,s=r.media();if(!s)return null;let a=null;s.attributes[i]&&(a=n[s.attributes[i]]);const l=Object.keys(n);if(!a)if(i==="AUDIO"&&l.length>1&&as(e.main))for(let u=0;u<l.length;u++){const p=n[l[u]];if(nf(p,s)){a=p;break}}else n.main?a=n.main:l.length===1&&(a=n[l[0]]);return typeof t>"u"?a:t===null||!a?null:a.filter(u=>u.id===t.id)[0]||null},S2={AUDIO:(i,e)=>()=>{const{mediaTypes:{[i]:{tracks:t}}}=e;for(const r in t)if(t[r].enabled)return t[r];return null},SUBTITLES:(i,e)=>()=>{const{mediaTypes:{[i]:{tracks:t}}}=e;for(const r in t)if(t[r].mode==="showing"||t[r].mode==="hidden")return t[r];return null}},E2=(i,{mediaTypes:e})=>()=>{const t=e[i].activeTrack();return t?e[i].activeGroup(t):null},w2=i=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(p=>{v2[p](p,i)});const{mediaTypes:e,mainPlaylistLoader:t,tech:r,vhs:n,segmentLoaders:{["AUDIO"]:s,main:a}}=i;["AUDIO","SUBTITLES"].forEach(p=>{e[p].activeGroup=T2(p,i),e[p].activeTrack=S2[p](p,i),e[p].onGroupChanged=y2(p,i),e[p].onGroupChanging=_2(p,i),e[p].onTrackChanged=b2(p,i),e[p].getActiveGroup=E2(p,i)});const l=e.AUDIO.activeGroup();if(l){const p=(l.filter(m=>m.default)[0]||l[0]).id;e.AUDIO.tracks[p].enabled=!0,e.AUDIO.onGroupChanged(),e.AUDIO.onTrackChanged(),e.AUDIO.getActiveGroup().playlistLoader?(a.setAudio(!1),s.setAudio(!0)):a.setAudio(!0)}t.on("mediachange",()=>{["AUDIO","SUBTITLES"].forEach(p=>e[p].onGroupChanged())}),t.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(p=>e[p].onGroupChanging())});const u=()=>{e.AUDIO.onTrackChanged(),r.trigger({type:"usage",name:"vhs-audio-change"})};r.audioTracks().addEventListener("change",u),r.remoteTextTracks().addEventListener("change",e.SUBTITLES.onTrackChanged),n.on("dispose",()=>{r.audioTracks().removeEventListener("change",u),r.remoteTextTracks().removeEventListener("change",e.SUBTITLES.onTrackChanged)}),r.clearTracks("audio");for(const p in e.AUDIO.tracks)r.audioTracks().addTrack(e.AUDIO.tracks[p])},k2=()=>{const i={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{i[e]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:fi,activeTrack:fi,getActiveGroup:fi,onGroupChanged:fi,onTrackChanged:fi,lastTrack_:null,logger_:jt(`MediaGroups[${e}]`)}}),i};class ph{constructor(){this.priority_=[],this.pathwayClones_=new Map}set version(e){e===1&&(this.version_=e)}set ttl(e){this.ttl_=e||300}set reloadUri(e){e&&(this.reloadUri_=vt(this.reloadUri_,e))}set priority(e){e&&e.length&&(this.priority_=e)}set pathwayClones(e){e&&e.length&&(this.pathwayClones_=new Map(e.map(t=>[t.ID,t])))}get version(){return this.version_}get ttl(){return this.ttl_}get reloadUri(){return this.reloadUri_}get priority(){return this.priority_}get pathwayClones(){return this.pathwayClones_}}class C2 extends F.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new ph,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=jt("Content Steering"),this.xhr_=e,this.getBandwidth_=t}assignTagProperties(e,t){this.manifestType_=t.serverUri?"HLS":"DASH";const r=t.serverUri||t.serverURL;if(!r){this.logger_(`steering manifest URL is ${r}, cannot request steering manifest.`),this.trigger("error");return}if(r.startsWith("data:")){this.decodeDataUriManifest_(r.substring(r.indexOf(",")+1));return}this.steeringManifest.reloadUri=vt(e,r),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering")}requestSteeringManifest(e){const t=this.steeringManifest.reloadUri;if(!t)return;const r=e?t:this.getRequestURI(t);if(!r){this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),this.dispose();return}const n={contentSteeringInfo:{uri:r}};this.trigger({type:"contentsteeringloadstart",metadata:n}),this.request_=this.xhr_({uri:r,requestType:"content-steering-manifest"},(s,a)=>{if(s){if(a.status===410){this.logger_(`manifest request 410 ${s}.`),this.logger_(`There will be no more content steering requests to ${r} this session.`),this.excludedSteeringManifestURLs.add(r);return}if(a.status===429){const p=a.responseHeaders["retry-after"];this.logger_(`manifest request 429 ${s}.`),this.logger_(`content steering will retry in ${p} seconds.`),this.startTTLTimeout_(parseInt(p,10));return}this.logger_(`manifest failed to load ${s}.`),this.startTTLTimeout_();return}this.trigger({type:"contentsteeringloadcomplete",metadata:n});let l;try{l=JSON.parse(this.request_.responseText)}catch(p){const m={errorType:F.Error.StreamingContentSteeringParserError,error:p};this.trigger({type:"error",metadata:m})}this.assignSteeringProperties_(l);const u={contentSteeringInfo:n.contentSteeringInfo,contentSteeringManifest:{version:this.steeringManifest.version,reloadUri:this.steeringManifest.reloadUri,priority:this.steeringManifest.priority}};this.trigger({type:"contentsteeringparsed",metadata:u}),this.startTTLTimeout_()})}setProxyServerUrl_(e){const t=new x.URL(e),r=new x.URL(this.proxyServerUrl_);return r.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(r.toString())}decodeDataUriManifest_(e){const t=JSON.parse(x.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new x.URL(e),r=this.getPathway(),n=this.getBandwidth_();if(r){const s=`_${this.manifestType_}_pathway`;t.searchParams.set(s,r)}if(n){const s=`_${this.manifestType_}_throughput`;t.searchParams.set(s,n)}return t.toString()}assignSteeringProperties_(e){if(this.steeringManifest.version=e.VERSION,!this.steeringManifest.version){this.logger_(`manifest version is ${e.VERSION}, which is not supported.`),this.trigger("error");return}this.steeringManifest.ttl=e.TTL,this.steeringManifest.reloadUri=e["RELOAD-URI"],this.steeringManifest.priority=e["PATHWAY-PRIORITY"]||e["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=e["PATHWAY-CLONES"],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_("There are no available pathways for content steering. Ending content steering."),this.trigger("error"),this.dispose());const t=(r=>{for(const n of r)if(this.availablePathways_.has(n))return n;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==t&&(this.currentPathway=t,this.trigger("content-steering"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(e){if(!e)return null;const t=n=>this.excludedSteeringManifestURLs.has(n);if(this.proxyServerUrl_){const n=this.setProxyServerUrl_(e);if(!t(n))return n}const r=this.setSteeringParams_(e);return t(r)?null:r}startTTLTimeout_(e=this.steeringManifest.ttl){const t=e*1e3;this.ttlTimeout_=x.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){x.clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off("content-steering"),this.off("error"),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new ph}addAvailablePathway(e){e&&this.availablePathways_.add(e)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(e){return this.availablePathways_.delete(e)}didDASHTagChange(e,t){return!t&&this.steeringManifest.reloadUri||t&&(vt(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}}const I2=(i,e)=>{let t=null;return(...r)=>{clearTimeout(t),t=setTimeout(()=>{i.apply(null,r)},e)}},A2=10;let Oi;const x2=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],L2=function(i){return this.audioSegmentLoader_[i]+this.mainSegmentLoader_[i]},D2=function({currentPlaylist:i,buffered:e,currentTime:t,nextPlaylist:r,bufferLowWaterLine:n,bufferHighWaterLine:s,duration:a,bufferBasedABR:l,log:u}){if(!r)return F.log.warn("We received no playlist to switch to. Please check your stream."),!1;const p=`allowing switch ${i&&i.id||"null"} -> ${r.id}`;if(!i)return u(`${p} as current playlist is not set`),!0;if(r.id===i.id)return!1;const m=!!Ir(e,t).length;if(!i.endList)return!m&&typeof i.partTargetDuration=="number"?(u(`not ${p} as current playlist is live llhls, but currentTime isn't in buffered.`),!1):(u(`${p} as current playlist is live`),!0);const _=Su(e,t),E=l?Je.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:Je.MAX_BUFFER_LOW_WATER_LINE;if(a<E)return u(`${p} as duration < max low water line (${a} < ${E})`),!0;const S=r.attributes.BANDWIDTH,C=i.attributes.BANDWIDTH;if(S<C&&(!l||_<s)){let v=`${p} as next bandwidth < current bandwidth (${S} < ${C})`;return l&&(v+=` and forwardBuffer < bufferHighWaterLine (${_} < ${s})`),u(v),!0}if((!l||S>C)&&_>=n){let v=`${p} as forwardBuffer >= bufferLowWaterLine (${_} >= ${n})`;return l&&(v+=` and next bandwidth > current bandwidth (${S} > ${C})`),u(v),!0}return u(`not ${p} as no switching criteria met`),!1};class P2 extends F.EventTarget{constructor(e){super(),this.fastQualityChange_=I2(this.fastQualityChange_.bind(this),100);const{src:t,withCredentials:r,tech:n,bandwidth:s,externVhs:a,useCueTags:l,playlistExclusionDuration:u,enableLowInitialPlaylist:p,sourceType:m,cacheEncryptionKeys:_,bufferBasedABR:E,leastPixelDiffSelector:S,captionServices:C,experimentalUseMMS:v}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:L}=e;(L===null||typeof L>"u")&&(L=1/0),Oi=a,this.bufferBasedABR=!!E,this.leastPixelDiffSelector=!!S,this.withCredentials=r,this.tech_=n,this.vhs_=n.vhs,this.player_=e.player_,this.sourceType_=m,this.useCueTags_=l,this.playlistExclusionDuration=u,this.maxPlaylistRetries=L,this.enableLowInitialPlaylist=p,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:r,maxPlaylistRetries:L,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=k2(),v&&x.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new x.ManagedMediaSource,this.usingManagedMediaSource_=!0,F.log("Using ManagedMediaSource")):x.MediaSource&&(this.mediaSource=new x.MediaSource),this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.load=this.load.bind(this),this.pause=this.pause.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.mediaSource.addEventListener("startstreaming",this.load),this.mediaSource.addEventListener("endstreaming",this.pause),this.seekable_=at(),this.hasPlayed_=!1,this.syncController_=new h2(e),this.segmentMetadataTrack_=n.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.decrypter_=new g2,this.sourceUpdater_=new ef(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new p2,this.keyStatusMap_=new Map;const D={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:C,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:s,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:_,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_=this.sourceType_==="dash"?new gl(t,this.vhs_,_e(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new Ar(t,this.vhs_,_e(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new _l(_e(D,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new _l(_e(D,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new o2(_e(D,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((B,P)=>{function $(){n.off("vttjserror",Q),B()}function Q(){n.off("vttjsloaded",$),P()}n.one("vttjsloaded",$),n.one("vttjserror",Q),n.addWebVttScript_()})}),e);const U=()=>this.mainSegmentLoader_.bandwidth;this.contentSteeringController_=new C2(this.vhs_.xhr,U),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_())),x2.forEach(B=>{this[B+"_"]=L2.bind(this,B)}),this.logger_=jt("pc"),this.triggeredFmp4Usage=!1,this.tech_.preload()==="none"?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;const O=this.tech_.preload()==="none"?"play":"loadstart";this.tech_.one(O,()=>{const B=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-B,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return e===-1||t===-1?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e="abr"){const t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,r){const n=this.media(),s=n&&(n.id||n.uri),a=e&&(e.id||e.uri);if(s&&s!==a){this.logger_(`switch media ${s} -> ${a} from ${t}`);const l={renditionInfo:{id:a,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:"renditionselected",metadata:l}),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,r)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{const t=this.mediaTypes_[e],r=t?t.activeGroup():null,n=this.contentSteeringController_.getPathway();if(r&&n){const s=(r.length?r[0].playlists:r.playlists).filter(a=>a.attributes.serviceLocation===n);s.length&&this.mediaTypes_[e].activePlaylistLoader.media(s[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=x.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(x.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const e=this.main(),t=e&&e.playlists||[];if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return t;const r=e.mediaGroups.AUDIO,n=Object.keys(r);let s;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)s=this.mediaTypes_.AUDIO.activeTrack();else{const l=r.main||n.length&&r[n[0]];for(const u in l)if(l[u].default){s={label:u};break}}if(!s)return t;const a=[];for(const l in r)if(r[l][s.label]){const u=r[l][s.label];if(u.playlists&&u.playlists.length)a.push.apply(a,u.playlists);else if(u.uri)a.push(u);else if(e.playlists.length)for(let p=0;p<e.playlists.length;p++){const m=e.playlists[p];m.attributes&&m.attributes.AUDIO&&m.attributes.AUDIO===l&&a.push(m)}}return a.length?a:t}setupMainPlaylistLoaderListeners_(){this.mainPlaylistLoader_.on("loadedmetadata",()=>{const e=this.mainPlaylistLoader_.media(),t=e.targetDuration*1.5*1e3;cl(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,e.endList&&this.tech_.preload()!=="none"&&(this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.mainSegmentLoader_.load()),w2({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),e),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger("selectedinitialmedia"):this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",()=>{this.trigger("selectedinitialmedia")})}),this.mainPlaylistLoader_.on("loadedplaylist",()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let e=this.mainPlaylistLoader_.media();if(!e){this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_();let t;if(this.enableLowInitialPlaylist&&(t=this.selectInitialPlaylist()),t||(t=this.selectPlaylist()),!t||!this.shouldSwitchToMedia_(t)||(this.initialMedia_=t,this.switchMedia_(this.initialMedia_,"initial"),!(this.sourceType_==="vhs-json"&&this.initialMedia_.segments)))return;e=this.initialMedia_}this.handleUpdatedMediaPlaylist(e)}),this.mainPlaylistLoader_.on("error",()=>{const e=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:e.playlist,error:e})}),this.mainPlaylistLoader_.on("mediachanging",()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()}),this.mainPlaylistLoader_.on("mediachange",()=>{const e=this.mainPlaylistLoader_.media(),t=e.targetDuration*1.5*1e3;cl(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,this.sourceType_==="dash"&&this.mainPlaylistLoader_.isPaused&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})}),this.mainPlaylistLoader_.on("playlistunchanged",()=>{const e=this.mainPlaylistLoader_.media();e.lastExcludeReason_!=="playlist-unchanged"&&this.stuckAtPlaylistEnd_(e)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))}),this.mainPlaylistLoader_.on("renditiondisabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})}),this.mainPlaylistLoader_.on("renditionenabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-enabled"})}),["manifestrequeststart","manifestrequestcomplete","manifestparsestart","manifestparsecomplete","playlistrequeststart","playlistrequestcomplete","playlistparsestart","playlistparsecomplete","renditiondisabled","renditionenabled"].forEach(e=>{this.mainPlaylistLoader_.on(e,t=>{this.player_.trigger(Ge({},t))})})}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!e.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){const r=e.mediaGroups||{};let n=!0;const s=Object.keys(r.AUDIO);for(const a in r.AUDIO)for(const l in r.AUDIO[a])r.AUDIO[a][l].uri||(n=!1);n&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(r.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),Oi.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),s.length&&Object.keys(r.AUDIO[s[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(e){const t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,r=this.tech_.currentTime(),n=this.bufferLowWaterLine(),s=this.bufferHighWaterLine(),a=this.tech_.buffered();return D2({buffered:a,currentTime:r,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:n,bufferHighWaterLine:s,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")}),this.mainSegmentLoader_.on("timeout",()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()}),this.bufferBasedABR||this.mainSegmentLoader_.on("progress",()=>{this.trigger("progress")}),this.mainSegmentLoader_.on("error",()=>{const t=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:t.playlist,error:t})}),this.mainSegmentLoader_.on("appenderror",()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.mainSegmentLoader_.on("timestampoffset",()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})}),this.audioSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.audioSegmentLoader_.on("appenderror",()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("ended",()=>{this.logger_("main segment loader ended"),this.onEndOfStream()}),this.timelineChangeController_.on("audioTimelineBehind",()=>{const t=this.audioSegmentLoader_.pendingSegment_;if(!t||!t.segment||!t.segment.syncInfo)return;const r=t.segment.syncInfo.end+.01;this.tech_.setCurrentTime(r)}),this.timelineChangeController_.on("fixBadTimelineChange",()=>{this.logger_("Fix bad timeline change. Restarting al segment loaders..."),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}),this.mainSegmentLoader_.on("earlyabort",t=>{this.bufferBasedABR||(this.delegateLoaders_("all",["abort"]),this.excludePlaylist({error:{message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},playlistExclusionDuration:A2}))});const e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const t=this.getCodecsOrExclude_();t&&this.sourceUpdater_.addOrChangeSourceBuffers(t)};this.mainSegmentLoader_.on("trackinfo",e),this.audioSegmentLoader_.on("trackinfo",e),this.mainSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("ended",()=>{this.logger_("audioSegmentLoader ended"),this.onEndOfStream()}),["segmentselected","segmentloadstart","segmentloaded","segmentkeyloadstart","segmentkeyloadcomplete","segmentdecryptionstart","segmentdecryptioncomplete","segmenttransmuxingstart","segmenttransmuxingcomplete","segmenttransmuxingtrackinfoavailable","segmenttransmuxingtiminginfoavailable","segmentappendstart","appendsdone","bandwidthupdated","timelinechange","codecschange"].forEach(t=>{this.mainSegmentLoader_.on(t,r=>{this.player_.trigger(Ge({},r))}),this.audioSegmentLoader_.on(t,r=>{this.player_.trigger(Ge({},r))}),this.subtitleSegmentLoader_.on(t,r=>{this.player_.trigger(Ge({},r))})})}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}pause(){this.mainSegmentLoader_.pause(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.pause(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.pause()}fastQualityChange_(e=this.selectPlaylist()){if(e&&e===this.mainPlaylistLoader_.media()){this.logger_("skipping fastQualityChange because new media is same as old");return}this.switchMedia_(e,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();const e=this.tech_.seekable();if(this.tech_.duration()===1/0&&this.tech_.currentTime()<e.start(0))return this.tech_.setCurrentTime(e.end(e.length-1))}setupFirstPlay(){const e=this.mainPlaylistLoader_.media();if(!e||this.tech_.paused()||this.hasPlayed_)return!1;if(!e.endList||e.start){const t=this.seekable();if(!t.length)return!1;const r=t.end(0);let n=r;if(e.start){const s=e.start.timeOffset;s<0?n=Math.max(r+s,t.start(0)):n=Math.min(r,s)}this.trigger("firstplay"),this.tech_.setCurrentTime(n)}return this.hasPlayed_=!0,this.load(),!0}handleSourceOpen_(){if(this.tryToCreateSourceBuffers_(),this.tech_.autoplay()){const e=this.tech_.play();typeof e<"u"&&typeof e.then=="function"&&e.then(null,t=>{})}this.trigger("sourceopen")}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;const e=this.inbandTextTracks_.metadataTrack_.cues;if(!e||!e.length)return;const t=this.duration();e[e.length-1].endTime=isNaN(t)||Math.abs(t)===1/0?Number.MAX_VALUE:t}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let e=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){const t=this.mainSegmentLoader_.getCurrentMediaInfo_();!t||t.hasVideo?e=e&&this.audioSegmentLoader_.ended_:e=this.audioSegmentLoader_.ended_}e&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(e){if(!this.seekable().length)return!1;const t=this.syncController_.getExpiredTime(e,this.duration());if(t===null)return!1;const r=Oi.Playlist.playlistEnd(e,t),n=this.tech_.currentTime(),s=this.tech_.buffered();if(!s.length)return r-n<=si;const a=s.end(s.length-1);return a-n<=si&&r-a<=si}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:r}){if(e=e||this.mainPlaylistLoader_.media(),r=r||t.playlistExclusionDuration||this.playlistExclusionDuration,!e){this.error=t,this.mediaSource.readyState!=="open"?this.trigger("error"):this.sourceUpdater_.endOfStream("network");return}e.playlistErrors_++;const n=this.mainPlaylistLoader_.main.playlists,s=n.filter(Ya),a=s.length===1&&s[0]===e;if(n.length===1&&r!==1/0)return F.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(a);if(a){if(this.main().contentSteering){const C=this.pathwayAttribute_(e),v=this.contentSteeringController_.steeringManifest.ttl*1e3;this.contentSteeringController_.excludePathway(C),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(C)},v);return}let S=!1;n.forEach(C=>{if(C===e)return;const v=C.excludeUntil;typeof v<"u"&&v!==1/0&&(S=!0,delete C.excludeUntil)}),S&&(F.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),this.tech_.trigger("retryplaylist"))}let l;e.playlistErrors_>this.maxPlaylistRetries?l=1/0:l=Date.now()+r*1e3,e.excludeUntil=l,t.reason&&(e.lastExcludeReason_=t.reason),this.tech_.trigger("excludeplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});const u=this.selectPlaylist();if(!u){this.error="Playback cannot continue. No available working or supported playlists.",this.trigger("error");return}const p=t.internal?this.logger_:F.log.warn,m=t.message?" "+t.message:"";p(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${m} Switching to playlist ${u.id}.`),u.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),u.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);const _=u.targetDuration/2*1e3||5*1e3,E=typeof u.lastRequest=="number"&&Date.now()-u.lastRequest<=_;return this.switchMedia_(u,"exclude",a||E)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(e,t){const r=[],n=e==="all";(n||e==="main")&&r.push(this.mainPlaylistLoader_);const s=[];(n||e==="audio")&&s.push("AUDIO"),(n||e==="subtitle")&&(s.push("CLOSED-CAPTIONS"),s.push("SUBTITLES")),s.forEach(a=>{const l=this.mediaTypes_[a]&&this.mediaTypes_[a].activePlaylistLoader;l&&r.push(l)}),["main","audio","subtitle"].forEach(a=>{const l=this[`${a}SegmentLoader_`];l&&(e===a||e==="all")&&r.push(l)}),r.forEach(a=>t.forEach(l=>{typeof a[l]=="function"&&a[l]()}))}setCurrentTime(e){const t=Ir(this.tech_.buffered(),e);if(!(this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media())||!this.mainPlaylistLoader_.media().segments)return 0;if(t&&t.length)return e;this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}duration(){if(!this.mainPlaylistLoader_)return 0;const e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:Oi.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}getSeekableRange_(e,t){const r=e.media();if(!r)return null;const n=this.syncController_.getMediaSequenceSync(t);if(n&&n.isReliable){const l=n.start,u=n.end;if(!isFinite(l)||!isFinite(u))return null;const p=Oi.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,r),m=Math.max(0,u-p);return m<l?null:at([[l,m]])}const s=this.syncController_.getExpiredTime(r,this.duration());if(s===null)return null;const a=Oi.Playlist.seekable(r,s,Oi.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,r));return a.length?a:null}computeFinalSeekable_(e,t){if(!t)return e;const r=e.start(0),n=e.end(0),s=t.start(0),a=t.end(0);return s>n||r>a?e:at([[Math.max(r,s),Math.min(n,a)]])}onSyncInfoUpdate_(){if(!this.mainPlaylistLoader_)return;const e=this.getSeekableRange_(this.mainPlaylistLoader_,"main");if(!e)return;let t;if(this.mediaTypes_.AUDIO.activePlaylistLoader&&(t=this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader,"audio"),!t))return;const r=this.seekable_;if(this.seekable_=this.computeFinalSeekable_(e,t),!this.seekable_||r&&r.length&&this.seekable_.length&&r.start(0)===this.seekable_.start(0)&&r.end(0)===this.seekable_.end(0))return;this.logger_(`seekable updated [${mg(this.seekable_)}]`);const n={seekableRanges:this.seekable_};this.trigger({type:"seekablerangeschanged",metadata:n}),this.tech_.trigger("seekablechanged")}updateDuration(e){if(this.updateDuration_&&(this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.updateDuration_=null),this.mediaSource.readyState!=="open"){this.updateDuration_=this.updateDuration.bind(this,e),this.mediaSource.addEventListener("sourceopen",this.updateDuration_);return}if(e){const n=this.seekable();if(!n.length)return;(isNaN(this.mediaSource.duration)||this.mediaSource.duration<n.end(n.length-1))&&this.sourceUpdater_.setDuration(n.end(n.length-1));return}const t=this.tech_.buffered();let r=Oi.Playlist.duration(this.mainPlaylistLoader_.media());t.length>0&&(r=Math.max(r,t.end(t.length-1))),this.mediaSource.duration!==r&&this.sourceUpdater_.setDuration(r)}dispose(){this.trigger("dispose"),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach(e=>{const t=this.mediaTypes_[e].groups;for(const r in t)t[r].forEach(n=>{n.playlistLoader&&n.playlistLoader.dispose()})}),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){const e=!!this.mediaTypes_.AUDIO.activePlaylistLoader,t=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),r=e?!!this.audioSegmentLoader_.getCurrentMediaInfo_():!0;return!(!t||!r)}getCodecsOrExclude_(){const e={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},t=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();e.video=e.main;const r=$n(this.main(),t),n={},s=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(n.video=r.video||e.main.videoCodec||ST),e.main.isMuxed&&(n.video+=`,${r.audio||e.main.audioCodec||ld}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||s)&&(n.audio=r.audio||e.main.audioCodec||e.audio.audioCodec||ld,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!n.audio&&!n.video){this.excludePlaylist({playlistToExclude:t,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});return}const a=(p,m)=>p?Un(m,this.usingManagedMediaSource_):Io(m),l={};let u;if(["video","audio"].forEach(function(p){if(n.hasOwnProperty(p)&&!a(e[p].isFmp4,n[p])){const m=e[p].isFmp4?"browser":"muxer";l[m]=l[m]||[],l[m].push(n[p]),p==="audio"&&(u=m)}}),s&&u&&t.attributes.AUDIO){const p=t.attributes.AUDIO;this.main().playlists.forEach(m=>{(m.attributes&&m.attributes.AUDIO)===p&&m!==t&&(m.excludeUntil=1/0)}),this.logger_(`excluding audio group ${p} as ${u} does not support codec(s): "${n.audio}"`)}if(Object.keys(l).length){const p=Object.keys(l).reduce((m,_)=>(m&&(m+=", "),m+=`${_} does not support codec(s): "${l[_].join(",")}"`,m),"")+".";this.excludePlaylist({playlistToExclude:t,error:{internal:!0,message:p},playlistExclusionDuration:1/0});return}if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const p=[];if(["video","audio"].forEach(m=>{const _=(ei(this.sourceUpdater_.codecs[m]||"")[0]||{}).type,E=(ei(n[m]||"")[0]||{}).type;_&&E&&_.toLowerCase()!==E.toLowerCase()&&p.push(`"${this.sourceUpdater_.codecs[m]}" -> "${n[m]}"`)}),p.length){this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${p.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0});return}}return n}tryToCreateSourceBuffers_(){if(this.mediaSource.readyState!=="open"||this.sourceUpdater_.hasCreatedSourceBuffers()||!this.areMediaTypesKnown_())return;const e=this.getCodecsOrExclude_();if(!e)return;this.sourceUpdater_.createSourceBuffers(e);const t=[e.video,e.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(t)}excludeUnsupportedVariants_(){const e=this.main().playlists,t=[];Object.keys(e).forEach(r=>{const n=e[r];if(t.indexOf(n.id)!==-1)return;t.push(n.id);const s=$n(this.main,n),a=[];s.audio&&!Io(s.audio)&&!Un(s.audio,this.usingManagedMediaSource_)&&a.push(`audio codec ${s.audio}`),s.video&&!Io(s.video)&&!Un(s.video,this.usingManagedMediaSource_)&&a.push(`video codec ${s.video}`),s.text&&s.text==="stpp.ttml.im1t"&&a.push(`text codec ${s.text}`),a.length&&(n.excludeUntil=1/0,this.logger_(`excluding ${n.id} for unsupported: ${a.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],r=this.main().playlists,n=ba(ei(e)),s=eh(n),a=n.video&&ei(n.video)[0]||null,l=n.audio&&ei(n.audio)[0]||null;Object.keys(r).forEach(u=>{const p=r[u];if(t.indexOf(p.id)!==-1||p.excludeUntil===1/0)return;t.push(p.id);const m=[],_=$n(this.mainPlaylistLoader_.main,p),E=eh(_);if(!(!_.audio&&!_.video)){if(E!==s&&m.push(`codec count "${E}" !== "${s}"`),!this.sourceUpdater_.canChangeType()){const S=_.video&&ei(_.video)[0]||null,C=_.audio&&ei(_.audio)[0]||null;S&&a&&S.type.toLowerCase()!==a.type.toLowerCase()&&m.push(`video codec "${S.type}" !== "${a.type}"`),C&&l&&C.type.toLowerCase()!==l.type.toLowerCase()&&m.push(`audio codec "${C.type}" !== "${l.type}"`)}m.length&&(p.excludeUntil=1/0,this.logger_(`excluding ${p.id}: ${m.join(" && ")}`))}})}updateAdCues_(e){let t=0;const r=this.seekable();r.length&&(t=r.start(0)),u2(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=Je.GOAL_BUFFER_LENGTH,r=Je.GOAL_BUFFER_LENGTH_RATE,n=Math.max(t,Je.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*r,n)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=Je.BUFFER_LOW_WATER_LINE,r=Je.BUFFER_LOW_WATER_LINE_RATE,n=Math.max(t,Je.MAX_BUFFER_LOW_WATER_LINE),s=Math.max(t,Je.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*r,this.bufferBasedABR?s:n)}bufferHighWaterLine(){return Je.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){rh(this.inbandTextTracks_,"com.apple.streaming",this.tech_),qw({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,r){const n=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();rh(this.inbandTextTracks_,e,this.tech_),Fw({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:n,videoDuration:r})}pathwayAttribute_(e){return e.attributes["PATHWAY-ID"]||e.attributes.serviceLocation}initContentSteeringController_(){const e=this.main();if(e.contentSteering){for(const t of e.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(t));if(this.contentSteeringController_.assignTagProperties(e.uri,e.contentSteering),this.contentSteeringController_.queryBeforeStart){this.contentSteeringController_.requestSteeringManifest(!0);return}this.tech_.one("canplay",()=>{this.contentSteeringController_.requestSteeringManifest()})}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on("content-steering",this.excludeThenChangePathway_.bind(this)),["contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach(e=>{this.contentSteeringController_.on(e,t=>{this.trigger(Ge({},t))})}),this.sourceType_==="dash"&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const e=this.main();(this.contentSteeringController_.didDASHTagChange(e.uri,e.contentSteering)||(()=>{const t=this.contentSteeringController_.getAvailablePathways(),r=[];for(const n of e.playlists){const s=n.attributes.serviceLocation;if(s&&(r.push(s),!t.has(s)))return!0}return!!(!r.length&&t.size)})())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){const e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();const t=this.main().playlists,r=new Set;let n=!1;Object.keys(t).forEach(s=>{const a=t[s],l=this.pathwayAttribute_(a),u=l&&e!==l;a.excludeUntil===1/0&&a.lastExcludeReason_==="content-steering"&&!u&&(delete a.excludeUntil,delete a.lastExcludeReason_,n=!0);const p=!a.excludeUntil&&a.excludeUntil!==1/0;!r.has(a.id)&&u&&p&&(r.add(a.id),a.excludeUntil=1/0,a.lastExcludeReason_="content-steering",this.logger_(`excluding ${a.id} for ${a.lastExcludeReason_}`))}),this.contentSteeringController_.manifestType_==="DASH"&&Object.keys(this.mediaTypes_).forEach(s=>{const a=this.mediaTypes_[s];if(a.activePlaylistLoader){const l=a.activePlaylistLoader.media_;l&&l.attributes.serviceLocation!==e&&(n=!0)}}),n&&this.changeSegmentPathway_()}handlePathwayClones_(){const e=this.main().playlists,t=this.contentSteeringController_.currentPathwayClones,r=this.contentSteeringController_.nextPathwayClones;if(t&&t.size||r&&r.size){for(const[n,s]of t.entries())r.get(n)||(this.mainPlaylistLoader_.updateOrDeleteClone(s),this.contentSteeringController_.excludePathway(n));for(const[n,s]of r.entries()){const a=t.get(n);if(!a){e.filter(l=>l.attributes["PATHWAY-ID"]===s["BASE-ID"]).forEach(l=>{this.mainPlaylistLoader_.addClonePathway(s,l)}),this.contentSteeringController_.addAvailablePathway(n);continue}this.equalPathwayClones_(a,s)||(this.mainPlaylistLoader_.updateOrDeleteClone(s,!0),this.contentSteeringController_.addAvailablePathway(n))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...r])))}}equalPathwayClones_(e,t){if(e["BASE-ID"]!==t["BASE-ID"]||e.ID!==t.ID||e["URI-REPLACEMENT"].HOST!==t["URI-REPLACEMENT"].HOST)return!1;const r=e["URI-REPLACEMENT"].PARAMS,n=t["URI-REPLACEMENT"].PARAMS;for(const s in r)if(r[s]!==n[s])return!1;for(const s in n)if(r[s]!==n[s])return!1;return!0}changeSegmentPathway_(){const e=this.selectPlaylist();this.pauseLoading(),this.contentSteeringController_.manifestType_==="DASH"&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0;const t="non-usable";this.mainPlaylistLoader_.main.playlists.forEach(r=>{const n=this.mainPlaylistLoader_.getKeyIdSet(r);!n||!n.size||n.forEach(s=>{const a="usable",l=this.keyStatusMap_.has(s)&&this.keyStatusMap_.get(s)===a,u=r.lastExcludeReason_===t&&r.excludeUntil===1/0;l?l&&u&&(delete r.excludeUntil,delete r.lastExcludeReason_,this.logger_(`enabling playlist ${r.id} because key ID ${s} is ${a}`)):(r.excludeUntil!==1/0&&r.lastExcludeReason_!==t&&(r.excludeUntil=1/0,r.lastExcludeReason_=t,this.logger_(`excluding playlist ${r.id} because the key ID ${s} doesn't exist in the keyStatusMap or is not ${a}`)),e++)})}),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(r=>{const n=r&&r.attributes&&r.attributes.RESOLUTION&&r.attributes.RESOLUTION.height<720,s=r.excludeUntil===1/0&&r.lastExcludeReason_===t;n&&s&&(delete r.excludeUntil,F.log.warn(`enabling non-HD playlist ${r.id} because all playlists were excluded due to ${t} key IDs`))})}addKeyStatus_(e,t){const r=(typeof e=="string"?e:s2(e)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${t}' with key ID ${r} added to the keyStatusMap`),this.keyStatusMap_.set(r,t)}updatePlaylistByKeyStatus(e,t){this.addKeyStatus_(e,t),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}}const R2=(i,e,t)=>r=>{const n=i.main.playlists[e],s=wu(n),a=Ya(n);if(typeof r>"u")return a;r?delete n.disabled:n.disabled=!0;const l={renditionInfo:{id:e,bandwidth:n.attributes.BANDWIDTH,resolution:n.attributes.RESOLUTION,codecs:n.attributes.CODECS},cause:"fast-quality"};return r!==a&&!s&&(r?(t(n),i.trigger({type:"renditionenabled",metadata:l})):i.trigger({type:"renditiondisabled",metadata:l})),r};class N2{constructor(e,t,r){const{playlistController_:n}=e,s=n.fastQualityChange_.bind(n);if(t.attributes){const a=t.attributes.RESOLUTION;this.width=a&&a.width,this.height=a&&a.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=$n(n.main(),t),this.playlist=t,this.id=r,this.enabled=R2(e.playlists,t.id,s)}}const O2=function(i){i.representations=()=>{const e=i.playlistController_.main(),t=as(e)?i.playlistController_.getAudioTrackPlaylists_():e.playlists;return t?t.filter(r=>!wu(r)).map((r,n)=>new N2(i,r,r.id)):[]}},mh=["seeking","seeked","pause","playing","error"];class U2 extends F.EventTarget{constructor(e){super(),this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.playedRanges_=[],this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=jt("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),r=()=>this.monitorCurrentTime_(),n=()=>this.techWaiting_(),s=()=>this.resetTimeUpdate_(),a=this.playlistController_,l=["main","subtitle","audio"],u={};l.forEach(m=>{u[m]={reset:()=>this.resetSegmentDownloads_(m),updateend:()=>this.checkSegmentDownloads_(m)},a[`${m}SegmentLoader_`].on("appendsdone",u[m].updateend),a[`${m}SegmentLoader_`].on("playlistupdate",u[m].reset),this.tech_.on(["seeked","seeking"],u[m].reset)});const p=m=>{["main","audio"].forEach(_=>{a[`${_}SegmentLoader_`][m]("appended",this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),p("off"))},this.clearSeekingAppendCheck_=()=>p("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),p("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",n),this.tech_.on(mh,s),this.tech_.on("canplay",r),this.tech_.one("play",t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",n),this.tech_.off(mh,s),this.tech_.off("canplay",r),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),l.forEach(m=>{a[`${m}SegmentLoader_`].off("appendsdone",u[m].updateend),a[`${m}SegmentLoader_`].off("playlistupdate",u[m].reset),this.tech_.off(["seeked","seeking"],u[m].reset)}),this.checkCurrentTimeTimeout_&&x.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&x.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=x.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(e){const t=this.playlistController_[`${e}SegmentLoader_`];this[`${e}StalledDownloads_`]>0&&this.logger_(`resetting possible stalled download count for ${e} loader`),this[`${e}StalledDownloads_`]=0,this[`${e}Buffered_`]=t.buffered_()}checkSegmentDownloads_(e){const t=this.playlistController_,r=t[`${e}SegmentLoader_`],n=r.buffered_(),s=vE(this[`${e}Buffered_`],n);if(this[`${e}Buffered_`]=n,s){const a={bufferedRanges:n};t.trigger({type:"bufferedrangeschanged",metadata:a}),this.resetSegmentDownloads_(e);return}this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:r.playlist_&&r.playlist_.id,buffered:ir(n)}),!(this[`${e}StalledDownloads_`]<10)&&(this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:"usage",name:`vhs-${e}-download-exclusion`}),e!=="subtitle"&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0}))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;const e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+si>=t.end(t.length-1)))return this.techWaiting_();if(this.consecutiveUpdates>=5&&e===this.lastRecordedTime)this.consecutiveUpdates++,this.waiting_();else if(e===this.lastRecordedTime)this.consecutiveUpdates++;else{this.playedRanges_.push(at([this.lastRecordedTime,e]));const r={playedRanges:this.playedRanges_};this.playlistController_.trigger({type:"playedrangeschanged",metadata:r}),this.consecutiveUpdates=0,this.lastRecordedTime=e}}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;const e=this.seekable(),t=this.tech_.currentTime(),r=this.afterSeekableWindow_(e,t,this.media(),this.allowSeeksWithinUnsafeLiveWindow);let n;if(r&&(n=e.end(e.length-1)),this.beforeSeekableWindow_(e,t)){const S=e.start(0);n=S+(S===e.end(0)?0:si)}if(typeof n<"u")return this.logger_(`Trying to seek outside of seekable at time ${t} with seekable range ${mg(e)}. Seeking to ${n}.`),this.tech_.setCurrentTime(n),!0;const s=this.playlistController_.sourceUpdater_,a=this.tech_.buffered(),l=s.audioBuffer?s.audioBuffered():null,u=s.videoBuffer?s.videoBuffered():null,p=this.media(),m=p.partTargetDuration?p.partTargetDuration:(p.targetDuration-ni)*2,_=[l,u];for(let S=0;S<_.length;S++)if(_[S]&&Su(_[S],t)<m)return!1;const E=js(a,t);return E.length===0?!1:(n=E.start(0)+si,this.logger_(`Buffered region starts (${E.start(0)}) just beyond seek point (${t}). Seeking to ${n}.`),this.tech_.setCurrentTime(n),!0)}waiting_(){if(this.techWaiting_())return;const e=this.tech_.currentTime(),t=this.tech_.buffered(),r=Ir(t,e);if(r.length&&e+3<=r.end(0)){this.resetTimeUpdate_(),this.tech_.setCurrentTime(e),this.logger_(`Stopped at ${e} while inside a buffered region [${r.start(0)} -> ${r.end(0)}]. Attempting to resume playback by seeking to the current time.`),this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"});return}}techWaiting_(){const e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){const a=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${a}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(a),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}const r=this.tech_.vhs.playlistController_.sourceUpdater_,n=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:r.audioBuffered(),videoBuffered:r.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;const s=js(n,t);return s.length>0?(this.logger_(`Stopped at ${t} and seeking to ${s.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0):!1}afterSeekableWindow_(e,t,r,n=!1){if(!e.length)return!1;let s=e.end(e.length-1)+si;const a=!r.endList,l=typeof r.partTargetDuration=="number";return a&&(l||n)&&(s=e.end(e.length-1)+r.targetDuration*3),t>s}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t<e.start(0)-this.liveRangeSafeTimeDelta)}videoUnderflow_({videoBuffered:e,audioBuffered:t,currentTime:r}){if(!e)return;let n;if(e.length&&t.length){const s=Ir(e,r-3),a=Ir(e,r),l=Ir(t,r);l.length&&!a.length&&s.length&&(n={start:s.end(0),end:l.end(0)})}else js(e,r).length||(n=this.gapFromVideoUnderflow_(e,r));return n?(this.logger_(`Encountered a gap in video from ${n.start} to ${n.end}. Seeking to current time ${r}`),!0):!1}skipTheGap_(e){const t=this.tech_.buffered(),r=this.tech_.currentTime(),n=js(t,r);if(this.resetTimeUpdate_(),n.length===0||r!==e)return;this.logger_("skipTheGap_:","currentTime:",r,"scheduled currentTime:",e,"nextRange start:",n.start(0)),this.tech_.setCurrentTime(n.start(0)+ni);const s={gapInfo:{from:r,to:n.start(0)}};this.playlistController_.trigger({type:"gapjumped",metadata:s}),this.tech_.trigger({type:"usage",name:"vhs-gap-skip"})}gapFromVideoUnderflow_(e,t){const r=yE(e);for(let n=0;n<r.length;n++){const s=r.start(n),a=r.end(n);if(t-s<4&&t-s>2)return{start:s,end:a}}return null}}const M2={errorInterval:30,getSource(i){const e=this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource();return i(e)}},sf=function(i,e){let t=0,r=0;const n=_e(M2,e);i.ready(()=>{i.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const s=function(){r&&i.currentTime(r)},a=function(m){m!=null&&(r=i.duration()!==1/0&&i.currentTime()||0,i.one("loadedmetadata",s),i.src(m),i.trigger({type:"usage",name:"vhs-error-reload"}),i.play())},l=function(){if(Date.now()-t<n.errorInterval*1e3){i.trigger({type:"usage",name:"vhs-error-reload-canceled"});return}if(!n.getSource||typeof n.getSource!="function"){F.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!");return}return t=Date.now(),n.getSource.call(i,a)},u=function(){i.off("loadedmetadata",s),i.off("error",l),i.off("dispose",u)},p=function(m){u(),sf(i,m)};i.on("error",l),i.on("dispose",u),i.reloadSourceOnError=p},B2=function(i){sf(this,i)};var af="3.16.2",F2="7.1.0",j2="1.3.1",$2="7.2.0",q2="4.0.2";const Be={PlaylistLoader:Ar,Playlist:Tt,utils:HE,STANDARD_PLAYLIST_SELECTOR:ih,INITIAL_PLAYLIST_SELECTOR:Nw,lastBandwidthSelector:ih,movingAverageBandwidthSelector:Pw,comparePlaylistBandwidth:Iu,comparePlaylistResolution:Dw,xhr:Dg()};Object.keys(Je).forEach(i=>{Object.defineProperty(Be,i,{get(){return F.log.warn(`using Vhs.${i} is UNSAFE be sure you know what you are doing`),Je[i]},set(e){if(F.log.warn(`using Vhs.${i} is UNSAFE be sure you know what you are doing`),typeof e!="number"||e<0){F.log.warn(`value of Vhs.${i} must be greater than or equal to 0`);return}Je[i]=e}})});const of="videojs-vhs",lf=function(i,e){const t=e.media();let r=-1;for(let n=0;n<i.length;n++)if(i[n].id===t.id){r=n;break}i.selectedIndex_=r,i.trigger({selectedIndex:r,type:"change"})},V2=function(i,e){e.representations().forEach(t=>{i.addQualityLevel(t)}),lf(i,e.playlists)};Be.canPlaySource=function(){return F.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const H2=(i,e,t)=>{if(!i)return i;let r={};e&&e.attributes&&e.attributes.CODECS&&(r=ba(ei(e.attributes.CODECS))),t&&t.attributes&&t.attributes.CODECS&&(r.audio=t.attributes.CODECS);const n=jr(r.video),s=jr(r.audio),a={};for(const l in i)a[l]={},s&&(a[l].audioContentType=s),n&&(a[l].videoContentType=n),e.contentProtection&&e.contentProtection[l]&&e.contentProtection[l].pssh&&(a[l].pssh=e.contentProtection[l].pssh),typeof i[l]=="string"&&(a[l].url=i[l]);return _e(i,a)},z2=(i,e)=>i.reduce((t,r)=>{if(!r.contentProtection)return t;const n=e.reduce((s,a)=>{const l=r.contentProtection[a];return l&&l.pssh&&(s[a]={pssh:l.pssh}),s},{});return Object.keys(n).length&&t.push(n),t},[]),W2=({player:i,sourceKeySystems:e,audioMedia:t,mainPlaylists:r})=>{if(!i.eme.initializeMediaKeys)return Promise.resolve();const n=t?r.concat([t]):r,s=z2(n,Object.keys(e)),a=[],l=[];return s.forEach(u=>{l.push(new Promise((p,m)=>{i.tech_.one("keysessioncreated",p)})),a.push(new Promise((p,m)=>{i.eme.initializeMediaKeys({keySystems:u},_=>{if(_){m(_);return}p()})}))}),Promise.race([Promise.all(a),Promise.race(l)])},G2=({player:i,sourceKeySystems:e,media:t,audioMedia:r})=>{const n=H2(e,t,r);return n?(i.currentSource().keySystems=n,n&&!i.eme?(F.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0):!1},uf=()=>{if(!x.localStorage)return null;const i=x.localStorage.getItem(of);if(!i)return null;try{return JSON.parse(i)}catch{return null}},X2=i=>{if(!x.localStorage)return!1;let e=uf();e=e?_e(e,i):i;try{x.localStorage.setItem(of,JSON.stringify(e))}catch{return!1}return e},K2=i=>i.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")===0?JSON.parse(i.substring(i.indexOf(",")+1)):i,cf=(i,e)=>{i._requestCallbackSet||(i._requestCallbackSet=new Set),i._requestCallbackSet.add(e)},df=(i,e)=>{i._responseCallbackSet||(i._responseCallbackSet=new Set),i._responseCallbackSet.add(e)},hf=(i,e)=>{i._requestCallbackSet&&(i._requestCallbackSet.delete(e),i._requestCallbackSet.size||delete i._requestCallbackSet)},pf=(i,e)=>{i._responseCallbackSet&&(i._responseCallbackSet.delete(e),i._responseCallbackSet.size||delete i._responseCallbackSet)};Be.supportsNativeHls=function(){if(!X||!X.createElement)return!1;const i=X.createElement("video");return F.getTech("Html5").isSupported()?["application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"].some(function(e){return/maybe|probably/i.test(i.canPlayType(e))}):!1}();Be.supportsNativeDash=function(){return!X||!X.createElement||!F.getTech("Html5").isSupported()?!1:/maybe|probably/i.test(X.createElement("video").canPlayType("application/dash+xml"))}();Be.supportsTypeNatively=i=>i==="hls"?Be.supportsNativeHls:i==="dash"?Be.supportsNativeDash:!1;Be.isSupported=function(){return F.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};Be.xhr.onRequest=function(i){cf(Be.xhr,i)};Be.xhr.onResponse=function(i){df(Be.xhr,i)};Be.xhr.offRequest=function(i){hf(Be.xhr,i)};Be.xhr.offResponse=function(i){pf(Be.xhr,i)};const Y2=F.getComponent("Component");class mf extends Y2{constructor(e,t,r){if(super(t,r.vhs),typeof r.initialBandwidth=="number"&&(this.options_.bandwidth=r.initialBandwidth),this.logger_=jt("VhsHandler"),t.options_&&t.options_.playerId){const n=F.getPlayer(t.options_.playerId);this.player_=n}if(this.tech_=t,this.source_=e,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&t.overrideNativeAudioTracks&&t.overrideNativeVideoTracks)t.overrideNativeAudioTracks(!0),t.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(t.featuresNativeVideoTracks||t.featuresNativeAudioTracks))throw new Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on(X,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],n=>{const s=X.fullscreenElement||X.webkitFullscreenElement||X.mozFullScreenElement||X.msFullscreenElement;s&&s.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()}),this.on(this.tech_,"seeking",function(){if(this.ignoreNextSeekingEvent_){this.ignoreNextSeekingEvent_=!1;return}this.setCurrentTime(this.tech_.currentTime())}),this.on(this.tech_,"error",function(){this.tech_.error()&&this.playlistController_&&this.playlistController_.pauseLoading()}),this.on(this.tech_,"play",this.play)}setOptions_(e={}){if(this.options_=_e(this.options_,e),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions!==!1,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.useBandwidthFromLocalStorage=typeof this.source_.useBandwidthFromLocalStorage<"u"?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=this.options_.useNetworkInformationApi||!1,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=this.options_.llhls!==!1,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,typeof this.options_.playlistExclusionDuration!="number"&&(this.options_.playlistExclusionDuration=60),typeof this.options_.bandwidth!="number"&&this.options_.useBandwidthFromLocalStorage){const r=uf();r&&r.bandwidth&&(this.options_.bandwidth=r.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),r&&r.throughput&&(this.options_.throughput=r.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"}))}typeof this.options_.bandwidth!="number"&&(this.options_.bandwidth=Je.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===Je.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","customPixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR","liveRangeSafeTimeDelta","llhls","useForcedSubtitles","useNetworkInformationApi","useDtsForTimestampOffset","exactManifestTimings","leastPixelDiffSelector"].forEach(r=>{typeof this.source_[r]<"u"&&(this.options_[r]=this.source_[r])}),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio;const t=this.options_.customPixelRatio;typeof t=="number"&&t>=0&&(this.customPixelRatio=t)}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=K2(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=Be,this.options_.sourceType=Rp(t),this.options_.seekTo=s=>{this.tech_.setCurrentTime(s)},this.options_.player_=this.player_,this.playlistController_=new P2(this.options_);const r=_e({liveRangeSafeTimeDelta:si},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new U2(r),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{const s=F.players[this.tech_.options_.playerId];let a=this.playlistController_.error;typeof a=="object"&&!a.code?a.code=3:typeof a=="string"&&(a={message:a,code:3}),s.error(a)});const n=this.options_.bufferBasedABR?Be.movingAverageBandwidthSelector(.55):Be.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):n.bind(this),this.playlistController_.selectInitialPlaylist=Be.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPlaylist},set(s){this.playlistController_.selectPlaylist=s.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(s){this.playlistController_.mainSegmentLoader_.throughput.rate=s,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let s=this.playlistController_.mainSegmentLoader_.bandwidth;const a=x.navigator.connection||x.navigator.mozConnection||x.navigator.webkitConnection,l=1e7;if(this.options_.useNetworkInformationApi&&a){const u=a.downlink*1e3*1e3;u>=l&&s>=l?s=Math.max(s,u):s=u}return s},set(s){this.playlistController_.mainSegmentLoader_.bandwidth=s,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){const s=1/(this.bandwidth||1);let a;return this.throughput>0?a=1/this.throughput:a=0,Math.floor(1/(s+a))},set(){F.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playlistController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>ir(this.tech_.buffered()),enumerable:!0},currentTime:{get:()=>this.tech_.currentTime(),enumerable:!0},currentSource:{get:()=>this.tech_.currentSource_,enumerable:!0},currentTech:{get:()=>this.tech_.name_,enumerable:!0},duration:{get:()=>this.tech_.duration(),enumerable:!0},main:{get:()=>this.playlists.main,enumerable:!0},playerDimensions:{get:()=>this.tech_.currentDimensions(),enumerable:!0},seekable:{get:()=>ir(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one("canplay",this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on("bandwidthupdate",()=>{this.options_.useBandwidthFromLocalStorage&&X2({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{O2(this)}),this.playlistController_.sourceUpdater_.on("createdsourcebuffers",()=>{this.setupEme_()}),this.on(this.playlistController_,"progress",function(){this.tech_.trigger("progress")}),this.on(this.playlistController_,"firstplay",function(){this.ignoreNextSeekingEvent_=!0}),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=x.URL.createObjectURL(this.playlistController_.mediaSource),(F.browser.IS_ANY_SAFARI||F.browser.IS_IOS)&&this.options_.overrideNative&&this.options_.sourceType==="hls"&&typeof this.tech_.addSourceElement=="function"?(this.tech_.addSourceElement(this.mediaSourceUrl_),this.tech_.addSourceElement(this.source_.src)):this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),W2({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:e&&e.media(),mainPlaylists:this.playlists.main.playlists}).then(()=>{this.logger_("created EME key session"),this.playlistController_.sourceUpdater_.initializedEme()}).catch(t=>{this.logger_("error while creating EME key session",t),this.player_.error({message:"Failed to initialize media keys for EME",code:3})})}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=G2({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});if(this.player_.tech_.on("keystatuschange",r=>{this.playlistController_.updatePlaylistByKeyStatus(r.keyId,r.status)}),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),!t){this.playlistController_.sourceUpdater_.initializedEme();return}this.createKeySessions_()}setupQualityLevels_(){const e=F.players[this.tech_.options_.playerId];!e||!e.qualityLevels||this.qualityLevels_||(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{V2(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{lf(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":af,"mux.js":F2,"mpd-parser":j2,"m3u8-parser":$2,"aes-decrypter":q2}}version(){return this.constructor.version()}canChangeType(){return ef.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(e){this.playlistController_.setCurrentTime(e)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&x.URL.revokeObjectURL&&(x.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return QE({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,r=!0,n=2){return Ug({programTime:e,playlist:this.playlistController_.media(),retryCount:n,pauseAfterSeek:r,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{cf(this.xhr,e)},this.xhr.onResponse=e=>{df(this.xhr,e)},this.xhr.offRequest=e=>{hf(this.xhr,e)},this.xhr.offResponse=e=>{pf(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}attachStreamingEventListeners_(){const e=["seekablerangeschanged","bufferedrangeschanged","contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"],t=["gapjumped","playedrangeschanged"];e.forEach(r=>{this.playlistController_.on(r,n=>{this.player_.trigger(Ge({},n))})}),t.forEach(r=>{this.playbackWatcher_.on(r,n=>{this.player_.trigger(Ge({},n))})})}}const Sa={name:"videojs-http-streaming",VERSION:af,canHandleSource(i,e={}){const t=_e(F.options,e);return!t.vhs.experimentalUseMMS&&!Un("avc1.4d400d,mp4a.40.2",!1)?!1:Sa.canPlayType(i.type,t)},handleSource(i,e,t={}){const r=_e(F.options,t);return e.vhs=new mf(i,e,r),e.vhs.xhr=Dg(),e.vhs.setupXhrHooks_(),e.vhs.src(i.src,i.type),e.vhs},canPlayType(i,e){const t=Rp(i);if(!t)return"";const r=Sa.getOverrideNative(e);return!Be.supportsTypeNatively(t)||r?"maybe":""},getOverrideNative(i={}){const{vhs:e={}}=i,t=!(F.browser.IS_ANY_SAFARI||F.browser.IS_IOS),{overrideNative:r=t}=e;return r}},Q2=()=>Un("avc1.4d400d,mp4a.40.2",!0);Q2()&&F.getTech("Html5").registerSourceHandler(Sa,0);F.VhsHandler=mf;F.VhsSourceHandler=Sa;F.Vhs=Be;F.use||F.registerComponent("Vhs",Be);F.options.vhs=F.options.vhs||{};(!F.getPlugin||!F.getPlugin("reloadSourceOnError"))&&F.registerPlugin("reloadSourceOnError",B2);const J2=i=>{const e=Se.useRef();return Se.useEffect(()=>{if(!e.current&&i.current){const t=document.createElement("video-js");t.classList.add("vjs-big-play-centered"),i.current.appendChild(t),e.current=F(t,{controls:!1,playsinline:!0})}return()=>{e.current&&(e.current.dispose(),e.current=void 0)}},[]),e},gf={time:0,adCount:0,adPosition:0,skipDelay:0,playing:!1,paused:!1,reset:()=>{},whyThisAd:null,hasAdUrl:!1,adAction:i=>{},playMuted:!1,muted:!1,autoplay:!0},Re=G.i(gf),gh=i=>{if(!i)return 0;const e=i.duration(),t=i.currentTime();return e===void 0||isNaN(e)||t===void 0||isNaN(t)?0:Math.round(e-t)},Z2=(i,e)=>{const t=Ib(i,e),r=J2(i),n=Se.useRef(),s=Se.useRef(!1),a=Se.useRef(!1),l=Se.useCallback(()=>{if(a.current)return;const S=t.get().nonceManager;if(S&&s.current)try{S.sendPlaybackEnd()}catch(C){console.warn("[PAL] sendPlaybackEnd failed",C)}a.current=!0},[t]),u=Se.useCallback(()=>{l(),r.current&&(r.current.pause(),r.current.src(void 0)),n.current=void 0,Re.set({...gf,reset:u})},[r,l]);Se.useEffect(()=>{Re.setKey("reset",u)},[u]);const p=Se.useCallback(()=>{var S,C,v;const{adPosition:L,adCount:D}=Re.get();if(r.current){if(L<D){const U=L+1,{ads:O,muted:B,autoplay:P,nonceManager:$}=t.get(),Q=O[U-1];if(Q){(S=n.current)==null||S.complete(),n.current=new _b(null,Q.ad,Q.creative),n.current.on("clickthrough",K=>{if($)try{$.sendAdClick()}catch(ie){console.warn("[PAL] sendAdClick failed",ie)}window.open(K,"_blank")}),Re.setKey("adPosition",U),Re.setKey("playMuted",B),Re.setKey("skipDelay",Q.creative.skipDelay||0),Re.setKey("time",0),Re.setKey("adAction",K=>{n.current&&n.current.click(null,{CLICKPOS:[K.clientX,K.clientY]})}),Re.setKey("whyThisAd",Q.creative.icons.find(K=>K.program==="GoogleWhyThisAd")||null),Re.setKey("hasAdUrl",!!((C=Q.creative.videoClickThroughURLTemplate)!=null&&C.url)),r.current.src(Q.mediaFileUrl),Re.setKey("playing",!0),L===0?(Re.setKey("muted",B),Re.setKey("autoplay",P),B&&r.current.muted(!0),P?r.current.play():(r.current.pause(),Re.setKey("paused",!0))):r.current.play();return}}(v=n.current)==null||v.complete(),u()}},[r,u,t]),m=Se.useCallback(()=>{if(!r.current)return;const S=r.current.muted();r.current.muted(!S),Re.setKey("muted",!S),n.current&&n.current.setMuted(!S)},[r]),_=Se.useCallback(()=>{r.current&&(r.current.paused()?(r.current.play(),n.current&&n.current.setPaused(!1)):(r.current.pause(),n.current&&n.current.setPaused(!0)))},[r]),E=Se.useCallback(()=>{r.current&&(n.current&&n.current.skip(),p())},[p,r]);return Se.useEffect(()=>{const S=r.current;if(!S)return()=>{};const C=P=>{if(Re.setKey("playing",!0),Re.setKey("paused",!1),Re.setKey("time",gh(P.target.player)),!s.current){const $=t.get().nonceManager;if($)try{$.sendPlaybackStart(),s.current=!0,a.current=!1}catch(Q){console.warn("[PAL] sendPlaybackStart failed",Q)}}},v=()=>{var P;(P=n.current)==null||P.complete(),p()},L=P=>{Re.setKey("muted",P.target.player.muted())},D=()=>{Re.setKey("paused",!0)},U=P=>{P.target.tagName==="VIDEO"&&(Re.get().autoplay||_())},O=P=>{Re.setKey("time",gh(P.target.player)),n.current&&n.current.setProgress(P.target.player.currentTime())},B=()=>{u()};return S.on("play",C),S.on("ended",v),S.on("muted",L),S.on("pause",D),S.on("click",U),S.on("timeupdate",O),S.on("error",B),()=>{S.off("play",C),S.off("ended",v),S.off("muted",L),S.off("pause",D),S.off("click",U),S.off("timeupdate",O),S.off("error",B)}},[_,p,r,u,t]),Se.useEffect(()=>t.subscribe(S=>{S&&(s.current=!1,a.current=!1,Re.setKey("adCount",S.ads.length),Re.setKey("adPosition",0),p())}),[t,r,p]),Se.useEffect(()=>()=>{u()},[u]),[Re,m,_,E,n]},ek=({promotion:i,onClose:e,promotionId:t,externalAd:r,skipAutoClose:n})=>{var s,a,l,u,p;const m=Se.useRef(null),[_,E,S,C]=Z2(m,r==null?void 0:r.url),{time:v,adCount:L,adPosition:D,skipDelay:U,playing:O,paused:B,reset:P,muted:$,playMuted:Q,autoplay:K,whyThisAd:ie,hasAdUrl:me,adAction:oe}=G.useStore(_),ge=((s=i.sponsor)==null?void 0:s.logo)&&i.logoMode===ce.PromotionLogoMode.CENTER;return W.jsxs(kh,{className:"PromoOverlay",children:[W.jsxs(Ch,{children:[W.jsx(Ih,{className:G.cx_default(!ge&&Ah),children:W.jsx(Lh,{style:{transform:"scale(1.5)"},children:"Ad"})}),W.jsxs(eb,{children:[W.jsx(z0,{time:v,adCount:L,adPosition:D}),!!U&&O&&W.jsx(G.y,{timerClassName:"SkipTimerCount",className:"ClosePromoIcon",close:()=>{C()},duration:U,isPlaying:!B,skipIcon:!0}),n&&W.jsx(G.y,{className:"ClosePromoIcon",close:()=>{P(),e==null||e()}})]})]}),W.jsx(xh,{className:G.cx_default(Sc,O&&Ec,!O&&wc),children:W.jsxs(Z0,{ref:m,children:[ie&&W.jsx(G0,{whyThisAd:ie}),W.jsxs(X0,{style:(ie==null?void 0:ie.xPosition)==="right"?{left:"8px"}:{right:"8px"},children:[Q&&W.jsx(Y0,{className:G.cx_default(!$&&"muted"),onClick:()=>E()}),B&&!K&&W.jsx(J0,{onClick:()=>S()})]})]})}),me&&W.jsx(Dh,{className:G.cx_default(Sc,O&&Ec,!O&&wc),children:W.jsx(Ph,{as:"button",onClick:oe,style:{backgroundColor:((l=(a=i.banner)==null?void 0:a.ctaButton)==null?void 0:l.color)||"#009dc4",color:((p=(u=i.banner)==null?void 0:u.ctaButton)==null?void 0:p.textColor)||"#fff"},"data-a":"button","data-promo-id":t,"data-promo-type":i.type,target:"_blank",children:"Show more"})})]})},fh=i=>{var e,t,r,n,s,a,l,u,p,m,_,E,S,C,v,L,D,U,O,B,P,$,Q,K,ie,me,oe,ge,ee,ue;const{promotion:te,open:de,advertisementPaused:be,togglePause:je,controlVideo:Ye,skipAutoClose:ve,promotionId:ye,onClose:kt,markAsViewed:Pt,externalAd:xe,isEventFired:pe,fireEvent:$e,muted:dr}=i,wi=te.type===ce.PromotionType.INGAME_IAB11_LBAR||te.type===ce.PromotionType.INGAME_IAB11||te.type===ce.PromotionType.INGAME_IAB11_SIDEBAR,ki=((e=te.sponsor)==null?void 0:e.logo)&&te.logoMode===ce.PromotionLogoMode.CENTER,qi=!!((r=(t=te.banner)==null?void 0:t.video)!=null&&r.url),Ct=te.autoPlayVideo===ce.AutoPlayVideo.ENABLED,Ci=te.playVideoMuted===ce.PlayVideoMuted.ENABLED;if(Se.useEffect(()=>{je==null||je(qi||Ct),de==null||de()},[]),Se.useEffect(()=>{ye&&te.type&&Pt&&Pt()},[ye,te.type,Pt]),Se.useEffect(()=>()=>{Ye==null||Ye({muted:!1})},[Ye]),xe)return W.jsx(ek,{...i,externalAd:xe});let Kt=(n=te.banner)==null?void 0:n.url;Kt&&Kt.indexOf("http")!==0&&(Kt=`https://${Kt}`);let Vi=!0;return qi&&(!be||!Ct?Vi=!0:Vi=!1),W.jsxs(kh,{className:"PromoOverlay",children:[W.jsxs("div",{children:[W.jsxs(Ch,{children:[W.jsxs(Ih,{className:G.cx_default(!ki&&Ah),children:[((s=te.sponsor)==null?void 0:s.logo)&&te.logoMode===ce.PromotionLogoMode.LEFT&&W.jsx(bc,{className:"PromoSponsorLogo",src:(a=te.sponsor)==null?void 0:a.logo,alt:"promo"}),W.jsxs(B0,{style:{paddingLeft:(l=te.sponsor)!=null&&l.logo&&te.logoMode===ce.PromotionLogoMode.LEFT?"0px":"8px"},children:[((u=te.sponsor)==null?void 0:u.logo)&&te.logoMode===ce.PromotionLogoMode.LEFT&&W.jsx(N0,{children:(p=te.sponsor)==null?void 0:p.name}),W.jsxs(F0,{className:"SponsorText",children:[W.jsx(Lh,{children:"AD"}),W.jsx(j0,{children:"SPONSORED"})]})]})]}),W.jsx(G.y,{className:"ClosePromoIcon",close:kt,autoClose:(m=te.closeTimer)==null?void 0:m.auto,duration:ve?0:(_=te.closeTimer)==null?void 0:_.seconds,isPlaying:Vi})]}),W.jsxs(xh,{children:[ki&&W.jsx(bc,{className:U0,src:(E=te.sponsor)==null?void 0:E.logo,alt:"promo"}),W.jsx(vc,{children:(C=(S=te.banner)==null?void 0:S.video)!=null&&C.url?W.jsx(G.Et,{source:(L=(v=te.banner)==null?void 0:v.video)==null?void 0:L.url,poster:(U=(D=te.banner)==null?void 0:D.video)==null?void 0:U.thumbnailUrl,aspectRatio:wi?"1/1":"2/1",onRender:()=>{pe!=null&&pe("video-rendered")||(G.eventBus.emit("advertisement",{action:"videoRendered",payload:{id:ye,type:te.type}}),$e==null||$e("video-rendered"))},onQuartile:$t=>{pe!=null&&pe(`video-quartile-${$t}`)||(G.eventBus.emit("advertisement",{action:"quartileCompleted",payload:{id:ye,type:te.type,quartile:$t}}),$e==null||$e(`video-quartile-${$t}`))},onMute:$t=>{const qt=$t?"muted":"unmuted";pe!=null&&pe(qt)||(G.eventBus.emit("advertisement",{action:$t?"videoMuted":"videoUnmuted",payload:{id:ye,type:te.type}}),$e==null||$e(qt))},onPause:()=>{Ct&&(je==null||je(!0))},onReplay:()=>{pe!=null&&pe("replayed")||(G.eventBus.emit("advertisement",{action:"videoReplayed",payload:{id:ye,type:te.type}}),$e==null||$e("replayed"))},onPlay:()=>{pe!=null&&pe("played")||(G.eventBus.emit("advertisement",{action:"videoPlay",payload:{id:ye,type:te.type}}),$e==null||$e("played")),je==null||je(!1),pe!=null&&pe("played")&&pe!=null&&pe("ended")&&!(pe!=null&&pe("replayed"))&&(G.eventBus.emit("advertisement",{action:"videoReplayed",payload:{id:ye,type:te.type}}),$e==null||$e("replayed"))},onEnd:()=>{pe!=null&&pe("ended")||(G.eventBus.emit("advertisement",{action:"videoEnd",payload:{id:ye,type:te.type}}),$e==null||$e("ended"))},controlVideo:Ye,autoPlay:Ct,playMuted:Ci,muted:dr}):(O=te.banner)!=null&&O.imageUrl?W.jsx(O0,{style:wi?{aspectRatio:"1/1"}:{},src:(B=te.banner)==null?void 0:B.imageUrl,alt:"promo"}):null}),!wi&&W.jsxs(vc,{children:[((P=te.banner)==null?void 0:P.title)&&W.jsx($0,{className:G.cx_default("AdvTitle",ki&&q0),children:($=te.banner)==null?void 0:$.title}),((Q=te.banner)==null?void 0:Q.body)&&W.jsx(M0,{className:"AdvDescription",children:(K=te.banner)==null?void 0:K.body})]})]})]}),te.buttonType===ce.PromotionButtonType.BASIC&&W.jsx(Dh,{children:W.jsx(Ph,{href:Kt,style:{backgroundColor:((me=(ie=te.banner)==null?void 0:ie.ctaButton)==null?void 0:me.color)||"#009dc4",color:((ge=(oe=te.banner)==null?void 0:oe.ctaButton)==null?void 0:ge.textColor)||"#fff"},"data-a":"button","data-promo-id":ye,"data-promo-type":te.type,target:"_blank",children:(ue=(ee=te.banner)==null?void 0:ee.ctaButton)==null?void 0:ue.label})})]})},tk=G.styled_default("div")({name:"SidebarContainer",class:"s1abskp8",propsAsIs:!1}),ik=({children:i,direction:e,style:t,className:r,hiding:n})=>W.jsx(Tl,{direction:e,style:t,hiding:n,className:r,children:W.jsx(tk,{children:i})}),yh=i=>(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB11_LBAR||(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB21_LBAR,rk=i=>(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB11_SIDEBAR||(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB21_SIDEBAR,nk=i=>(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB11||(i==null?void 0:i.type)===ce.PromotionType.INGAME_IAB21,sk=({advertisement:i,close:e,skipTypeCheck:t,skipAutoClose:r,layoutMode:n="side-by-side",sidebar:s,isNotification:a,banner:l,markAsViewed:u,open:p,externalAd:m,controlVideo:_,advertisementPaused:E,togglePause:S,isEventFired:C,fireEvent:v,muted:L})=>i.promotion?a&&i.notification?W.jsx(P0,{open:()=>p==null?void 0:p({fromNotification:!0}),notification:i.notification,promotionId:i.question.id,close:e}):!s&&!l&&(t||nk(i.promotion))?W.jsx(R0,{className:"PromoOverlayContainer",children:W.jsx(fh,{markAsViewed:u,promotionId:i.question.id,promotion:i.promotion,onClose:e,open:p,skipAutoClose:r,externalAd:m,controlVideo:_,advertisementPaused:E,togglePause:S,isEventFired:C,fireEvent:v,muted:L})}):s&&(t||yh(i.promotion)||rk(i.promotion)||m)?W.jsx(ik,{className:"PromoSidebarContainer",direction:s,hiding:!1,children:W.jsx(fh,{markAsViewed:u,promotionId:i.question.id,promotion:i.promotion,externalAd:m,onClose:e,open:p,controlVideo:_,skipAutoClose:r,advertisementPaused:E,togglePause:S,isEventFired:C,fireEvent:v,muted:L})}):l&&yh(i.promotion)?W.jsx(vh,{promotionId:i.question.id,hiding:!1,promotion:i.promotion,direction:l,isEventFired:C,fireEvent:v}):null:null,_h=G.styled_default("div")({name:"AdvertisementUIWrap",class:"aa6pjif",propsAsIs:!1}),ak=i=>{const e=i.target;if(e instanceof HTMLAnchorElement&&e.target==="_blank"){const t=e.getAttribute("data-promo-id")||"",r=e.getAttribute("data-promo-type")||ce.PromotionType.UNSET;e.getAttribute("data-a")==="button"&&G.eventBus.emit("advertisement",{action:"buttonSelect",payload:{id:t,type:r}}),e.getAttribute("data-a")==="banner"&&G.eventBus.emit("advertisement",{action:"bannerSelect",payload:{id:t,type:r}})}},ok=({gamification:i,advertisement:e,layoutMode:t,skipAutoClose:r,skipTypeCheck:n,sidebar:s,banner:a,notification:l,isMobileScreen:u,persistent:p,containerId:m,externalAd:_,controlVideo:E,muted:S})=>{var C,v,L,D,U,O,B,P,$,Q,K,ie,me,oe,ge,ee,ue,te,de,be,je;const Ye=Se.useRef(null),ve=G.useStore(e.$store),ye=G.useStore(i.openedQuestion.$store);G.b(Ye,{enabled:!!ve.data,event:"click",listener:ak});const kt=((L=(v=(C=ve.data)==null?void 0:C.question)==null?void 0:v.backgroundImage)==null?void 0:L.landscapeUrl)||((U=(D=ve.data)==null?void 0:D.promotion)==null?void 0:U.backgroundImageLandscapeUrl),Pt=((P=(B=(O=ve.data)==null?void 0:O.question)==null?void 0:B.backgroundImage)==null?void 0:P.portraitUrl)||((Q=($=ve.data)==null?void 0:$.promotion)==null?void 0:Q.backgroundImagePortraitUrl),xe=G.y$1({containerId:m,landscapeUrl:kt,portraitUrl:Pt});if(((K=ye==null?void 0:ye.attributes)==null?void 0:K.adUnit)===ce.AdUnit.STANDART&&(oe=(me=(ie=ye==null?void 0:ye.attributes)==null?void 0:ie.adPromotion)==null?void 0:me.banner)!=null&&oe.imageUrl)return a?W.jsx(_h,{ref:Ye,style:{height:"100%"},className:G.cx_default("SL-AdvertisementUIWrap",u&&"mobile-view"),children:W.jsx(q_,{cardId:ye.id,promotion:{...(ge=ye==null?void 0:ye.attributes)==null?void 0:ge.adPromotion,adUnit:(ee=ye==null?void 0:ye.attributes)==null?void 0:ee.adUnit}})}):null;const pe=!a&&!s;if(ve.data===void 0||!p&&ve.isViewed)return null;const $e=((de=(te=(ue=ve==null?void 0:ve.data)==null?void 0:ue.notification)==null?void 0:te.promotion)==null?void 0:de.mode)===ce.NotificationPromotionMode.LOWER_THIRD;return W.jsxs(_h,{ref:Ye,style:{height:pe?"auto":"100%"},className:G.cx_default("SL-AdvertisementUIWrap",u&&"mobile-view",$e&&"SL-AdvertisementUIWrap--lower-third"),children:[!l&&xe,W.jsx(sk,{skipTypeCheck:n,sidebar:s,banner:a,advertisement:ve.data,advertisementPaused:!!ve.isPaused,togglePause:ve.togglePause,isEventFired:ve.isEventFired,toggleMute:ve.toggleMute,fireEvent:ve.fireEvent,close:ve.close,externalAd:_?ve.externalAd:void 0,markAsViewed:(be=i.advertisement)==null?void 0:be.markAsViewed,open:(je=i.advertisement)==null?void 0:je.open,layoutMode:t,isNotification:l,skipAutoClose:r,controlVideo:E,muted:S})]})},ff=({sdk:i,sidebar:e,externalAd:t,banner:r,skipAutoClose:n,skipTypeCheck:s,layoutMode:a,isMobileScreen:l,persistent:u,notification:p,muted:m})=>{const _=G.useStore(i.featuresList.getStore()),[E,S]=Se.useState(!t),C=G.useStore(i.options);if(Se.useEffect(()=>{if(t){const L=document.createElement("script");L.async=!0,L.src="https://imasdk.googleapis.com/pal/sdkloader/pal.js",document.body.appendChild(L),L.onload=()=>{S(!0)}}},[t]),e&&r)return W.jsx("div",{style:{color:"red"},children:"define either sidebar or banner, not both."});if(r&&t)return W.jsx("div",{style:{color:"red"},children:"externalAd is not supported with banner"});if(!_)return null;const v=i.getFeature(ce.SdkOverlayType.GAMES);return!v||t&&!E?null:W.jsx(ok,{gamification:v,advertisement:v.advertisement,sidebar:e,banner:r,layoutMode:a,isMobileScreen:l,persistent:u,notification:p,skipTypeCheck:s,skipAutoClose:n,externalAd:t,controlVideo:i.controlVideoPlayer,containerId:C.containerId,muted:m})},lk=({event:i,sidebar:e,banner:t,isMobileScreen:r,skipAutoClose:n,persistent:s,theme:a,notification:l,skipTypeCheck:u,externalAd:p,muted:m=!1})=>{const _=G.useStreamLayer(),E=G.useStreamLayerUI(),S=G.useStreamLayerTheme();return _?p&&!E.promotionExternalAd?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):!p&&E.promotionExternalAd?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):e&&!E.promotionSidebar?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):t&&!E.promotionBanner?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):l&&!E.promotionNotification?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):!t&&!e&&!l&&!E.promotionOverlay&&!u?i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i}):W.jsxs("div",{className:"StreamLayerSDK",children:[W.jsx(G.h,{customTheme:a??S.theme,themeMode:S.themeMode,children:W.jsx(ff,{sdk:_,sidebar:e,banner:t,isMobileScreen:r,persistent:s,notification:l,skipTypeCheck:u,skipAutoClose:n,layoutMode:"side-by-side",externalAd:p,muted:m})}),i!==void 0&&W.jsx(G.StreamLayerSDKEvent,{event:i})]}):null};exports.StreamLayerSDKAdvertisement=lk;exports.StreamLayerSDKAdvertisementUI=ff;