p)continue}else if(0>=p+Db)continue;return{partIndex:e.partIndex,segmentIndex:e.segmentIndex,startTime:g-sd({defaultDuration:a.targetDuration,durationList:t,startIndex:x,endIndex:c})}}return{partIndex:t[0]&&t[0].partIndex||null,segmentIndex:t[0]&&t[0].segmentIndex||0,startTime:b}}if(0>x){for(;0>x;x++)if(p-=a.targetDuration,0>p)return{partIndex:t[0]&&t[0].partIndex||
null,segmentIndex:t[0]&&t[0].segmentIndex||0,startTime:b};x=0}for(c=x;cDb&&0<=p+Db,0!==p&&!y||c===t.length-1){if(l){if(0`placeholder-uri-${a}-${b}-${c}`,qp=({onwarn:a,oninfo:b,manifestString:c,customTagParsers:e=[],customTagMappers:g=[],
llhls:l})=>{const p=new jn;if(a)p.on("warn",a);if(b)p.on("info",b);e.forEach(x=>p.addParser(x));g.forEach(x=>p.addTagMapper(x));p.push(c);p.end();const t=p.manifest;l||("preloadSegment skip serverControl renditionReports partInf partTargetDuration".split(" ").forEach(function(x){t.hasOwnProperty(x)&&delete t[x]}),t.segments&&t.segments.forEach(function(x){["parts","preloadHints"].forEach(function(y){x.hasOwnProperty(y)&&delete x[y]})}));t.targetDuration||(b=10,t.segments&&t.segments.length&&(b=t.segments.reduce((x,
y)=>Math.max(x,y.duration),0)),a&&a({message:`manifest has no targetDuration defaulting to ${b}`}),t.targetDuration=b);b=Bk(t);b.length&&!t.partTargetDuration&&(b=b.reduce((x,y)=>Math.max(x,y.duration),0),a&&(a({message:`manifest has no partTargetDuration defaulting to ${b}`}),Kk.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),t.partTargetDuration=
b);return t},Qc=(a,b)=>{a.mediaGroups&&["AUDIO","SUBTITLES"].forEach(c=>{if(a.mediaGroups[c])for(const e in a.mediaGroups[c])for(const g in a.mediaGroups[c][e])b(a.mediaGroups[c][e][g],c,e,g)})},Mk=({playlist:a,uri:b,id:c})=>{a.id=c;a.playlistErrors_=0;b&&(a.uri=b);a.attributes=a.attributes||{}},rp=a=>{let b=a.playlists.length;for(;b--;){const c=a.playlists[b];Mk({playlist:c,id:`${b}-${c.uri}`});c.resolvedUri=Ja(a.uri,c.uri);a.playlists[c.id]=c;a.playlists[c.uri]=c;c.attributes.BANDWIDTH||Kk.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},
sp=a=>{Qc(a,b=>{b.uri&&(b.resolvedUri=Ja(a.uri,b.uri))})},tp=(a,b)=>{a=`${0}-${b}`;const c={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:D.location.href,resolvedUri:D.location.href,playlists:[{uri:b,id:a,resolvedUri:b,attributes:{}}]};c.playlists[a]=c.playlists[0];c.playlists[b]=c.playlists[0];return c},Nk=(a,b,c=Lk)=>{a.uri=b;for(b=0;b{if(!g.playlists||!g.playlists.length){if(e&&
"AUDIO"===l&&!g.uri)for(let x=0;x{c.set(e.id,e);return c},new Map)}}processDateRange(a){this.pendingDateRanges_.delete(a.id);this.processedDateRanges_.set(a.id,a)}getDateRangesToProcess(){if(null===this.offset_)return[];const a={},b=
[];this.pendingDateRanges_.forEach((c,e)=>{this.processedDateRanges_.has(e)||(c.startTime=c.startDate.getTime()/1E3-this.offset_,c.processDateRange=()=>this.processDateRange(c),b.push(c),c.class&&(a[c.class]?(e=a[c.class].push(c),c.classListIndex=e-1):(a[c.class]=[c],c.classListIndex=0)))});for(const c of b){const e=a[c.class]||[];c.endTime=c.endDate?c.endDate.getTime()/1E3-this.offset_:c.endOnNext&&e[c.classListIndex+1]?e[c.classListIndex+1].startTime:c.duration?c.startTime+c.duration:c.plannedDuration?
c.startTime+c.plannedDuration:c.startTime}return b}trimProcessedDateRanges_(a){(new Map(this.processedDateRanges_)).forEach((b,c)=>{b.startDate.getTime(){if(b.endList||!b.serverControl)return a;const c={};if(b.serverControl.canBlockReload){var {preloadSegment:e}=b;let g=b.mediaSequence+b.segments.length;if(e){e=e.parts||[];const l=Ck(b)-1;-1{a=a.slice();b=b.slice();c=c||0;const e=[];let g;for(let y=0;y{!a.resolvedUri&&a.uri&&(a.resolvedUri=Ja(b,a.uri));a.key&&!a.key.resolvedUri&&(a.key.resolvedUri=Ja(b,a.key.uri));a.map&&!a.map.resolvedUri&&(a.map.resolvedUri=Ja(b,a.map.uri));a.map&&a.map.key&&!a.map.key.resolvedUri&&
(a.map.key.resolvedUri=Ja(b,a.map.key.uri));a.parts&&a.parts.length&&a.parts.forEach(c=>{c.resolvedUri||(c.resolvedUri=Ja(b,c.uri))});a.preloadHints&&a.preloadHints.length&&a.preloadHints.forEach(c=>{c.resolvedUri||(c.resolvedUri=Ja(b,c.uri))})},Qk=function(a){const b=a.segments||[],c=a.preloadSegment;if(c&&c.parts&&c.parts.length){if(c.preloadHints)for(let e=0;ea===b||a.segments&&b.segments&&a.segments.length===b.segments.length&&a.endList===b.endList&&a.mediaSequence===b.mediaSequence&&a.preloadSegment===b.preloadSegment,Lg=(a,b,c=Rk)=>{const e=ia(a,{});var g=e.playlists[b.id];if(!g||c(g,b))return null;b.segments=Qk(b);const l=ia(g,b);l.preloadSegment&&!b.preloadSegment&&delete l.preloadSegment;if(g.segments){if(b.skip)for(b.segments=b.segments||[],c=0;c{Pk(p,l.resolvedUri)});for(g=0;g{if(p.playlists)for(t=0;t{var c=a.segments||[];const e=(c=c[c.length-1])&&c.parts&&c.parts[c.parts.length-1];c=e&&e.duration||c&&c.duration;return b&&c?1E3*c:500*(a.partTargetDuration||a.targetDuration||
10)};class Rc extends up{constructor(a,b,c={}){super();if(!a)throw Error("A non-empty playlist URL or object is required");this.logger_=mb("PlaylistLoader");const {withCredentials:e=!1}=c;this.src=a;this.vhs_=b;this.withCredentials=e;this.addDateRangesToTextTrack_=c.addDateRangesToTextTrack;this.customTagParsers=(a=b.options_)&&a.customTagParsers||[];this.customTagMappers=a&&a.customTagMappers||[];this.llhls=a&&a.llhls;this.dateRangesStorage_=new Ok;this.state="HAVE_NOTHING";this.handleMediaupdatetimeout_=
this.handleMediaupdatetimeout_.bind(this);this.on("mediaupdatetimeout",this.handleMediaupdatetimeout_);this.on("loadedplaylist",this.handleLoadedPlaylist_.bind(this))}handleLoadedPlaylist_(){var a=this.media();a&&(this.dateRangesStorage_.setOffset(a.segments),this.dateRangesStorage_.setPendingDateRanges(a.dateRanges),a=this.dateRangesStorage_.getDateRangesToProcess(),a.length&&this.addDateRangesToTextTrack_&&this.addDateRangesToTextTrack_(a))}handleMediaupdatetimeout_(){if("HAVE_METADATA"===this.state){var a=
this.media(),b=Ja(this.main.uri,a.uri);this.llhls&&(b=vp(b,a));this.state="HAVE_CURRENT_METADATA";this.request=this.vhs_.xhr({uri:b,withCredentials:this.withCredentials,requestType:"hls-playlist"},(c,e)=>{if(this.request){if(c)return this.playlistRequestError(this.request,this.media(),"HAVE_METADATA");this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})}})}}playlistRequestError(a,b,c){const {uri:e,id:g}=b;this.request=null;c&&(this.state=c);this.error=
{playlist:this.main.playlists[g],status:a.status,message:`HLS playlist request error at URL: ${e}.`,responseText:a.responseText,code:500<=a.status?4:2,metadata:{errorType:H.Error.HlsPlaylistRequestError}};this.trigger("error")}parseManifest_({url:a,manifestString:b}){return qp({onwarn:({message:c})=>this.logger_(`m3u8-parser warn for ${a}: ${c}`),oninfo:({message:c})=>this.logger_(`m3u8-parser info for ${a}: ${c}`),manifestString:b,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,
llhls:this.llhls})}haveMetadata({playlistString:a,playlistObject:b,url:c,id:e}){this.request=null;this.state="HAVE_METADATA";a=b||this.parseManifest_({url:c,manifestString:a});a.lastRequest=Date.now();Mk({playlist:a,uri:c,id:e});c=Lg(this.main,a);this.targetDuration=a.partTargetDuration||a.targetDuration;this.pendingMedia_=null;c?(this.main=c,this.media_=this.main.playlists[e]):this.trigger("playlistunchanged");this.updateMediaUpdateTimeout_(Mg(this.media(),!!c));this.trigger("loadedplaylist")}dispose(){this.trigger("dispose");
this.stopRequest();D.clearTimeout(this.mediaUpdateTimeout);D.clearTimeout(this.finalRenditionTimeout);this.dateRangesStorage_=new Ok;this.off()}stopRequest(){if(this.request){const a=this.request;this.request=null;a.onreadystatechange=null;a.abort()}}media(a,b){if(!a)return this.media_;if("HAVE_NOTHING"===this.state)throw Error("Cannot switch media playlist from "+this.state);if("string"===typeof a){if(!this.main.playlists[a])throw Error("Unknown playlist URI: "+a);a=this.main.playlists[a]}D.clearTimeout(this.finalRenditionTimeout);
if(b)b=(a.partTargetDuration||a.targetDuration)/2*1E3||5E3,this.finalRenditionTimeout=D.setTimeout(this.media.bind(this,a,!1),b);else{var c=this.state;b=!this.media_||a.id!==this.media_.id;var e=this.main.playlists[a.id];if(e&&e.endList||a.endList&&a.segments.length)this.request&&(this.request.onreadystatechange=null,this.request.abort(),this.request=null),this.state="HAVE_METADATA",this.media_=a,b&&(this.trigger("mediachanging"),"HAVE_MAIN_MANIFEST"===c?this.trigger("loadedmetadata"):this.trigger("mediachange"));
else if(this.updateMediaUpdateTimeout_(Mg(a,!0)),b){this.state="SWITCHING_MEDIA";if(this.request){if(a.resolvedUri===this.request.url)return;this.request.onreadystatechange=null;this.request.abort();this.request=null}this.media_&&this.trigger("mediachanging");this.pendingMedia_=a;this.request=this.vhs_.xhr({uri:a.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},(g,l)=>{if(this.request){a.lastRequest=Date.now();a.resolvedUri=ye(a.resolvedUri,l);if(g)return this.playlistRequestError(this.request,
a,c);this.haveMetadata({playlistString:l.responseText,url:a.uri,id:a.id});"HAVE_MAIN_MANIFEST"===c?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}}}pause(){this.mediaUpdateTimeout&&(D.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);this.stopRequest();"HAVE_NOTHING"===this.state&&(this.started=!1);"SWITCHING_MEDIA"===this.state?this.state=this.media_?"HAVE_METADATA":"HAVE_MAIN_MANIFEST":"HAVE_CURRENT_METADATA"===this.state&&(this.state="HAVE_METADATA")}load(a){this.mediaUpdateTimeout&&
(D.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const b=this.media();a?this.mediaUpdateTimeout=D.setTimeout(()=>{this.mediaUpdateTimeout=null;this.load()},b?(b.partTargetDuration||b.targetDuration)/2*1E3:5E3):this.started?b&&!b.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist"):this.start()}updateMediaUpdateTimeout_(a){this.mediaUpdateTimeout&&(D.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);this.media()&&!this.media().endList&&(this.mediaUpdateTimeout=
D.setTimeout(()=>{this.mediaUpdateTimeout=null;this.trigger("mediaupdatetimeout");this.updateMediaUpdateTimeout_(a)},a))}start(){this.started=!0;"object"===typeof this.src?(this.src.uri||(this.src.uri=D.location.href),this.src.resolvedUri=this.src.uri,setTimeout(()=>{this.setupInitialPlaylist(this.src)},0)):this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials,requestType:"hls-playlist"},(a,b)=>{if(this.request){this.request=null;if(a)return this.error={status:b.status,message:`HLS playlist request error at URL: ${this.src}.`,
responseText:b.responseText,code:2,metadata:{errorType:H.Error.HlsPlaylistRequestError}},"HAVE_NOTHING"===this.state&&(this.started=!1),this.trigger("error");this.src=ye(this.src,b);a=this.parseManifest_({manifestString:b.responseText,url:this.src});this.setupInitialPlaylist(a)}})}srcUri(){return"string"===typeof this.src?this.src:this.src.uri}setupInitialPlaylist(a){this.state="HAVE_MAIN_MANIFEST";if(a.playlists)this.main=a,Nk(this.main,this.srcUri()),a.playlists.forEach(c=>{c.segments=Qk(c);c.segments.forEach(e=>
{Pk(e,c.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);else{var b=this.srcUri()||D.location.href;this.main=tp(a,b);this.haveMetadata({playlistObject:a,url:b,id:this.main.playlists[0].id});this.trigger("loadedmetadata")}}updateOrDeleteClone(a,b){const c=this.main,e=a.ID;let g=c.playlists.length;for(;g--;){var l=c.playlists[g];if(l.attributes["PATHWAY-ID"]===e){const p=l.resolvedUri,t=l.id;if(b){const x=this.createCloneURI_(l.resolvedUri,a),y=`${e}-${x}`,
A=this.createCloneAttributes_(e,l.attributes);l=this.createClonePlaylist_(l,y,a,A);c.playlists[g]=l;c.playlists[y]=l;c.playlists[x]=l}else c.playlists.splice(g,1);delete c.playlists[t];delete c.playlists[p]}}this.updateOrDeleteCloneMedia(a,b)}updateOrDeleteCloneMedia(a,b){const c=this.main,e=a.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(g=>{if(c.mediaGroups[g]&&c.mediaGroups[g][e])for(const l in c.mediaGroups[g])if(l===e){for(const p in c.mediaGroups[g][l])c.mediaGroups[g][l][p].playlists.forEach((t,
x)=>{t=c.playlists[t.id];x=t.resolvedUri;delete c.playlists[t.id];delete c.playlists[x]});delete c.mediaGroups[g][l]}});b&&this.createClonedMediaGroups_(a)}addClonePathway(a,b={}){const c=this.main,e=c.playlists.length,g=this.createCloneURI_(b.resolvedUri,a),l=`${a.ID}-${g}`,p=this.createCloneAttributes_(a.ID,b.attributes);b=this.createClonePlaylist_(b,l,a,p);c.playlists[e]=b;c.playlists[l]=b;c.playlists[g]=b;this.createClonedMediaGroups_(a)}createClonedMediaGroups_(a){const b=a.ID,c=a["BASE-ID"],
e=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(g=>{if(e.mediaGroups[g]&&!e.mediaGroups[g][b])for(const l in e.mediaGroups[g])if(l===c){e.mediaGroups[g][b]={};for(const p in e.mediaGroups[g][l]){const t=e.mediaGroups[g][l][p];e.mediaGroups[g][b][p]=nb({},t);const x=e.mediaGroups[g][b][p],y=this.createCloneURI_(t.resolvedUri,a);x.resolvedUri=y;x.uri=y;x.playlists=[];t.playlists.forEach((A,z)=>{var E=e.playlists[A.id],I=Lk(g,b,p);I=`${b}-${I}`;if(E&&!e.playlists[I]){E=this.createClonePlaylist_(E,
I,a);const G=E.resolvedUri;e.playlists[I]=E;e.playlists[G]=E}x.playlists[z]=this.createClonePlaylist_(A,I,a)})}}})}createClonePlaylist_(a,b,c,e){c=this.createCloneURI_(a.resolvedUri,c);b={resolvedUri:c,uri:c,id:b};a.segments&&(b.segments=[]);e&&(b.attributes=e);return ia(a,b)}createCloneURI_(a,b){a=new URL(a);a.hostname=b["URI-REPLACEMENT"].HOST;b=b["URI-REPLACEMENT"].PARAMS;for(const c of Object.keys(b))a.searchParams.set(c,b[c]);return a.href}createCloneAttributes_(a,b){const c={["PATHWAY-ID"]:a};
["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{b[e]&&(c[e]=a)});return c}getKeyIdSet(a){if(a.contentProtection){const b=new Set;for(const c in a.contentProtection){const e=a.contentProtection[c].attributes.keyId;e&&b.add(e.toLowerCase())}return b}}}const Ng=function(a,b,c,e){const g="arraybuffer"===a.responseType?a.response:a.responseText;!b&&g&&(a.responseTime=Date.now(),a.roundTripTime=a.responseTime-a.requestTime,a.bytesReceived=g.byteLength||g.length,a.bandwidth||(a.bandwidth=Math.floor(a.bytesReceived/
a.roundTripTime*8E3)));c.headers&&(a.responseHeaders=c.headers);b&&"ETIMEDOUT"===b.code&&(a.timedout=!0);b||a.aborted||200===c.statusCode||206===c.statusCode||0===c.statusCode||(b=Error("XHR Failed with a response of: "+(a&&(g||a.responseText))));e(b,a)},xp=(a,b)=>{if(a&&a.size){var c=b;a.forEach(e=>{c=e(c)});return c}},yp=(a,b,c,e)=>{a&&a.size&&a.forEach(g=>{g(b,c,e)})},Sk=function(){const a=function g(c,e){c=ia({timeout:45E3},c);const l=g.beforeRequest||H.Vhs.xhr.beforeRequest,p=g._requestCallbackSet||
H.Vhs.xhr._requestCallbackSet||new Set,t=g._responseCallbackSet||H.Vhs.xhr._responseCallbackSet;l&&"function"===typeof l&&(H.log.warn("beforeRequest is deprecated, use onRequest instead."),p.add(l));const x=!0===H.Vhs.xhr.original?H.xhr:H.Vhs.xhr,y=xp(p,c);p.delete(l);const A=x(y||c,function(E,I){yp(t,A,E,I);return Ng(A,E,I,e)}),z=A.abort;A.abort=function(){A.aborted=!0;return z.apply(A,arguments)};A.uri=c.uri;A.requestTime=Date.now();return A};a.original=!0;return a},Og=function(a){const b={};if(a.byterange){var c=
a.byterange;a=c.offset;c="bigint"===typeof c.offset||"bigint"===typeof c.length?D.BigInt(c.offset)+D.BigInt(c.length)-D.BigInt(1):c.offset+c.length-1;b.Range="bytes\x3d"+a+"-"+c}return b},zp=function(a,b){a=a.toString(16);return"00".substring(0,2-a.length)+a+(b%2?" ":"")},Ap=function(a){return 32<=a&&126>a?String.fromCharCode(a):"."},Tk=function(a){const b={};Object.keys(a).forEach(c=>{const e=a[c];Oi(e)?b[c]={bytes:e.buffer,byteOffset:e.byteOffset,byteLength:e.byteLength}:b[c]=e});return b},Be=function(a){const b=
a.byterange||{length:Infinity,offset:0};return[b.length,b.offset,a.resolvedUri].join()},Uk=a=>{a=Array.prototype.slice.call(a);let b="",c,e;for(let g=0;gUk(a),textRanges:a=>{var b="";let c;for(c=0;c{let c;try{c=new Date(a)}catch(p){return null}if(!b||!b.segments||0===b.segments.length)return null;a=b.segments[0];if(cl)return null;c>new Date(g)&&(a=e);return{segment:a,estimatedStart:a.videoTimingInfo?a.videoTimingInfo.transmuxedPresentationStart:Ya.duration(b,b.mediaSequence+b.segments.indexOf(a)),type:a.videoTimingInfo?"accurate":"estimate"}},Dp=(a,b)=>{if(!b||!b.segments||0===b.segments.length)return null;let c=0,e;for(let g=0;gc){if(a>c+.25*b.duration)return null;e=b}return{segment:e,estimatedStart:e.videoTimingInfo?e.videoTimingInfo.transmuxedPresentationStart:c-e.duration,type:e.videoTimingInfo?"accurate":"estimate"}},Ep=(a,b)=>{let c,e;try{c=new Date(a),e=new Date(b)}catch(g){}a=c.getTime();return(e.getTime()-a)/1E3},Fp=a=>{if(!a.segments||0===a.segments.length)return!1;for(let b=0;b{if(!c)throw Error("getProgramTime: callback must be provided");if(!a||void 0===b)return c({message:"getProgramTime: playlist and time must be provided"});var e=Dp(b,a);if(!e)return c({message:"valid programTime was not found"});if("estimate"===e.type)return c({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:e.estimatedStart});a={mediaSeconds:b};e=e.segment;e.dateTimeObject?(b-=e.videoTimingInfo.transmuxedPresentationStart+
e.videoTimingInfo.transmuxerPrependedSeconds,b=new Date(e.dateTimeObject.getTime()+1E3*b)):b=null;b&&(a.programDateTime=b.toISOString());return c(null,a)},Vk=({programTime:a,playlist:b,retryCount:c=2,seekTo:e,pauseAfterSeek:g=!0,tech:l,callback:p})=>{if(!p)throw Error("seekToProgramTime: callback must be provided");if("undefined"===typeof a||!b||!e)return p({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!b.endList&&!l.hasStarted_)return p({message:"player must be playing a live stream to start buffering"});
if(!Fp(b))return p({message:"programDateTime tags must be provided in the manifest "+b.resolvedUri});var t=Cp(a,b);if(!t)return p({message:`${a} was not found in the stream`});const x=t.segment,y=Ep(x.dateTimeObject,a);if("estimate"===t.type){if(0===c)return p({message:`${a} is not buffered yet. Try again`});e(t.estimatedStart+y);l.one("seeked",()=>{Vk({programTime:a,playlist:b,retryCount:c-1,seekTo:e,pauseAfterSeek:g,tech:l,callback:p})})}else t=x.start+y,l.one("seeked",()=>p(null,l.currentTime())),
g&&l.pause(),e(t)},Wk=(a,b)=>{if(4===a.readyState)return b()},Hp=(a,b,c)=>{let e=[],g,l=!1;const p=function(y,A,z,E){A.abort();l=!0;return c(y,A,z,E)},t=function(y,A){if(!l){if(y)return p(y,A,"",e);var z=A.responseText.substring(e&&e.byteLength||0,A.responseText.length);e=rn(e,Pi(z,!0));g=g||kd(e);if(10>e.length||g&&e.lengthp(y,A,"",e));z=Vf(e);return"ts"===z&&188>e.length||!z&&376>e.length?Wk(A,()=>p(y,A,"",e)):p(null,A,z,e)}},x=b({uri:a,beforeSend(y){y.overrideMimeType("text/plain; charset\x3dx-user-defined");
y.addEventListener("progress",function({}){return Ng(y,null,{statusCode:y.status},t)})}},function(y,A){return Ng(x,y,A,t)});return x},{EventTarget:Ip}=H,Xk=function(a,b){if(!Rk(a,b)||a.sidx&&b.sidx&&(a.sidx.offset!==b.sidx.offset||a.sidx.length!==b.sidx.length)||!a.sidx&&b.sidx||a.sidx&&!b.sidx||a.segments&&!b.segments||!a.segments&&b.segments)return!1;if(!a.segments&&!b.segments)return!0;for(let g=0;g`placeholder-uri-${a}-${b}-${e.attributes.NAME||c}`,Kp=({mainXml:a,srcUrl:b,clientOffset:c,sidxMapping:e,previousManifest:g})=>{a=io(a,{manifestUri:b,clientOffset:c,sidxMapping:e,previousManifest:g});Nk(a,b,Jp);return a},Lp=(a,b)=>{Qc(a,(c,e,g,l)=>{l in b.mediaGroups[e][g]||delete a.mediaGroups[e][g][l]})},Mp=(a,b,c)=>{let e=!0,g=ia(a,{duration:b.duration,minimumUpdatePeriod:b.minimumUpdatePeriod,
timelineStarts:b.timelineStarts});for(let p=0;p{if(p.playlists&&p.playlists.length){const A=p.playlists[0].id,z=Lg(g,p.playlists[0],Xk);z&&(g=z,y in g.mediaGroups[t][x]||(g.mediaGroups[t][x][y]=p),g.mediaGroups[t][x][y].playlists[0]=g.playlists[A],e=!1)}});Lp(g,b);b.minimumUpdatePeriod!==a.minimumUpdatePeriod&&(e=!1);return e?null:
g},Yk=(a,b)=>{const c={};for(const e in a){const g=a[e].sidx;if(g){const l=de(g);if(!b[l])break;const p=b[l].sidxInfo;(!p.map&&!g.map||p.map&&g.map&&p.map.byterange.offset===g.map.byterange.offset&&p.map.byterange.length===g.map.byterange.length)&&p.uri===g.uri&&p.byterange.offset===g.byterange.offset&&p.byterange.length===g.byterange.length&&(c[l]=b[l])}}return c},Np=(a,b)=>{let c=Yk(a.playlists,b);Qc(a,(e,g,l,p)=>{e.playlists&&e.playlists.length&&(c=ia(c,Yk(e.playlists,b)))});return c};class Pg extends Ip{constructor(a,
b,c={},e){super();this.mainPlaylistLoader_=e||this;e||(this.isMain_=!0);({withCredentials:e=!1}=c);this.vhs_=b;this.withCredentials=e;this.addMetadataToTextTrack=c.addMetadataToTextTrack;if(!a)throw Error("A non-empty playlist URL or object is required");this.on("minimumUpdatePeriod",()=>{this.refreshXml_()});this.on("mediaupdatetimeout",()=>{this.refreshMedia_(this.media().id)});this.state="HAVE_NOTHING";this.loadedPlaylists_={};this.logger_=mb("DashPlaylistLoader");this.isMain_?(this.mainPlaylistLoader_.srcUrl=
a,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=a}requestErrored_(a,b,c){if(!this.request)return!0;this.request=null;if(a)return this.error="object"!==typeof a||a instanceof Error?{status:b.status,message:"DASH request error at URL: "+b.uri,response:b.response,code:2,metadata:a.metadata}:a,c&&(this.state=c),this.trigger("error"),!0}addSidxSegments_(a,b,c){const e=a.sidx&&de(a.sidx);if(a.sidx&&e&&!this.mainPlaylistLoader_.sidxMapping_[e]){var g=ye(a.sidx.resolvedUri),l=(p,t)=>{if(!this.requestErrored_(p,
t,b)){p=this.mainPlaylistLoader_.sidxMapping_;try{var x=ko(U(t.response).subarray(8))}catch(y){y.metadata={errorType:H.Error.DashManifestSidxParsingError};this.requestErrored_(y,t,b);return}p[e]={sidxInfo:a.sidx,sidx:x};Pf(a,x,a.sidx.resolvedUri);return c(!0)}};this.request=Hp(g,this.vhs_.xhr,(p,t,x,y)=>{if(p)return l(p,t);if(!x||"mp4"!==x)return p=x||"unknown",l({status:t.status,message:`Unsupported ${p} container type for sidx segment at URL: ${g}`,response:"",playlist:a,internal:!0,playlistExclusionDuration:Infinity,
code:2,metadata:{errorType:H.Error.UnsupportedSidxContainer,sidxContainer:p}},t);const {offset:A,length:z}=a.sidx.byterange;if(y.length>=z+A)return l(p,{response:y.subarray(A,A+z),status:t.status,uri:t.uri});this.request=this.vhs_.xhr({uri:g,responseType:"arraybuffer",headers:Og({byterange:a.sidx.byterange})},l)})}else this.mediaRequest_=D.setTimeout(()=>c(!1),0)}dispose(){this.trigger("dispose");this.stopRequest();this.loadedPlaylists_={};D.clearTimeout(this.minimumUpdatePeriodTimeout_);D.clearTimeout(this.mediaRequest_);
D.clearTimeout(this.mediaUpdateTimeout);this.minimumUpdatePeriodTimeout_=this.mediaRequest_=this.mediaUpdateTimeout=null;this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null);this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){const a=this.request;this.request=null;a.onreadystatechange=null;a.abort()}}media(a){if(!a)return this.media_;if("HAVE_NOTHING"===
this.state)throw Error("Cannot switch media playlist from "+this.state);const b=this.state;if("string"===typeof a){if(!this.mainPlaylistLoader_.main.playlists[a])throw Error("Unknown playlist URI: "+a);a=this.mainPlaylistLoader_.main.playlists[a]}const c=!this.media_||a.id!==this.media_.id;c&&this.loadedPlaylists_[a.id]&&this.loadedPlaylists_[a.id].endList?(this.state="HAVE_METADATA",this.media_=a,c&&(this.trigger("mediachanging"),this.trigger("mediachange"))):c&&(this.media_&&this.trigger("mediachanging"),
this.addSidxSegments_(a,b,e=>{this.haveMetadata({startingState:b,playlist:a})}))}haveMetadata({startingState:a,playlist:b}){this.state="HAVE_METADATA";this.loadedPlaylists_[b.id]=b;this.mediaRequest_=null;this.refreshMedia_(b.id);"HAVE_MAIN_MANIFEST"===a?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null);this.stopRequest();
D.clearTimeout(this.mediaUpdateTimeout);this.mediaUpdateTimeout=null;this.isMain_&&(D.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null);"HAVE_NOTHING"===this.state&&(this.started=!1)}load(a){D.clearTimeout(this.mediaUpdateTimeout);this.mediaUpdateTimeout=null;const b=this.media();a?this.mediaUpdateTimeout=D.setTimeout(()=>this.load(),b?b.targetDuration/2*1E3:5E3):this.started?b&&!b.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&
(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist"):this.start()}start(){this.started=!0;this.isMain_?this.requestMain_((a,b)=>{this.haveMain_();this.hasPendingRequest()||this.media_||this.media(this.mainPlaylistLoader_.main.playlists[0])}):this.mediaRequest_=D.setTimeout(()=>this.haveMain_(),0)}requestMain_(a){this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,
requestType:"dash-manifest"},(b,c)=>{if(this.requestErrored_(b,c))"HAVE_NOTHING"===this.state&&(this.started=!1);else{var e=c.responseText!==this.mainPlaylistLoader_.mainXml_;this.mainPlaylistLoader_.mainXml_=c.responseText;this.mainLoaded_=c.responseHeaders&&c.responseHeaders.date?Date.parse(c.responseHeaders.date):Date.now();this.mainPlaylistLoader_.srcUrl=ye(this.mainPlaylistLoader_.srcUrl,c);if(e)this.handleMain_(),this.syncClientServerClock_(()=>a(c,e));else return a(c,e)}})}syncClientServerClock_(a){const b=
ho(gj(this.mainPlaylistLoader_.mainXml_));if(null===b)return this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),a();if("DIRECT"===b.method)return this.mainPlaylistLoader_.clientOffset_=b.value-Date.now(),a();this.request=this.vhs_.xhr({uri:Ja(this.mainPlaylistLoader_.srcUrl,b.value),method:b.method,withCredentials:this.withCredentials,requestType:"dash-clock-sync"},(c,e)=>{if(this.request){if(c)return this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),a();c="HEAD"===
b.method?e.responseHeaders&&e.responseHeaders.date?Date.parse(e.responseHeaders.date):this.mainLoaded_:Date.parse(e.responseText);this.mainPlaylistLoader_.clientOffset_=c-Date.now();a()}})}haveMain_(){this.state="HAVE_MAIN_MANIFEST";this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){this.mediaRequest_=null;const a=this.mainPlaylistLoader_.main;let b=Kp({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,
sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:a});a&&(b=Mp(a,b,this.mainPlaylistLoader_.sidxMapping_));this.mainPlaylistLoader_.main=b?b:a;const c=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];c&&c!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=c);(!a||b&&b.minimumUpdatePeriod!==a.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_();this.addEventStreamToMetadataTrack_(b);return!!b}updateMinimumUpdatePeriodTimeout_(){const a=
this.mainPlaylistLoader_;a.createMupOnMedia_&&(a.off("loadedmetadata",a.createMupOnMedia_),a.createMupOnMedia_=null);a.minimumUpdatePeriodTimeout_&&(D.clearTimeout(a.minimumUpdatePeriodTimeout_),a.minimumUpdatePeriodTimeout_=null);let b=a.main&&a.main.minimumUpdatePeriod;0===b&&(a.media()?b=1E3*a.media().targetDuration:(a.createMupOnMedia_=a.updateMinimumUpdatePeriodTimeout_,a.one("loadedmetadata",a.createMupOnMedia_)));"number"!==typeof b||0>=b?0>b&&this.logger_(`found invalid minimumUpdatePeriod of ${b}, not setting a timeout`):
this.createMUPTimeout_(b)}createMUPTimeout_(a){const b=this.mainPlaylistLoader_;b.minimumUpdatePeriodTimeout_=D.setTimeout(()=>{b.minimumUpdatePeriodTimeout_=null;b.trigger("minimumUpdatePeriod");b.createMUPTimeout_(a)},a)}refreshXml_(){this.requestMain_((a,b)=>{b&&(this.media_&&(this.media_=this.mainPlaylistLoader_.main.playlists[this.media_.id]),this.mainPlaylistLoader_.sidxMapping_=Np(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.sidxMapping_),this.addSidxSegments_(this.media(),this.state,
c=>{this.refreshMedia_(this.media().id)}))})}refreshMedia_(a){if(!a)throw Error("refreshMedia_ must take a media id");this.media_&&this.isMain_&&this.handleMain_();const b=this.mainPlaylistLoader_.main.playlists,c=!this.media_||this.media_!==b[a];c?this.media_=b[a]:this.trigger("playlistunchanged");if(!this.mediaUpdateTimeout){const e=()=>{this.media().endList||(this.mediaUpdateTimeout=D.setTimeout(()=>{this.trigger("mediaupdatetimeout");e()},Mg(this.media(),!!c)))};e()}this.trigger("loadedplaylist")}addEventStreamToMetadataTrack_(a){a&&
this.mainPlaylistLoader_.main.eventStream&&(a=this.mainPlaylistLoader_.main.eventStream.map(b=>({cueTime:b.start,frames:[{data:b.messageData}]})),this.addMetadataToTextTrack("EventStream",a,this.mainPlaylistLoader_.main.duration))}getKeyIdSet(a){if(a.contentProtection){const b=new Set;for(const c in a.contentProtection){const e=a.contentProtection[c].attributes["cenc:default_KID"];e&&b.add(e.replace(/-/g,"").toLowerCase())}return b}}}var Ha={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,BACK_BUFFER_LENGTH:30,
GOAL_BUFFER_LENGTH_RATE:1,INITIAL_BANDWIDTH:4194304,BANDWIDTH_VARIANCE:1.2,BUFFER_LOW_WATER_LINE:0,MAX_BUFFER_LOW_WATER_LINE:30,EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:16,BUFFER_LOW_WATER_LINE_RATE:1,BUFFER_HIGH_WATER_LINE:30};const Zk=function(a){a.on=a.addEventListener;a.off=a.removeEventListener;return a},Op=function(a){try{return URL.createObjectURL(new Blob([a],{type:"application/javascript"}))}catch(b){const c=new BlobBuilder;c.append(a);return URL.createObjectURL(c.getBlob())}},$k=function(a){return function(){const b=
Op(a),c=Zk(new Worker(b));c.objURL=b;const e=c.terminate;c.on=c.addEventListener;c.off=c.removeEventListener;c.terminate=function(){URL.revokeObjectURL(b);return e.call(this)};return c}},al=function(a){return`var browserWorkerPolyFill = ${Zk.toString()};\n`+"browserWorkerPolyFill(self);\n"+a},bl=function(a){return a.toString().replace(/^function.+?{/,"").slice(0,-1)},wq=al(bl(function(){var a="undefined"!==typeof globalThis?globalThis:"undefined"!==typeof window?window:"undefined"!==typeof global?
global:"undefined"!==typeof self?self:{},b=function(){this.init=function(){var h={};this.on=function(m,r){h[m]||(h[m]=[]);h[m]=h[m].concat(r)};this.off=function(m,r){if(!h[m])return!1;r=h[m].indexOf(r);h[m]=h[m].slice();h[m].splice(r,1);return-1>>1,h.samplingfrequencyindex<<7|h.channelcount<<3,6,1,2]))};var Fa=function(){return K(p.ftyp,t,x,t,y)};var W=function(h){return K(p.hdlr,
E[h])};var Da=function(h){var m=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,h.duration>>>24&255,h.duration>>>16&255,h.duration>>>8&255,h.duration&255,85,196,0,0]);h.samplerate&&(m[12]=h.samplerate>>>24&255,m[13]=h.samplerate>>>16&255,m[14]=h.samplerate>>>8&255,m[15]=h.samplerate&255);return K(p.mdhd,m)};var Qg=function(h){return K(p.mdia,Da(h),W(h.type),Ce(h))};var De=function(h){return K(p.mfhd,new Uint8Array([0,0,0,0,(h&4278190080)>>24,(h&16711680)>>16,(h&65280)>>8,h&255]))};var Ce=function(h){return K(p.minf,
"video"===h.type?K(p.vmhd,I):K(p.smhd,G),ba(),Pp(h))};var cl=function(h){for(var m=h.length,r=[];m--;)r[m]=Qp(h[m]);return K.apply(null,[p.moov,Rp(4294967295)].concat(r).concat(Sp(h)))};var Sp=function(h){for(var m=h.length,r=[];m--;)r[m]=Tp(h[m]);return K.apply(null,[p.mvex].concat(r))};var Rp=function(h){h=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(h&4278190080)>>24,(h&16711680)>>16,(h&65280)>>8,h&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return K(p.mvhd,h)};var Up=function(h){h=h.samples||[];var m=new Uint8Array(4+h.length),r;for(r=0;r>>8),w.push(q[C].byteLength&255),w=w.concat(Array.prototype.slice.call(q[C]));for(C=0;C>>8),B.push(v[C].byteLength&255),B=B.concat(Array.prototype.slice.call(v[C]));q=[p.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,(r.width&65280)>>8,r.width&255,(r.height&65280)>>8,r.height&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,
111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),K(p.avcC,new Uint8Array([1,r.profileIdc,r.profileCompatibility,r.levelIdc,255].concat([q.length],w,[v.length],B))),K(p.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))];r.sarRatio&&(v=r.sarRatio[0],r=r.sarRatio[1],q.push(K(p.pasp,new Uint8Array([(v&4278190080)>>24,(v&16711680)>>16,(v&65280)>>8,v&255,(r&4278190080)>>24,(r&16711680)>>16,(r&65280)>>8,r&255]))));return K.apply(null,q)};var m=function(r){return K(p.mp4a,
new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(r.channelcount&65280)>>8,r.channelcount&255,(r.samplesize&65280)>>8,r.samplesize&255,0,0,0,0,(r.samplerate&65280)>>8,r.samplerate&255,0,0]),ta(r))}})();var Vp=function(h){h=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(h.id&4278190080)>>24,(h.id&16711680)>>16,(h.id&65280)>>8,h.id&255,0,0,0,0,(h.duration&4278190080)>>24,(h.duration&16711680)>>16,(h.duration&65280)>>8,h.duration&255,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,(h.width&65280)>>8,h.width&255,0,0,(h.height&65280)>>8,h.height&255,0,0]);return K(p.tkhd,h)};var Wp=function(h){var m=K(p.tfhd,new Uint8Array([0,0,0,58,(h.id&4278190080)>>24,(h.id&16711680)>>16,(h.id&65280)>>8,h.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0]));var r=Math.floor(h.baseMediaDecodeTime/c);var q=Math.floor(h.baseMediaDecodeTime%c);r=K(p.tfdt,new Uint8Array([1,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,r&255,q>>>24&255,q>>>16&255,q>>>8&255,q&255]));if("audio"===h.type)return h=
l(h,92),K(p.traf,m,r,h);q=Up(h);h=l(h,q.length+92);return K(p.traf,m,r,h,q)};var Qp=function(h){h.duration=h.duration||4294967295;return K(p.trak,Vp(h),Qg(h))};var Tp=function(h){var m=new Uint8Array([0,0,0,0,(h.id&4278190080)>>24,(h.id&16711680)>>16,(h.id&65280)>>8,h.id&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);"video"!==h.type&&(m[m.length-1]=0);return K(p.trex,m)};(function(){var h=function(q,v){var w=0,B=0,C=0,F=0;q.length&&(void 0!==q[0].duration&&(w=1),void 0!==q[0].size&&(B=2),void 0!==q[0].flags&&
(C=4),void 0!==q[0].compositionTimeOffset&&(F=8));return[0,0,w|B|C|F,1,(q.length&4278190080)>>>24,(q.length&16711680)>>>16,(q.length&65280)>>>8,q.length&255,(v&4278190080)>>>24,(v&16711680)>>>16,(v&65280)>>>8,v&255]};var m=function(q,v){var w;q=q.samples||[];v+=20+16*q.length;var B=h(q,v);v=new Uint8Array(B.length+16*q.length);v.set(B);B=B.length;for(w=0;w>>24;v[B++]=(C.duration&16711680)>>>16;v[B++]=(C.duration&65280)>>>8;v[B++]=C.duration&
255;v[B++]=(C.size&4278190080)>>>24;v[B++]=(C.size&16711680)>>>16;v[B++]=(C.size&65280)>>>8;v[B++]=C.size&255;v[B++]=C.flags.isLeading<<2|C.flags.dependsOn;v[B++]=C.flags.isDependedOn<<6|C.flags.hasRedundancy<<4|C.flags.paddingValue<<1|C.flags.isNonSyncSample;v[B++]=C.flags.degradationPriority&61440;v[B++]=C.flags.degradationPriority&15;v[B++]=(C.compositionTimeOffset&4278190080)>>>24;v[B++]=(C.compositionTimeOffset&16711680)>>>16;v[B++]=(C.compositionTimeOffset&65280)>>>8;v[B++]=C.compositionTimeOffset&
255}return K(p.trun,v)};var r=function(q,v){var w;q=q.samples||[];v+=20+8*q.length;var B=h(q,v);v=new Uint8Array(B.length+8*q.length);v.set(B);B=B.length;for(w=0;w>>24;v[B++]=(C.duration&16711680)>>>16;v[B++]=(C.duration&65280)>>>8;v[B++]=C.duration&255;v[B++]=(C.size&4278190080)>>>24;v[B++]=(C.size&16711680)>>>16;v[B++]=(C.size&65280)>>>8;v[B++]=C.size&255}return K(p.trun,v)};l=function(q,v){return"audio"===q.type?r(q,v):m(q,v)}})();var ud=
{ftyp:Fa,mdat:function(h){return K(p.mdat,h)},moof:function(h,m){for(var r=[],q=m.length;q--;)r[q]=Wp(m[q]);return K.apply(null,[p.moof,De(h)].concat(r))},moov:cl,initSegment:function(h){var m=Fa();h=cl(h);var r=new Uint8Array(m.byteLength+h.byteLength);r.set(m);r.set(h,m.byteLength);return r}},dl=function(h,m){var r={size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}};r.dataOffset=m;r.compositionTimeOffset=h.pts-h.dts;r.duration=h.duration;
r.size=4*h.length;r.size+=h.byteLength;h.keyFrame&&(r.flags.dependsOn=2,r.flags.isNonSyncSample=0);return r},ac=[33,16,5,32,164,27],Rg=[33,65,108,84,1,2,4,8,168,2,4,8,17,191,252],ja=function(h){for(var m=[];h--;)m.push(0);return m},Xp=function(h){return Object.keys(h).reduce(function(m,r){m[r]=new Uint8Array(h[r].reduce(function(q,v){return q.concat(v)},[]));return m},{})},Sg;var el=function(h){return 9E4*h};var fl=function(h,m){return h*m};var Tg=function(h){return h/9E4};var gl=function(h,m){return h/
m};var ha={ONE_SECOND_IN_TS:9E4,secondsToVideoTs:el,secondsToAudioTs:fl,videoTsToSeconds:Tg,audioTsToSeconds:gl,audioTsToVideoTs:function(h,m){return el(gl(h,m))},videoTsToAudioTs:function(h,m){return fl(Tg(h),m)},metadataTsToSeconds:function(h,m,r){return Tg(r?h:h-m)}},Yp=ha.ONE_SECOND_IN_TS,vd={parseSei:function(h){for(var m=0,r={payloadType:-1,payloadSize:0},q=0,v=0;mm.type?this.dispatchCea608Packet(m):this.dispatchCea708Packet(m)},this),this.captionPackets_.length=0);this.flushCCStreams(h)};Za.prototype.flush=function(){return this.flushStream("flush")};Za.prototype.partialFlush=function(){return this.flushStream("partialFlush")};Za.prototype.reset=function(){this.latestDts_=null;this.ignoreNextEqualDts_=!1;this.numSameDts_=0;this.activeCea608Channel_=[null,null];this.ccStreams_.forEach(function(h){h.reset()})};
Za.prototype.dispatchCea608Packet=function(h){this.setsTextOrXDSActive(h)?this.activeCea608Channel_[h.type]=null:this.setsChannel1Active(h)?this.activeCea608Channel_[h.type]=0:this.setsChannel2Active(h)&&(this.activeCea608Channel_[h.type]=1);null!==this.activeCea608Channel_[h.type]&&this.ccStreams_[(h.type<<1)+this.activeCea608Channel_[h.type]].push(h)};Za.prototype.setsChannel1Active=function(h){return 4096===(h.ccData&30720)};Za.prototype.setsChannel2Active=function(h){return 6144===(h.ccData&30720)};
Za.prototype.setsTextOrXDSActive=function(h){return 256===(h.ccData&28928)||4138===(h.ccData&30974)||6186===(h.ccData&30974)};Za.prototype.dispatchCea708Packet=function(h){this.parse708captions_&&this.cc708Stream_.push(h)};var Zp={127:9834,4128:32,4129:160,4133:8230,4138:352,4140:338,4144:9608,4145:8216,4146:8217,4147:8220,4148:8221,4149:8226,4153:8482,4154:353,4156:339,4157:8480,4159:376,4214:8539,4215:8540,4216:8541,4217:8542,4218:9168,4219:9124,4220:9123,4221:9135,4222:9126,4223:9121,4256:12600},
$p=function(h){var m=Zp[h]||h;return h&4096&&h===m?"":String.fromCharCode(m)},Ee=function(h){return 32<=h&&127>=h||160<=h&&255>=h},Ob=function(h){this.windowNum=h;this.reset()};Ob.prototype.reset=function(){this.clearText();this.pendingNewLine=!1;this.winAttr={};this.penAttr={};this.penLoc={};this.penColor={};this.anchorPoint=this.anchorHorizontal=this.anchorVertical=this.relativePositioning=this.priority=this.columnLock=this.rowLock=this.visible=0;this.rowCount=1;this.virtualRowCount=this.rowCount+
1;this.columnCount=41;this.penStyle=this.windowStyle=0};Ob.prototype.getText=function(){return this.rows.join("\n")};Ob.prototype.clearText=function(){this.rows=[""];this.rowIdx=0};Ob.prototype.newLine=function(h){this.rows.length>=this.virtualRowCount&&"function"===typeof this.beforeRowOverflow&&this.beforeRowOverflow(h);0this.virtualRowCount;)this.rows.shift(),this.rowIdx--};Ob.prototype.isEmpty=function(){return 0===this.rows.length?
!0:1===this.rows.length?""===this.rows[0]:!1};Ob.prototype.addText=function(h){this.rows[this.rowIdx]+=h};Ob.prototype.backspace=function(){if(!this.isEmpty()){var h=this.rows[this.rowIdx];this.rows[this.rowIdx]=h.substr(0,h.length-1)}};var Fe=function(h,m,r){this.serviceNum=h;this.text="";this.currentWindow=new Ob(-1);this.windows=[];this.stream=r;"string"===typeof m&&this.createTextDecoder(m)};Fe.prototype.init=function(h,m){this.startPts=h;for(h=0;8>h;h++)this.windows[h]=new Ob(h),"function"===
typeof m&&(this.windows[h].beforeRowOverflow=m)};Fe.prototype.setCurrentWindow=function(h){this.currentWindow=this.windows[h]};Fe.prototype.createTextDecoder=function(h){if("undefined"===typeof TextDecoder)this.stream.trigger("log",{level:"warn",message:"The `encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(h)}catch(m){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+h+" encoding. "+m})}};var la=function(h){h=
h||{};la.prototype.init.call(this);var m=this,r=h.captionServices||{},q={},v;Object.keys(r).forEach(w=>{v=r[w];/^SERVICE/.test(w)&&(q[w]=v.encoding)});this.serviceEncodings=q;this.current708Packet=null;this.services={};this.push=function(w){3===w.type?m.new708Packet():null===m.current708Packet&&m.new708Packet();m.add708Bytes(w)}};la.prototype=new b;la.prototype.new708Packet=function(){null!==this.current708Packet&&this.push708Packet();this.current708Packet={data:[],ptsVals:[]}};la.prototype.add708Bytes=
function(h){var m=h.ccData,r=m>>>8;m&=255;this.current708Packet.ptsVals.push(h.pts);this.current708Packet.data.push(r);this.current708Packet.data.push(m)};la.prototype.push708Packet=function(){var h=this.current708Packet,m=h.data,r=null,q=null,v=0,w=m[v++];h.seq=w>>6;for(h.sizeCode=w&63;v>5,q=w&31,7===r&&0=h?q=this.setCurrentWindow(q,w):152<=h&&159>=h?q=this.defineWindow(q,w):136===h?q=this.clearWindows(q,w):140===h?q=this.deleteWindows(q,w):137===h?q=this.displayWindows(q,w):138===h?q=this.hideWindows(q,w):139===h?q=this.toggleWindows(q,w):151===h?q=this.setWindowAttributes(q,w):144===h?q=this.setPenAttributes(q,w):145===h?q=this.setPenColor(q,
w):146===h?q=this.setPenLocation(q,w):143===h?w=this.reset(q,w):8===h?w.currentWindow.backspace():12===h?w.currentWindow.clearText():13===h?w.currentWindow.pendingNewLine=!0:14===h?w.currentWindow.clearText():141===h&&q++};la.prototype.extendedCommands=function(h,m){var r=this.current708Packet.data[++h];Ee(r)&&(h=this.handleText(h,m,{isExtended:!0}));return h};la.prototype.getPts=function(h){return this.current708Packet.ptsVals[Math.floor(h/2)]};la.prototype.initService=function(h,m){var r="SERVICE"+
h,q=this,v;r in this.serviceEncodings&&(v=this.serviceEncodings[r]);this.services[h]=new Fe(h,v,q);this.services[h].init(this.getPts(m),function(w){q.flushDisplayed(w,q.services[h])});return this.services[h]};la.prototype.handleText=function(h,m,r){function q(J){return J.map(N=>("0"+(N&255).toString(16)).slice(-2)).join("")}var v=r&&r.isExtended,w=r&&r.isMultiByte;r=this.current708Packet.data;var B=v?4096:0,C=r[h],F=r[h+1];r=m.currentWindow;w?(F=[C,F],h++):F=[C];m.textDecoder_&&!v?m=m.textDecoder_.decode(new Uint8Array(F)):
w?(m=q(F),m=String.fromCharCode(parseInt(m,16))):m=$p(B|C);r.pendingNewLine&&!r.isEmpty()&&r.newLine(this.getPts(h));r.pendingNewLine=!1;r.addText(m);return h};la.prototype.multiByteCharacter=function(h,m){var r=this.current708Packet.data,q=r[h+2];Ee(r[h+1])&&Ee(q)&&(h=this.handleText(++h,m,{isMultiByte:!0}));return h};la.prototype.setCurrentWindow=function(h,m){m.setCurrentWindow(this.current708Packet.data[h]&7);return h};la.prototype.defineWindow=function(h,m){var r=this.current708Packet.data,q=
r[h];m.setCurrentWindow(q&7);m=m.currentWindow;q=r[++h];m.visible=(q&32)>>5;m.rowLock=(q&16)>>4;m.columnLock=(q&8)>>3;m.priority=q&7;q=r[++h];m.relativePositioning=(q&128)>>7;m.anchorVertical=q&127;q=r[++h];m.anchorHorizontal=q;q=r[++h];m.anchorPoint=(q&240)>>4;m.rowCount=q&15;q=r[++h];m.columnCount=q&63;q=r[++h];m.windowStyle=(q&56)>>3;m.penStyle=q&7;m.virtualRowCount=m.rowCount+1;return h};la.prototype.setWindowAttributes=function(h,m){var r=this.current708Packet.data,q=r[h];m=m.currentWindow.winAttr;
q=r[++h];m.fillOpacity=(q&192)>>6;m.fillRed=(q&48)>>4;m.fillGreen=(q&12)>>2;m.fillBlue=q&3;q=r[++h];m.borderType=(q&192)>>6;m.borderRed=(q&48)>>4;m.borderGreen=(q&12)>>2;m.borderBlue=q&3;q=r[++h];m.borderType+=(q&128)>>5;m.wordWrap=(q&64)>>6;m.printDirection=(q&48)>>4;m.scrollDirection=(q&12)>>2;m.justify=q&3;q=r[++h];m.effectSpeed=(q&240)>>4;m.effectDirection=(q&12)>>2;m.displayEffect=q&3;return h};la.prototype.flushDisplayed=function(h,m){for(var r=[],q=0;8>q;q++)m.windows[q].visible&&!m.windows[q].isEmpty()&&
r.push(m.windows[q].getText());m.endPts=h;m.text=r.join("\n\n");this.pushCaption(m);m.startPts=h};la.prototype.pushCaption=function(h){""!==h.text&&(this.trigger("data",{startPts:h.startPts,endPts:h.endPts,text:h.text,stream:"cc708_"+h.serviceNum}),h.text="",h.startPts=h.endPts)};la.prototype.displayWindows=function(h,m){var r=this.current708Packet.data[++h],q=this.getPts(h);this.flushDisplayed(q,m);for(q=0;8>q;q++)r&1<q;q++)r&1<q;q++)r&1<q;q++)r&1<q;q++)r&1<>4;m.offset=(q&12)>>2;m.penSize=q&3;q=r[++h];m.italics=(q&128)>>7;m.underline=(q&64)>>6;m.edgeType=(q&56)>>3;m.fontStyle=q&7;return h};la.prototype.setPenColor=function(h,m){var r=this.current708Packet.data,q=r[h];m=
m.currentWindow.penColor;q=r[++h];m.fgOpacity=(q&192)>>6;m.fgRed=(q&48)>>4;m.fgGreen=(q&12)>>2;m.fgBlue=q&3;q=r[++h];m.bgOpacity=(q&192)>>6;m.bgRed=(q&48)>>4;m.bgGreen=(q&12)>>2;m.bgBlue=q&3;q=r[++h];m.edgeRed=(q&48)>>4;m.edgeGreen=(q&12)>>2;m.edgeBlue=q&3;return h};la.prototype.setPenLocation=function(h,m){var r=this.current708Packet.data,q=r[h],v=m.currentWindow.penLoc;m.currentWindow.pendingNewLine=!0;q=r[++h];v.row=q&15;q=r[++h];v.column=q&63;return h};la.prototype.reset=function(h,m){var r=this.getPts(h);
this.flushDisplayed(r,m);return this.initService(m.serviceNum,h)};var aq={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,
572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},Ge=function(h){if(null===h)return"";h=aq[h]||h;return String.fromCharCode(h)},bq=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],mc=function(){for(var h=[],m=15;m--;)h.push({text:"",
indent:0,offset:0});return h},sa=function(h,m){sa.prototype.init.call(this);this.field_=h||0;this.dataChannel_=m||0;this.name_="CC"+((this.field_<<1|this.dataChannel_)+1);this.setConstants();this.reset();this.push=function(r){var q=r.ccData&32639;if(q===this.lastControlCode_)this.lastControlCode_=null;else{4096===(q&61440)?this.lastControlCode_=q:q!==this.PADDING_&&(this.lastControlCode_=null);var v=q>>>8;var w=q&255;q!==this.PADDING_&&(q===this.RESUME_CAPTION_LOADING_?this.mode_="popOn":q===this.END_OF_CAPTION_?
(this.mode_="popOn",this.clearFormatting(r.pts),this.flushDisplayed(r.pts),w=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=w,this.startPts_=r.pts):q===this.ROLL_UP_2_ROWS_?(this.rollUpRows_=2,this.setRollUp(r.pts)):q===this.ROLL_UP_3_ROWS_?(this.rollUpRows_=3,this.setRollUp(r.pts)):q===this.ROLL_UP_4_ROWS_?(this.rollUpRows_=4,this.setRollUp(r.pts)):q===this.CARRIAGE_RETURN_?(this.clearFormatting(r.pts),this.flushDisplayed(r.pts),this.shiftRowsUp_(),this.startPts_=r.pts):q===
this.BACKSPACE_?"popOn"===this.mode_?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1):q===this.ERASE_DISPLAYED_MEMORY_?(this.flushDisplayed(r.pts),this.displayed_=mc()):q===this.ERASE_NON_DISPLAYED_MEMORY_?this.nonDisplayed_=mc():q===this.RESUME_DIRECT_CAPTIONING_?("paintOn"!==this.mode_&&(this.flushDisplayed(r.pts),this.displayed_=mc()),this.mode_="paintOn",this.startPts_=r.pts):this.isSpecialCharacter(v,
w)?(q=Ge((v&3)<<8|w),this[this.mode_](r.pts,q),this.column_++):this.isExtCharacter(v,w)?("popOn"===this.mode_?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),q=Ge((v&3)<<8|w),this[this.mode_](r.pts,q),this.column_++):this.isMidRowCode(v,w)?(this.clearFormatting(r.pts),this[this.mode_](r.pts," "),this.column_++,14===(w&14)&&this.addFormatting(r.pts,["i"]),1===(w&1)&&this.addFormatting(r.pts,
["u"])):this.isOffsetControlCode(v,w)?(r=w&3,this.nonDisplayed_[this.row_].offset=r,this.column_+=r):this.isPAC(v,w)?(v=bq.indexOf(q&7968),"rollUp"===this.mode_&&(0>v-this.rollUpRows_+1&&(v=this.rollUpRows_-1),this.setRollUp(r.pts,v)),v!==this.row_&&0<=v&&14>=v&&(this.clearFormatting(r.pts),this.row_=v),w&1&&-1===this.formatting_.indexOf("u")&&this.addFormatting(r.pts,["u"]),16===(q&16)&&(q=(q&14)>>1,this.column_=4*q,this.nonDisplayed_[this.row_].indent+=q),this.isColorPAC(w)&&14===(w&14)&&this.addFormatting(r.pts,
["i"])):this.isNormalChar(v)&&(0===w&&(w=null),q=Ge(v),q+=Ge(w),this[this.mode_](r.pts,q),this.column_+=q.length))}}};sa.prototype=new b;sa.prototype.flushDisplayed=function(h){const m=q=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+q+"."})},r=[];this.displayed_.forEach((q,v)=>{if(q&&q.text&&q.text.length){try{q.text=q.text.trim()}catch(w){m(v)}q.text.length&&r.push({text:q.text,line:v+1,position:10+Math.min(70,10*q.indent)+2.5*q.offset})}else void 0!==q&&
null!==q||m(v)});r.length&&this.trigger("data",{startPts:this.startPts_,endPts:h,content:r,stream:this.name_})};sa.prototype.reset=function(){this.mode_="popOn";this.startPts_=this.topRow_=0;this.displayed_=mc();this.nonDisplayed_=mc();this.lastControlCode_=null;this.column_=0;this.row_=14;this.rollUpRows_=2;this.formatting_=[]};sa.prototype.setConstants=function(){0===this.dataChannel_?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):1===this.dataChannel_&&(this.BASE_=
24,this.EXT_=25,this.CONTROL_=(28|this.field_)<<8,this.OFFSET_=31);this.PADDING_=0;this.RESUME_CAPTION_LOADING_=this.CONTROL_|32;this.END_OF_CAPTION_=this.CONTROL_|47;this.ROLL_UP_2_ROWS_=this.CONTROL_|37;this.ROLL_UP_3_ROWS_=this.CONTROL_|38;this.ROLL_UP_4_ROWS_=this.CONTROL_|39;this.CARRIAGE_RETURN_=this.CONTROL_|45;this.RESUME_DIRECT_CAPTIONING_=this.CONTROL_|41;this.BACKSPACE_=this.CONTROL_|33;this.ERASE_DISPLAYED_MEMORY_=this.CONTROL_|44;this.ERASE_NON_DISPLAYED_MEMORY_=this.CONTROL_|46};sa.prototype.isSpecialCharacter=
function(h,m){return h===this.EXT_&&48<=m&&63>=m};sa.prototype.isExtCharacter=function(h,m){return(h===this.EXT_+1||h===this.EXT_+2)&&32<=m&&63>=m};sa.prototype.isMidRowCode=function(h,m){return h===this.EXT_&&32<=m&&47>=m};sa.prototype.isOffsetControlCode=function(h,m){return h===this.OFFSET_&&33<=m&&35>=m};sa.prototype.isPAC=function(h,m){return h>=this.BASE_&&h=m};sa.prototype.isColorPAC=function(h){return 64<=h&&79>=h||96<=h&&127>=h};sa.prototype.isNormalChar=function(h){return 32<=
h&&127>=h};sa.prototype.setRollUp=function(h,m){"rollUp"!==this.mode_&&(this.row_=14,this.mode_="rollUp",this.flushDisplayed(h),this.nonDisplayed_=mc(),this.displayed_=mc());if(void 0!==m&&m!==this.row_)for(h=0;hh;h++)this.displayed_[h]={text:"",indent:0,offset:0};for(h=this.topRow_;hm&&(r=-1);4294967296
{if(!h)return-1;for(;rr||(h.mimeType=unescape(Fb(h.data,m,r)),m=r+1,h.pictureType=h.data[m],m++,r=He(h.data,0,m),0>r||(h.description=decodeURIComponent(Fb(h.data,m,r)),m=r+1,"--\x3e"===h.mimeType?h.url=unescape(Fb(h.data,m,h.data.length)):h.pictureData=
h.data.subarray(m,h.data.length)))}},"T*":function(h){3===h.data[0]&&(h.value=decodeURIComponent(Fb(h.data,1,h.data.length)).replace(/\0*$/,""),h.values=h.value.split("\x00"))},TXXX:function(h){if(3===h.data[0]){var m=He(h.data,0,1);-1!==m&&(h.description=decodeURIComponent(Fb(h.data,1,m)),h.value=decodeURIComponent(Fb(h.data,m+1,h.data.length)).replace(/\0*$/,""),h.data=h.value)}},"W*":function(h){h.url=unescape(Fb(h.data,0,h.data.length)).replace(/\0.*$/,"")},WXXX:function(h){if(3===h.data[0]){var m=
He(h.data,0,1);-1!==m&&(h.description=decodeURIComponent(Fb(h.data,1,m)),h.url=unescape(Fb(h.data,m+1,h.data.length)).replace(/\0.*$/,""))}},PRIV:function(h){var m;for(m=0;mh.length||73!==h[0]||68!==h[1]||51!==h[2])){r=wd(h.subarray(6,10));r+=10;h[5]&64&&(m=m+4+wd(h.subarray(10,14)),r-=wd(h.subarray(16,20)));
do{var v=wd(h.subarray(m+4,m+8));if(1>v)break;var w=String.fromCharCode(h[m],h[m+1],h[m+2],h[m+3]);w={id:w,data:h.subarray(m+10,m+v+10)};w.key=w.id;if(xd[w.id])xd[w.id](w);else if("T"===w.id[0])xd["T*"](w);else if("W"===w.id[0])xd["W*"](w);q.push(w);m+=10;m+=v}while(mw.data.length||73!==w.data[0]||68!==w.data[1]||51!==w.data[2]))this.trigger("log",{level:"warn",message:"Skipping unrecognized metadata packet"});else if(r.push(w),q+=w.data.byteLength,1===r.length&&(m=Pb.parseSyncSafeInteger(w.data.subarray(6,10)),m+=10),!(qC){this.trigger("log",{level:"warn",message:"Malformed ID3 frame encountered. Skipping remaining metadata parsing."});break}var F=String.fromCharCode(w.data[B],w.data[B+1],w.data[B+2],w.data[B+3]);F={id:F,data:w.data.subarray(B+10,B+C+10)};F.key=
F.id;if(Pb.frameParsers[F.id])Pb.frameParsers[F.id](F);else if("T"===F.id[0])Pb.frameParsers["T*"](F);else if("W"===F.id[0])Pb.frameParsers["W*"](F);if("com.apple.streaming.transportStreamTimestamp"===F.owner){var J=F.data,N=(J[3]&1)<<30|J[4]<<22|J[5]<<14|J[6]<<6|J[7]>>>2;N*=4;N+=J[7]&3;F.timeStamp=N;void 0===w.pts&&void 0===w.dts&&(w.pts=F.timeStamp,w.dts=F.timeStamp);this.trigger("timestamp",F)}w.frames.push(F);B+=10;B+=C}while(B>>4&&(B+=v[B]+1);if(0===w.pid)w.type="pat",m(v.subarray(B),w),this.trigger("data",w);else if(w.pid===this.pmtPid)for(w.type="pmt",m(v.subarray(B),w),this.trigger("data",w);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else void 0===this.programMapTable?this.packetsWaitingForPmt.push([v,B,w]):this.processPes_(v,B,w)};this.processPes_=function(v,w,B){B.streamType=B.pid===this.programMapTable.video?La.H264_STREAM_TYPE:
B.pid===this.programMapTable.audio?La.ADTS_STREAM_TYPE:this.programMapTable["timed-metadata"][B.pid];B.type="pes";B.data=v.subarray(w);this.trigger("data",B)}};Ie.prototype=new b;Ie.STREAM_TYPES={h264:27,adts:15};var Xg=function(){var h=this,m=!1,r={data:[],size:0},q={data:[],size:0},v={data:[],size:0},w,B=function(C,F,J){var N=new Uint8Array(C.size),L={type:F},X=0,S=0;X=!1;if(C.data.length&&!(9>C.size)){L.trackId=C.data[0].pid;for(X=0;X>>3,L.pts*=4,L.pts+=(N[13]&6)>>>1,L.dts=L.pts,S&64&&(L.dts=(N[14]&14)<<27|(N[15]&255)<<20|(N[16]&254)<<12|(N[17]&255)<<5|(N[18]&254)>>>3,L.dts*=4,L.dts+=(N[18]&6)>>>1)),L.data=N.subarray(9+N[8]));X="video"===F||L.packetLength<=C.size;if(J||X)C.size=0,C.data.length=0;X&&h.trigger("data",
L)}};Xg.prototype.init.call(this);this.push=function(C){({pat:function(){},pes:function(){switch(C.streamType){case La.H264_STREAM_TYPE:var F=r;var J="video";break;case La.ADTS_STREAM_TYPE:F=q;J="audio";break;case La.METADATA_STREAM_TYPE:F=v;J="timed-metadata";break;default:return}C.payloadUnitStartIndicator&&B(F,J,!0);F.data.push(C);F.size+=C.data.byteLength},pmt:function(){var F={type:"metadata",tracks:[]};w=C.programMapTable;null!==w.video&&F.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},
id:+w.video,codec:"avc",type:"video"});null!==w.audio&&F.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+w.audio,codec:"adts",type:"audio"});m=!0;h.trigger("data",F)}})[C.type]()};this.reset=function(){r.size=0;r.data.length=0;q.size=0;q.data.length=0;this.trigger("reset")};this.flushStreams_=function(){B(r,"video");B(q,"audio");B(v,"timed-metadata")};this.flush=function(){if(!m&&w){var C={type:"metadata",tracks:[]};null!==w.video&&C.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},
id:+w.video,codec:"avc",type:"video"});null!==w.audio&&C.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+w.audio,codec:"adts",type:"audio"});h.trigger("data",C)}m=!1;this.flushStreams_();this.trigger("done")}};Xg.prototype=new b;var Gb={PAT_PID:0,MP2T_PACKET_LENGTH:188,TransportPacketStream:Wg,TransportParseStream:Ie,ElementaryStream:Xg,TimestampRolloverStream:eq,CaptionStream:hl,Cea608Stream:cq,Cea708Stream:dq,MetadataStream:Vg},Je;for(Je in La)La.hasOwnProperty(Je)&&(Gb[Je]=La[Je]);var fq=
ha.ONE_SECOND_IN_TS,il=[96E3,88200,64E3,48E3,44100,32E3,24E3,22050,16E3,12E3,11025,8E3,7350];var Ke=function(h){var m,r=0;Ke.prototype.init.call(this);this.skipWarn_=function(q,v){this.trigger("log",{level:"warn",message:`adts skiping bytes ${q} to ${v} in frame ${r} outside syncword`})};this.push=function(q){var v=0;h||(r=0);if("audio"===q.type){if(m&&m.length){var w=m;m=new Uint8Array(w.byteLength+q.data.byteLength);m.set(w);m.set(q.data,w.byteLength)}else m=q.data;for(var B;v+7>5;var F=1024*((m[v+6]&3)+1);var J=F*fq/il[(m[v+2]&60)>>>2];if(m.byteLength-v>>6&3)+1,channelcount:(m[v+2]&1)<<2|(m[v+3]&192)>>>6,samplerate:il[(m[v+2]&60)>>>2],samplingfrequencyindex:(m[v+2]&60)>>>2,samplesize:16,data:m.subarray(v+7+
C,v+w)});r++;v+=w}"number"===typeof B&&(this.skipWarn_(B,v),B=null);m=m.subarray(v)}};this.flush=function(){r=0;this.trigger("done")};this.reset=function(){m=void 0;this.trigger("reset")};this.endTimeline=function(){m=void 0;this.trigger("endedtimeline")}};Ke.prototype=new b;var gq=function(h){var m=h.byteLength,r=0,q=0;this.length=function(){return 8*m};this.bitsAvailable=function(){return 8*m+q};this.loadWord=function(){var v=h.byteLength-m,w=new Uint8Array(4),B=Math.min(4,m);if(0===B)throw Error("no bytes available");
w.set(h.subarray(v,v+B));r=(new DataView(w.buffer)).getUint32(0);q=8*B;m-=B};this.skipBits=function(v){if(!(q>v)){v-=q;var w=Math.floor(v/8);v-=8*w;m-=w;this.loadWord()}r<<=v;q-=v};this.readBits=function(v){var w=Math.min(q,v),B=r>>>32-w;q-=w;0>>v))return r<<=v,q-=v,v;this.loadWord();return v+this.skipLeadingZeros()};this.skipUnsignedExpGolomb=function(){this.skipBits(1+
this.skipLeadingZeros())};this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())};this.readUnsignedExpGolomb=function(){var v=this.skipLeadingZeros();return this.readBits(v+1)-1};this.readExpGolomb=function(){var v=this.readUnsignedExpGolomb();return 1&v?1+v>>>1:-1*(v>>>1)};this.readBoolean=function(){return 1===this.readBits(1)};this.readUnsignedByte=function(){return this.readBits(8)};this.loadWord()};var Yg=function(){var h=0,m,r;Yg.prototype.init.call(this);this.push=function(q){if(r){var v=
new Uint8Array(r.byteLength+q.data.byteLength);v.set(r);v.set(q.data,r.byteLength);r=v}else r=q.data;for(q=r.byteLength;hIa?w(16,F):w(64,F))}}F.skipUnsignedExpGolomb();Ia=F.readUnsignedExpGolomb();if(0===Ia)F.readUnsignedExpGolomb();else if(1===Ia)for(F.skipBits(1),F.skipExpGolomb(),F.skipExpGolomb(),zd=F.readUnsignedExpGolomb(),Ia=0;Ia>4?r+20:r+10},ll=function(h,m){if(10>h.length-m||73!==h[m]||68!==h[m+
1]||51!==h[m+2])return m;m+=kl(h,m);return ll(h,m)},ml=function(h){return h[0]<<21|h[1]<<14|h[2]<<7|h[3]},Qb={isLikelyAacData:function(h){var m=ll(h,0);return h.length>=m+2&&255===(h[m]&255)&&240===(h[m+1]&240)&&16===(h[m+1]&22)},parseId3TagSize:kl,parseAdtsSize:function(h,m){return h[m+3]&6144|h[m+4]<<3|(h[m+5]&224)>>5},parseType:function(h,m){return 73===h[m]&&68===h[m+1]&&51===h[m+2]?"timed-metadata":h[m]&1&&240===(h[m+1]&240)?"audio":null},parseSampleRate:function(h){for(var m=0;m+5>>2];return null},parseAacTimestamp:function(h){var m=10;h[5]&64&&(m=m+4+ml(h.subarray(10,14)));do{var r=ml(h.subarray(m+4,m+8));if(1>r)break;var q=String.fromCharCode(h[m],h[m+1],h[m+2],h[m+3]);if("PRIV"===q){q=h.subarray(m+10,m+r+10);for(var v=0;v>>2,m*=4,m+=h[7]&3;break}}m+=10;m+=r}while(mh.length-v)break;q=Qb.parseId3TagSize(h,v);if(v+q>h.length)break;r={type:"timed-metadata",
data:h.subarray(v,v+q)};this.trigger("data",r);v+=q}else if(255===(h[v]&255)&&240===(h[v+1]&240)){if(7>h.length-v)break;q=Qb.parseAdtsSize(h,v);if(v+q>h.length)break;r={type:"audio",data:h.subarray(v,v+q),pts:m,dts:m};this.trigger("data",r);v+=q}else v++;h=0=r.duration)&&
(r.duration=q[q.length-1].duration);q.byteLength+=r.byteLength;q.nalCount+=r.length;q.duration+=r.duration;q.push(r);return q},groupFramesIntoGops:function(h){var m,r=[],q=[];r.byteLength=0;r.nalCount=0;r.duration=0;r.pts=h[0].pts;r.dts=h[0].dts;q.byteLength=0;q.nalCount=0;q.duration=0;q.pts=h[0].pts;q.dts=h[0].dts;for(m=0;m=r.duration&&(r.duration=q[q.length-1].duration);q.byteLength+=r.byteLength;q.nalCount+=r.nalCount;q.duration+=r.duration;q.push(r);return q},extendFirstKeyFrame:function(h){if(!h[0][0].keyFrame&&1w||
B>ha.ONE_SECOND_IN_TS/2)){Sg||(r={96E3:[ac,[227,64],ja(154),[56]],88200:[ac,[231],ja(170),[56]],64E3:[ac,[248,192],ja(240),[56]],48E3:[ac,[255,192],ja(268),[55,148,128],ja(54),[112]],44100:[ac,[255,192],ja(268),[55,163,128],ja(84),[112]],32E3:[ac,[255,192],ja(268),[55,234],ja(226),[112]],24E3:[ac,[255,192],ja(268),[55,255,128],ja(268),[111,112],ja(126),[224]],16E3:[ac,[255,192],ja(268),[55,255,128],ja(268),[111,255],ja(269),[223,108],ja(195),[1,192]],12E3:[Rg,ja(268),[3,127,248],ja(268),[6,255,240],
ja(268),[13,255,224],ja(268),[27,253,128],ja(259),[56]],11025:[Rg,ja(268),[3,127,248],ja(268),[6,255,240],ja(268),[13,255,224],ja(268),[27,255,192],ja(268),[55,175,128],ja(108),[112]],8E3:[Rg,ja(268),[3,121,16],ja(47),[7]]},Sg=Xp(r));r=Sg[h.samplerate];r||(r=m[0].data);for(q=0;q=r)return h;m.minSegmentDts=
Infinity;return h.filter(function(q){return q.dts>=r?(m.minSegmentDts=Math.min(m.minSegmentDts,q.dts),m.minSegmentPts=m.minSegmentDts,!0):!1})},generateSampleTable:function(h){var m,r=[];for(m=0;m=L&&(!X||F>L))){var X=N;F=L}}return X?X.gop:null};this.alignGopsAtStart_=function(C){var F,J;var N=C.byteLength;var L=C.nalCount;var X=C.duration;for(F=J=0;FS.pts?F++:(J++,N-=ea.byteLength,L-=ea.nalCount,X-=ea.duration)}if(0===J)return C;if(J===C.length)return null;C=C.slice(J);C.byteLength=N;C.duration=X;C.nalCount=L;C.pts=C[0].pts;C.dts=C[0].dts;return C};this.alignGopsAtEnd_=function(C){var F;var J=q.length-1;var N=
C.length-1;var L=null;for(F=!1;0<=J&&0<=N;){var X=q[J];var S=C[N];if(X.pts===S.pts){F=!0;break}X.pts>S.pts?J--:(J===q.length-1&&(L=N),N--)}if(!F&&null===L)return null;J=F?N:L;if(0===J)return C;C=C.slice(J);J=C.reduce(function(ea,gb){ea.byteLength+=gb.byteLength;ea.duration+=gb.duration;ea.nalCount+=gb.nalCount;return ea},{byteLength:0,duration:0,nalCount:0});C.byteLength=J.byteLength;C.duration=J.duration;C.nalCount=J.nalCount;C.pts=C[0].pts;C.dts=C[0].dts;return C};this.alignGopsWith=function(C){q=
C}};ah.prototype=new b;var Sc=function(h,m){this.numberOfTracks=0;this.metadataStream=m;h=h||{};this.remuxTracks="undefined"!==typeof h.remux?!!h.remux:!0;this.keepOriginalTimestamps="boolean"===typeof h.keepOriginalTimestamps?h.keepOriginalTimestamps:!1;this.pendingTracks=[];this.videoTrack=null;this.pendingBoxes=[];this.pendingCaptions=[];this.pendingMetadata=[];this.emittedTracks=this.pendingBytes=0;Sc.prototype.init.call(this);this.push=function(r){if(r.content||r.text)return this.pendingCaptions.push(r);
if(r.frames)return this.pendingMetadata.push(r);this.pendingTracks.push(r.track);this.pendingBytes+=r.boxes.byteLength;"video"===r.track.type&&(this.videoTrack=r.track,this.pendingBoxes.push(r.boxes));"audio"===r.track.type&&(this.audioTrack=r.track,this.pendingBoxes.unshift(r.boxes))}};Sc.prototype=new b;Sc.prototype.flush=function(h){var m=0,r={captions:[],captionStreams:{},metadata:[],info:{}},q=0;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0);return}}this.videoTrack?(q=this.videoTrack.timelineStartInfo.pts,ol.forEach(function(v){r.info[v]=this.videoTrack[v]},this)):this.audioTrack&&(q=this.audioTrack.timelineStartInfo.pts,nl.forEach(function(v){r.info[v]=this.audioTrack[v]},this));if(this.videoTrack||this.audioTrack){r.type=1===this.pendingTracks.length?this.pendingTracks[0].type:
"combined";this.emittedTracks+=this.pendingTracks.length;h=ud.initSegment(this.pendingTracks);r.initSegment=new Uint8Array(h.byteLength);r.initSegment.set(h);r.data=new Uint8Array(this.pendingBytes);for(h=0;h=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)};Sc.prototype.setRemux=function(h){this.remuxTracks=h};var bh=function(h){var m=this,r=!0,q,v;bh.prototype.init.call(this);h=h||{};this.baseMediaDecodeTime=h.baseMediaDecodeTime||0;this.transmuxPipeline_={};this.setupAacPipeline=function(){var w={};this.transmuxPipeline_=w;w.type="aac";w.metadataStream=new Gb.MetadataStream;w.aacStream=
new $g;w.audioTimestampRolloverStream=new Gb.TimestampRolloverStream("audio");w.timedMetadataTimestampRolloverStream=new Gb.TimestampRolloverStream("timed-metadata");w.adtsStream=new Ke;w.coalesceStream=new Sc(h,w.metadataStream);w.headOfPipeline=w.aacStream;w.aacStream.pipe(w.audioTimestampRolloverStream).pipe(w.adtsStream);w.aacStream.pipe(w.timedMetadataTimestampRolloverStream).pipe(w.metadataStream).pipe(w.coalesceStream);w.metadataStream.on("timestamp",function(B){w.aacStream.setTimestamp(B.timeStamp)});
w.aacStream.on("data",function(B){"timed-metadata"!==B.type&&"audio"!==B.type||w.audioSegmentStream||(v=v||{timelineStartInfo:{baseMediaDecodeTime:m.baseMediaDecodeTime},codec:"adts",type:"audio"},w.coalesceStream.numberOfTracks++,w.audioSegmentStream=new Me(v,h),w.audioSegmentStream.on("log",m.getLogTrigger_("audioSegmentStream")),w.audioSegmentStream.on("timingInfo",m.trigger.bind(m,"audioTimingInfo")),w.adtsStream.pipe(w.audioSegmentStream).pipe(w.coalesceStream),m.trigger("trackinfo",{hasAudio:!!v,
hasVideo:!!q}))});w.coalesceStream.on("data",this.trigger.bind(this,"data"));w.coalesceStream.on("done",this.trigger.bind(this,"done"));pl(this,w)};this.setupTsPipeline=function(){var w={};this.transmuxPipeline_=w;w.type="ts";w.metadataStream=new Gb.MetadataStream;w.packetStream=new Gb.TransportPacketStream;w.parseStream=new Gb.TransportParseStream;w.elementaryStream=new Gb.ElementaryStream;w.timestampRolloverStream=new Gb.TimestampRolloverStream;w.adtsStream=new Ke;w.h264Stream=new Zg;w.captionStream=
new Gb.CaptionStream(h);w.coalesceStream=new Sc(h,w.metadataStream);w.headOfPipeline=w.packetStream;w.packetStream.pipe(w.parseStream).pipe(w.elementaryStream).pipe(w.timestampRolloverStream);w.timestampRolloverStream.pipe(w.h264Stream);w.timestampRolloverStream.pipe(w.adtsStream);w.timestampRolloverStream.pipe(w.metadataStream).pipe(w.coalesceStream);w.h264Stream.pipe(w.captionStream).pipe(w.coalesceStream);w.elementaryStream.on("data",function(B){var C;if("metadata"===B.type){for(C=B.tracks.length;C--;)q||
"video"!==B.tracks[C].type?v||"audio"!==B.tracks[C].type||(v=B.tracks[C],v.timelineStartInfo.baseMediaDecodeTime=m.baseMediaDecodeTime):(q=B.tracks[C],q.timelineStartInfo.baseMediaDecodeTime=m.baseMediaDecodeTime);q&&!w.videoSegmentStream&&(w.coalesceStream.numberOfTracks++,w.videoSegmentStream=new ah(q,h),w.videoSegmentStream.on("log",m.getLogTrigger_("videoSegmentStream")),w.videoSegmentStream.on("timelineStartInfo",function(F){v&&!h.keepOriginalTimestamps&&(v.timelineStartInfo=F,w.audioSegmentStream.setEarliestDts(F.dts-
m.baseMediaDecodeTime))}),w.videoSegmentStream.on("processedGopsInfo",m.trigger.bind(m,"gopInfo")),w.videoSegmentStream.on("segmentTimingInfo",m.trigger.bind(m,"videoSegmentTimingInfo")),w.videoSegmentStream.on("baseMediaDecodeTime",function(F){v&&w.audioSegmentStream.setVideoBaseMediaDecodeTime(F)}),w.videoSegmentStream.on("timingInfo",m.trigger.bind(m,"videoTimingInfo")),w.h264Stream.pipe(w.videoSegmentStream).pipe(w.coalesceStream));v&&!w.audioSegmentStream&&(w.coalesceStream.numberOfTracks++,
w.audioSegmentStream=new Me(v,h),w.audioSegmentStream.on("log",m.getLogTrigger_("audioSegmentStream")),w.audioSegmentStream.on("timingInfo",m.trigger.bind(m,"audioTimingInfo")),w.audioSegmentStream.on("segmentTimingInfo",m.trigger.bind(m,"audioSegmentTimingInfo")),w.adtsStream.pipe(w.audioSegmentStream).pipe(w.coalesceStream));m.trigger("trackinfo",{hasAudio:!!v,hasVideo:!!q})}});w.coalesceStream.on("data",this.trigger.bind(this,"data"));w.coalesceStream.on("id3Frame",function(B){B.dispatchType=w.metadataStream.dispatchType;
m.trigger("id3Frame",B)});w.coalesceStream.on("caption",this.trigger.bind(this,"caption"));w.coalesceStream.on("done",this.trigger.bind(this,"done"));pl(this,w)};this.setBaseMediaDecodeTime=function(w){var B=this.transmuxPipeline_;h.keepOriginalTimestamps||(this.baseMediaDecodeTime=w);v&&(v.timelineStartInfo.dts=void 0,v.timelineStartInfo.pts=void 0,sb.clearDtsInfo(v),B.audioTimestampRolloverStream&&B.audioTimestampRolloverStream.discontinuity());q&&(B.videoSegmentStream&&(B.videoSegmentStream.gopCache_=
[]),q.timelineStartInfo.dts=void 0,q.timelineStartInfo.pts=void 0,sb.clearDtsInfo(q),B.captionStream.reset());B.timestampRolloverStream&&B.timestampRolloverStream.discontinuity()};this.setAudioAppendStart=function(w){v&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(w)};this.setRemux=function(w){var B=this.transmuxPipeline_;h.remux=w;B&&B.coalesceStream&&B.coalesceStream.setRemux(w)};this.alignGopsWith=function(w){q&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(w)};
this.getLogTrigger_=function(w){var B=this;return function(C){C.stream=w;B.trigger("log",C)}};this.push=function(w){if(r){var B=kq(w);B&&"aac"!==this.transmuxPipeline_.type?this.setupAacPipeline():B||"ts"===this.transmuxPipeline_.type||this.setupTsPipeline();r=!1}this.transmuxPipeline_.headOfPipeline.push(w)};this.flush=function(){r=!0;this.transmuxPipeline_.headOfPipeline.flush()};this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()};this.reset=function(){this.transmuxPipeline_.headOfPipeline&&
this.transmuxPipeline_.headOfPipeline.reset()};this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}};bh.prototype=new b;var nc=function(h){var m=""+String.fromCharCode(h[0]);m+=String.fromCharCode(h[1]);m+=String.fromCharCode(h[2]);return m+=String.fromCharCode(h[3])},sl=function(h,m){var r=[],q;if(!m.length)return null;for(q=0;q>>0;var w=nc(h.subarray(q+4,q+8));v=1>>0;return m},ul=function(h){return{isLeading:(h[0]&12)>>>2,dependsOn:h[0]&3,isDependedOn:(h[1]&192)>>>6,hasRedundancy:(h[1]&48)>>>4,paddingValue:(h[1]&14)>>>1,isNonSyncSample:h[1]&1,degradationPriority:h[2]<<
8|h[3]}},vl=function(h){var m={version:h[0],flags:new Uint8Array(h.subarray(1,4)),samples:[]},r=new DataView(h.buffer,h.byteOffset,h.byteLength),q=m.flags[2]&1,v=m.flags[2]&4,w=m.flags[1]&1,B=m.flags[1]&2,C=m.flags[1]&4,F=m.flags[1]&8,J=r.getUint32(4),N=8;q&&(m.dataOffset=r.getInt32(N),N+=4);v&&J&&(q={flags:ul(h.subarray(N,N+4))},N+=4,w&&(q.duration=r.getUint32(N),N+=4),B&&(q.size=r.getUint32(N),N+=4),F&&(q.compositionTimeOffset=1===m.version?r.getInt32(N):r.getUint32(N),N+=4),m.samples.push(q),J--);
for(;J--;)q={},w&&(q.duration=r.getUint32(N),N+=4),B&&(q.size=r.getUint32(N),N+=4),C&&(q.flags=ul(h.subarray(N,N+4)),N+=4),F&&(q.compositionTimeOffset=1===m.version?r.getInt32(N):r.getUint32(N),N+=4),m.samples.push(q);return m},wl=function(h){var m=new DataView(h.buffer,h.byteOffset,h.byteLength);h={version:h[0],flags:new Uint8Array(h.subarray(1,4)),trackId:m.getUint32(4)};var r=h.flags[2]&1,q=h.flags[2]&2,v=h.flags[2]&8,w=h.flags[2]&16,B=h.flags[2]&32,C=h.flags[0]&65536,F=h.flags[0]&131072;var J=
8;r&&(J+=4,h.baseDataOffset=m.getUint32(12),J+=4);q&&(h.sampleDescriptionIndex=m.getUint32(J),J+=4);v&&(h.defaultSampleDuration=m.getUint32(J),J+=4);w&&(h.defaultSampleSize=m.getUint32(J),J+=4);B&&(h.defaultSampleFlags=m.getUint32(J));C&&(h.durationIsEmpty=!0);!r&&F&&(h.baseDataOffsetIsMoof=!0);return h},Bd="undefined"!==typeof window?window:"undefined"!==typeof a?a:"undefined"!==typeof self?self:{},nq=vd.discardEmulationPreventionBytes,oq=function(h,m,r){var q=m,v=r.defaultSampleDuration||0,w=r.defaultSampleSize||
0,B=r.trackId,C=[];h.forEach(function(F){F=vl(F).samples;F.forEach(function(J){void 0===J.duration&&(J.duration=v);void 0===J.size&&(J.size=w);J.trackId=B;J.dts=q;void 0===J.compositionTimeOffset&&(J.compositionTimeOffset=0);"bigint"===typeof q?(J.pts=q+Bd.BigInt(J.compositionTimeOffset),q+=Bd.BigInt(J.duration)):(J.pts=q+J.compositionTimeOffset,q+=J.duration)});C=C.concat(F)});return C},pq=function(h,m){var r=oa(h,["moof","traf"]),q={},v=[];oa(h,["mdat"]).forEach(function(w,B){v.push({mdat:w,traf:r[B]})});
v.forEach(function(w){var B=w.mdat,C=w.traf;w=oa(C,["tfhd"]);var F=wl(w[0]);w=F.trackId;var J=oa(C,["tfdt"]);J=0=X))switch(B[L]&31){case 6:var S=B.subarray(L+1,L+1+X);a:{var ea=L;for(var gb=0;gb>>0};var dh={findBox:oa,
parseType:nc,timescale:function(h){return oa(h,["moov","trak"]).reduce(function(m,r){var q=oa(r,["tkhd"])[0];if(!q)return null;var v=q[0];v=0===v?12:20;q=(q[v]<<24|q[v+1]<<16|q[v+2]<<8|q[v+3])>>>0;r=oa(r,["mdia","mdhd"])[0];if(!r)return null;v=r[0];v=0===v?12:20;m[q]=(r[v]<<24|r[v+1]<<16|r[v+2]<<8|r[v+3])>>>0;return m},{})},startTime:function(h,m){m=oa(m,["moof","traf"]).reduce(function(r,q){var v=oa(q,["tfhd"])[0];v=h[(v[4]<<24|v[5]<<16|v[6]<<8|v[7])>>>0]||9E4;q=oa(q,["tfdt"])[0];var w=new DataView(q.buffer,
q.byteOffset,q.byteLength);q=1===q[0]?e(q.subarray(4,12)):w.getUint32(4);let B;"bigint"===typeof q?B=q/Bd.BigInt(v):"number"!==typeof q||isNaN(q)||(B=q/v);B>>2&63).replace(/^0/,"")):q.codec="mp4a.40.2"):q.codec=q.codec.toLowerCase();if(r=oa(r,["mdia","mdhd"])[0])q.timescale=yl(r);m.push(q)});return m},getTimescaleFromMediaHeader:yl,getEmsgID3:function(h,m=0){return oa(h,
["emsg"]).map(r=>{r=ch.parseEmsgBox(new Uint8Array(r));var q=rq(r.message_data);return{cueTime:ch.scaleTime(r.presentation_time,r.timescale,r.presentation_time_delta,m),duration:ch.scaleTime(r.event_duration,r.timescale),frames:q}})}},zl=function(h){var m=h[1]&31;return m=m<<8|h[2]},Oe=function(h){return!!(h[1]&64)},Pe=function(h){var m=0;1<(h[3]&48)>>>4&&(m+=h[4]+1);return m},eh=function(h){switch(h){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";
case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}};var za={parseType:function(h,m){h=zl(h);return 0===h?"pat":h===m?"pmt":m?"pes":null},parsePat:function(h){var m=Oe(h),r=4+Pe(h);m&&(r+=h[r]+1);return(h[r+10]&31)<<8|h[r+11]},parsePmt:function(h){var m={},r=Oe(h),q=4+Pe(h);r&&(q+=h[q]+1);if(h[q+5]&1){r=3+((h[q+1]&15)<<8|h[q+2])-4;for(var v=12+((h[q+10]&15)<<8|h[q+11]);v=h.byteLength)return null;var r=null;var q=h[m+7];q&192&&(r={},r.pts=(h[m+9]&14)<<27|(h[m+10]&255)<<20|(h[m+11]&254)<<12|(h[m+12]&255)<<5|(h[m+13]&254)>>>3,r.pts*=4,r.pts+=(h[m+13]&6)>>>1,r.dts=r.pts,q&
64&&(r.dts=(h[m+14]&14)<<27|(h[m+15]&255)<<20|(h[m+16]&254)<<12|(h[m+17]&255)<<5|(h[m+18]&254)>>>3,r.dts*=4,r.dts+=(h[m+18]&6)>>>1));return r},videoPacketContainsKeyFrame:function(h){var m=4+Pe(h);h=h.subarray(m);for(var r=m=0,q=!1;rh.length-C){r=!0;break}B=Qb.parseId3TagSize(h,
C);if(B>h.length){r=!0;break}null===w&&(F=h.subarray(C,C+B),w=Qb.parseAacTimestamp(F));C+=B;break;case "audio":if(7>h.length-C){r=!0;break}B=Qb.parseAdtsSize(h,C);if(B>h.length){r=!0;break}null===v&&(F=h.subarray(C,C+B),v=Qb.parseSampleRate(F));q++;C+=B;break;default:C++}if(r){h=null;break a}}null===v||null===w?h=null:(h=oc/v,h={audio:[{type:"audio",dts:w,pts:w},{type:"audio",dts:w+1024*q*h,pts:w+1024*q*h}]})}else{q={pid:null,table:null};w={};sq(h,q);for(r in q.table)if(q.table.hasOwnProperty(r))switch(q.table[r]){case La.H264_STREAM_TYPE:w.video=
[];var J=void 0,N=void 0,L=void 0;v=N=L=N=L=void 0;B=h;C=q;F=w;var X=0,S=188,ea=!1,gb=[];for(J=0;S{a.buffer=[];b(a)},Cl=a=>{const {transmuxer:b,bytes:c,audioAppendStart:e,gopsToAlignWith:g,remux:l,onData:p,onTrackInfo:t,onAudioTimingInfo:x,onVideoTimingInfo:y,onVideoSegmentTimingInfo:A,onAudioSegmentTimingInfo:z,onId3:E,
onCaptions:I,onDone:G,onEndedTimeline:O,onTransmuxerLog:Q,isEndOfTimeline:V}=a,T={buffer:[]};let ca=V;b.onmessage=K=>{if(b.currentTransmux===a){if("data"===K.data.action){const {type:ta,initSegment:Fa,captions:W,captionStreams:Da,metadata:Qg,videoFrameDtsTime:De,videoFramePtsTime:Ce}=K.data.segment;T.buffer.push({captions:W,captionStreams:Da,metadata:Qg});var ba=K.data.segment.boxes||{data:K.data.segment.data};ba={type:ta,data:new Uint8Array(ba.data,ba.data.byteOffset,ba.data.byteLength),initSegment:new Uint8Array(Fa.data,
Fa.byteOffset,Fa.byteLength)};"undefined"!==typeof De&&(ba.videoFrameDtsTime=De);"undefined"!==typeof Ce&&(ba.videoFramePtsTime=Ce);p(ba)}"trackinfo"===K.data.action&&t(K.data.trackInfo);"gopInfo"===K.data.action&&(T.gopInfo=K.data.gopInfo);"audioTimingInfo"===K.data.action&&x(K.data.audioTimingInfo);"videoTimingInfo"===K.data.action&&y(K.data.videoTimingInfo);"videoSegmentTimingInfo"===K.data.action&&A(K.data.videoSegmentTimingInfo);"audioSegmentTimingInfo"===K.data.action&&z(K.data.audioSegmentTimingInfo);
"id3Frame"===K.data.action&&E([K.data.id3Frame],K.data.id3Frame.dispatchType);"caption"===K.data.action&&I(K.data.caption);"endedtimeline"===K.data.action&&(ca=!1,O());"log"===K.data.action&&Q(K.data.log);"transmuxed"!==K.data.type||ca||(b.onmessage=null,yq({transmuxedData:T,callback:G}),fh(b))}};e&&b.postMessage({action:"setAudioAppendStart",appendStart:e});Array.isArray(g)&&b.postMessage({action:"alignGopsWith",gopsToAlignWith:g});"undefined"!==typeof l&&b.postMessage({action:"setRemux",remux:l});
if(c.byteLength){const K=c instanceof ArrayBuffer?c:c.buffer;b.postMessage({action:"push",data:K,byteOffset:c instanceof ArrayBuffer?0:c.byteOffset,byteLength:c.byteLength},[K])}V&&b.postMessage({action:"endTimeline"});b.postMessage({action:"flush"})},fh=a=>{a.currentTransmux=null;a.transmuxQueue.length&&(a.currentTransmux=a.transmuxQueue.shift(),"function"===typeof a.currentTransmux?a.currentTransmux():Cl(a.currentTransmux))},zq=(a,b)=>{a.postMessage({action:b});fh(a)},Dl=(a,b)=>{b.currentTransmux?
b.transmuxQueue.push(zq.bind(null,b,a)):(b.currentTransmux=a,b.postMessage({action:a}),fh(b))},El=a=>{a.transmuxer.currentTransmux?a.transmuxer.transmuxQueue.push(a):(a.transmuxer.currentTransmux=a,Cl(a))};var gh={reset:a=>{Dl("reset",a)},endTimeline:a=>{Dl("endTimeline",a)},transmux:El,createTransmuxer:a=>{const b=new xq;b.currentTransmux=null;b.transmuxQueue=[];const c=b.terminate;b.terminate=()=>{b.currentTransmux=null;b.transmuxQueue.length=0;return c.call(b)};b.postMessage({action:"init",options:a});
return b}};const Dd=function(a){const b=a.transmuxer,c=a.endAction||a.action,e=a.callback,g=nb({},a,{endAction:null,transmuxer:null,callback:null}),l=p=>{p.data.action===c&&(b.removeEventListener("message",l),p.data.data&&(p.data.data=new Uint8Array(p.data.data,a.byteOffset||0,a.byteLength||p.data.data.byteLength),a.data&&(a.data=p.data.data)),e(p.data))};b.addEventListener("message",l);if(a.data){const p=a.data instanceof ArrayBuffer;g.byteOffset=p?0:a.data.byteOffset;g.byteLength=a.data.byteLength;
b.postMessage(g,[p?a.data:a.data.buffer])}else b.postMessage(g)},hh=a=>{a.forEach(b=>{b.abort()})},ih=(a,b)=>b.timedout?{status:b.status,message:"HLS request timed-out at URL: "+b.uri,code:-101,xhr:b}:b.aborted?{status:b.status,message:"HLS request aborted at URL: "+b.uri,code:-102,xhr:b}:a?{status:b.status,message:"HLS request errored at URL: "+b.uri,code:2,xhr:b}:"arraybuffer"===b.responseType&&0===b.response.byteLength?{status:b.status,message:"Empty HLS response at URL: "+b.uri,code:2,xhr:b}:
null,Fl=(a,b,c)=>(e,g)=>{var l=g.response;if(e=ih(e,g))return c(e,a);if(16!==l.byteLength)return c({status:g.status,message:"Invalid HLS key at URL: "+g.uri,code:2,xhr:g},a);g=new DataView(l);g=new Uint32Array([g.getUint32(0),g.getUint32(4),g.getUint32(8),g.getUint32(12)]);for(l=0;l{var c=Vf(a.map.bytes);if("mp4"!==c)return c=c||"unknown",b({internal:!0,message:`Found unsupported ${c} container for initialization segment at URL: ${a.map.resolvedUri||
a.map.uri}`,code:2,metadata:{errorType:H.Error.UnsupportedMediaInitialization,mediaType:c}});Dd({action:"probeMp4Tracks",data:a.map.bytes,transmuxer:a.transmuxer,callback:({tracks:e,data:g})=>{a.map.bytes=g;e.forEach(function(l){a.map.tracks=a.map.tracks||{};a.map.tracks[l.type]||(a.map.tracks[l.type]=l,"number"===typeof l.id&&l.timescale&&(a.map.timescales=a.map.timescales||{},a.map.timescales[l.id]=l.timescale))});return b(null)}})},Aq=({segment:a,finishProcessingFn:b})=>(c,e)=>{if(c=ih(c,e))return b(c,
a);c=new Uint8Array(e.response);if(a.map.key)return a.map.encryptedBytes=c,b(null,a);a.map.bytes=c;Gl(a,function(g){if(g)return g.xhr=e,g.status=e.status,b(g,a);b(null,a)})},Bq=({segment:a,finishProcessingFn:b,responseType:c})=>(e,g)=>{if(e=ih(e,g))return b(e,a);if("arraybuffer"!==c&&g.responseText){e=g.responseText.substring(a.lastReachedChar||0);const l=new Uint8Array(new ArrayBuffer(e.length));for(let p=0;p{const I=a.map&&a.map.tracks||{},G=!(!I.audio||!I.video);let O=e.bind(null,a,"audio","start");const Q=e.bind(null,a,"audio","end");let V=e.bind(null,
a,"video","start");const T=e.bind(null,a,"video","end"),ca=()=>El({bytes:b,transmuxer:a.transmuxer,audioAppendStart:a.audioAppendStart,gopsToAlignWith:a.gopsToAlignWith,remux:G,onData:K=>{K.type="combined"===K.type?"video":K.type;A(a,K)},onTrackInfo:K=>{c&&(G&&(K.isMuxed=!0),c(a,K))},onAudioTimingInfo:K=>{O&&"undefined"!==typeof K.start&&(O(K.start),O=null);Q&&"undefined"!==typeof K.end&&Q(K.end)},onVideoTimingInfo:K=>{V&&"undefined"!==typeof K.start&&(V(K.start),V=null);T&&"undefined"!==typeof K.end&&
T(K.end)},onVideoSegmentTimingInfo:K=>{g(K)},onAudioSegmentTimingInfo:K=>{l(K)},onId3:(K,ba)=>{p(a,K,ba)},onCaptions:K=>{t(a,[K])},isEndOfTimeline:x,onEndedTimeline:()=>{y()},onTransmuxerLog:E,onDone:K=>{z&&(K.type="combined"===K.type?"video":K.type,z(null,a,K))}});Dd({action:"probeTs",transmuxer:a.transmuxer,data:b,baseStartTime:a.baseStartTime,callback:K=>{a.bytes=b=K.data;if(K=K.result)c(a,{hasAudio:K.hasAudio,hasVideo:K.hasVideo,isMuxed:G}),c=null;ca()}})},Hl=({segment:a,bytes:b,trackInfoFn:c,
timingInfoFn:e,videoSegmentTimingInfoFn:g,audioSegmentTimingInfoFn:l,id3Fn:p,captionsFn:t,isEndOfTimeline:x,endedTimelineFn:y,dataFn:A,doneFn:z,onTransmuxerLog:E})=>{let I=new Uint8Array(b);if(0{A(a,{data:I,type:O.hasAudio&&!O.isMuxed?"audio":"video"});T&&T.length&&p(a,T);V&&V.length&&t(a,V);z(null,a,{})};Dd({action:"probeMp4StartTime",timescales:a.map.timescales,data:I,transmuxer:a.transmuxer,callback:({data:V,startTime:T})=>{b=V.buffer;a.bytes=I=V;O.hasAudio&&!O.isMuxed&&e(a,"audio","start",T);O.hasVideo&&e(a,"video","start",T);Dd({action:"probeEmsgID3",data:I,transmuxer:a.transmuxer,offset:T,callback:({emsgData:ca,id3Frames:K})=>{b=ca.buffer;a.bytes=I=ca;G.video&&ca.byteLength&&
a.transmuxer?Dd({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:a.transmuxer,data:I,timescales:a.map.timescales,trackIds:[G.video.id],callback:ba=>{b=ba.data.buffer;a.bytes=I=ba.data;ba.logs.forEach(function(ta){E(ia(ta,{stream:"mp4CaptionParser"}))});Q(ba.captions,K)}}):Q(void 0,K)}})}})}else a.transmuxer?("undefined"===typeof a.container&&(a.container=Vf(I)),"ts"!==a.container&&"aac"!==a.container?(c(a,{hasAudio:!1,hasVideo:!1}),z(null,a,{})):Cq({segment:a,bytes:b,trackInfoFn:c,timingInfoFn:e,
videoSegmentTimingInfoFn:g,audioSegmentTimingInfoFn:l,id3Fn:p,captionsFn:t,isEndOfTimeline:x,endedTimelineFn:y,dataFn:A,doneFn:z,onTransmuxerLog:E})):z(null,a,{})},Il=function({id:a,key:b,encryptedBytes:c,decryptionWorker:e},g){const l=t=>{t.data.source===a&&(e.removeEventListener("message",l),t=t.data.decrypted,g(new Uint8Array(t.bytes,t.byteOffset,t.byteLength)))};e.addEventListener("message",l);let p;p=b.bytes.slice?b.bytes.slice():new Uint32Array(Array.prototype.slice.call(b.bytes));e.postMessage(Tk({source:a,
encrypted:c,key:p,iv:b.iv}),[c.buffer,p.buffer])},Dq=({decryptionWorker:a,segment:b,trackInfoFn:c,timingInfoFn:e,videoSegmentTimingInfoFn:g,audioSegmentTimingInfoFn:l,id3Fn:p,captionsFn:t,isEndOfTimeline:x,endedTimelineFn:y,dataFn:A,doneFn:z,onTransmuxerLog:E})=>{Il({id:b.requestId,key:b.key,encryptedBytes:b.encryptedBytes,decryptionWorker:a},I=>{b.bytes=I;Hl({segment:b,bytes:b.bytes,trackInfoFn:c,timingInfoFn:e,videoSegmentTimingInfoFn:g,audioSegmentTimingInfoFn:l,id3Fn:p,captionsFn:t,isEndOfTimeline:x,
endedTimelineFn:y,dataFn:A,doneFn:z,onTransmuxerLog:E})})},Eq=({activeXhrs:a,decryptionWorker:b,trackInfoFn:c,timingInfoFn:e,videoSegmentTimingInfoFn:g,audioSegmentTimingInfoFn:l,id3Fn:p,captionsFn:t,isEndOfTimeline:x,endedTimelineFn:y,dataFn:A,doneFn:z,onTransmuxerLog:E})=>{let I=0,G=!1;return(O,Q)=>{if(!G){if(O)return G=!0,hh(a),z(O,Q);I+=1;if(I===a.length){const V=function(){if(Q.encryptedBytes)return Dq({decryptionWorker:b,segment:Q,trackInfoFn:c,timingInfoFn:e,videoSegmentTimingInfoFn:g,audioSegmentTimingInfoFn:l,
id3Fn:p,captionsFn:t,isEndOfTimeline:x,endedTimelineFn:y,dataFn:A,doneFn:z,onTransmuxerLog:E});Hl({segment:Q,bytes:Q.bytes,trackInfoFn:c,timingInfoFn:e,videoSegmentTimingInfoFn:g,audioSegmentTimingInfoFn:l,id3Fn:p,captionsFn:t,isEndOfTimeline:x,endedTimelineFn:y,dataFn:A,doneFn:z,onTransmuxerLog:E})};Q.endOfAllRequests=Date.now();if(Q.map&&Q.map.encryptedBytes&&!Q.map.bytes)return Il({decryptionWorker:b,id:Q.requestId+"-init",encryptedBytes:Q.map.encryptedBytes,key:Q.map.key},T=>{Q.map.bytes=T;Gl(Q,
ca=>{if(ca)return hh(a),z(ca,Q);V()})});V()}}}},Fq=({loadendState:a,abortFn:b})=>c=>{c.target.aborted&&b&&!a.calledAbortFn&&(b(),a.calledAbortFn=!0)},Gq=({segment:a,progressFn:b})=>c=>{if(!c.target.aborted){var e=a.stats,g=c.target;g=Date.now()-g.requestTime;g={bandwidth:Infinity,bytesReceived:0,roundTripTime:g||0};g.bytesReceived=c.loaded;g.bandwidth=Math.floor(g.bytesReceived/g.roundTripTime*8E3);a.stats=ia(e,g);!a.stats.firstBytesReceivedAt&&a.stats.bytesReceived&&(a.stats.firstBytesReceivedAt=
Date.now());return b(c,a)}},Hq=({xhr:a,xhrOptions:b,decryptionWorker:c,segment:e,abortFn:g,progressFn:l,trackInfoFn:p,timingInfoFn:t,videoSegmentTimingInfoFn:x,audioSegmentTimingInfoFn:y,id3Fn:A,captionsFn:z,isEndOfTimeline:E,endedTimelineFn:I,dataFn:G,doneFn:O,onTransmuxerLog:Q})=>{const V=[];c=Eq({activeXhrs:V,decryptionWorker:c,trackInfoFn:p,timingInfoFn:t,videoSegmentTimingInfoFn:x,audioSegmentTimingInfoFn:y,id3Fn:A,captionsFn:z,isEndOfTimeline:E,endedTimelineFn:I,dataFn:G,doneFn:O,onTransmuxerLog:Q});
e.key&&!e.key.bytes&&(Q=[e.key],e.map&&!e.map.bytes&&e.map.key&&e.map.key.resolvedUri===e.key.resolvedUri&&Q.push(e.map.key),O=ia(b,{uri:e.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),Q=Fl(e,Q,c),O=a(O,Q),V.push(O));e.map&&!e.map.bytes&&(!e.map.key||e.key&&e.key.resolvedUri===e.map.key.resolvedUri||(O=ia(b,{uri:e.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),Q=Fl(e,[e.map.key],c),O=a(O,Q),V.push(O)),O=ia(b,{uri:e.map.resolvedUri,responseType:"arraybuffer",
headers:Og(e.map),requestType:"segment-media-initialization"}),Q=Aq({segment:e,finishProcessingFn:c}),O=a(O,Q),V.push(O));b=ia(b,{uri:e.part&&e.part.resolvedUri||e.resolvedUri,responseType:"arraybuffer",headers:Og(e),requestType:"segment"});c=Bq({segment:e,finishProcessingFn:c,responseType:b.responseType});a=a(b,c);a.addEventListener("progress",Gq({segment:e,progressFn:l,trackInfoFn:p,timingInfoFn:t,videoSegmentTimingInfoFn:x,audioSegmentTimingInfoFn:y,id3Fn:A,captionsFn:z,isEndOfTimeline:E,endedTimelineFn:I,
dataFn:G}));V.push(a);const T={};V.forEach(ca=>{ca.addEventListener("loadend",Fq({loadendState:T,abortFn:g}))});return()=>hh(V)},Iq=mb("CodecUtils"),Jl=(a,b)=>{b=b.attributes||{};return a&&a.mediaGroups&&a.mediaGroups.AUDIO&&b.AUDIO&&a.mediaGroups.AUDIO[b.AUDIO]},Qe=function(a){const b={};a.forEach(({mediaType:c,type:e,details:g})=>{b[c]=b[c]||[];b[c].push(Li(`${e}${g}`))});Object.keys(b).forEach(function(c){1{let O;const Q=G.attributes&&G.attributes.RESOLUTION&&G.attributes.RESOLUTION.width,V=G.attributes&&G.attributes.RESOLUTION&&G.attributes.RESOLUTION.height;O=(O=G.attributes&&G.attributes.BANDWIDTH)||D.Number.MAX_VALUE;return{bandwidth:O,width:Q,height:V,playlist:G}});Tc(x,(G,O)=>G.bandwidth-O.bandwidth);
x=x.filter(G=>!Ya.isIncompatible(G.playlist));a=x.filter(G=>Ya.isEnabled(G.playlist));a.length||(a=x.filter(G=>!Ya.isDisabled(G.playlist)));var y=a.filter(G=>G.bandwidth*Ha.BANDWIDTH_VARIANCEG.bandwidth===A.bandwidth)[0];if(!1===g){var z=t||a[0]||x[0];if(z&&z.playlist){var E="sortedPlaylistReps";t&&(E="bandwidthBestRep");a[0]&&(E="enabledPlaylistReps");Re(`choosing ${Ll(z)} using ${E} with options`,p);return z.playlist}Re("could not choose a playlist with options",
p);return null}y=y.filter(G=>G.width&&G.height);Tc(y,(G,O)=>G.width-O.width);g=y.filter(G=>G.width===c&&G.height===e);A=g[g.length-1];g=g.filter(G=>G.bandwidth===A.bandwidth)[0];if(!g){var I=y.filter(G=>G.width>c||G.height>e);z=I.filter(G=>G.width===I[0].width&&G.height===I[0].height);A=z[z.length-1];z=z.filter(G=>G.bandwidth===A.bandwidth)[0]}l.leastPixelDiffSelector&&(E=y.map(G=>{G.pixelDiff=Math.abs(G.width-c)+Math.abs(G.height-e);return G}),Tc(E,(G,O)=>G.pixelDiff===O.pixelDiff?O.bandwidth-G.bandwidth:
G.pixelDiff-O.pixelDiff),E=E[0]);if((l=E||z||g||t||a[0]||x[0])&&l.playlist)return x="sortedPlaylistReps",E?x="leastPixelDiffRep":z?x="resolutionPlusOneRep":g?x="resolutionBestRep":t?x="bandwidthBestRep":a[0]&&(x="enabledPlaylistReps"),Re(`choosing ${Ll(l)} using ${x} with options`,p),l.playlist;Re("could not choose a playlist with options",p);return null}};const Nl=function(){let a=this.useDevicePixelRatio?D.devicePixelRatio||1:1;isNaN(this.customPixelRatio)||(a=this.customPixelRatio);return Ml(this.playlists.main,
this.systemBandwidth,parseInt(Se(this.tech_.el(),"width"),10)*a,parseInt(Se(this.tech_.el(),"height"),10)*a,this.limitRenditionByPlayerDimensions,this.playlistController_)},Jq=function(a){const {main:b,currentTime:c,bandwidth:e,duration:g,segmentDuration:l,timeUntilRebuffer:p,currentTimeline:t,syncController:x}=a;a=b.playlists.filter(A=>!Ya.isIncompatible(A));var y=a.filter(Ya.isEnabled);y.length||(y=a.filter(A=>!Ya.isDisabled(A)));a=y.filter(Ya.hasAttribute.bind(null,"BANDWIDTH")).map(A=>{var z=
x.getSyncPoint(A,g,t,c)?1:2;z=Ya.estimateSegmentRequestTime(l,e,A)*z-p;return{playlist:A,rebufferingImpact:z}});y=a.filter(A=>0>=A.rebufferingImpact);Tc(y,(A,z)=>jh(z.playlist,A.playlist));if(y.length)return y[0];Tc(a,(A,z)=>A.rebufferingImpact-z.rebufferingImpact);return a[0]||null},Kq=a=>{let b=0,c;a.bytes&&(c=new Uint8Array(a.bytes),a.segments.forEach(e=>{c.set(e,b);b+=e.byteLength}));return c},Lq=function({inbandTextTracks:a,captionArray:b,timestampOffset:c}){if(b){var e=D.WebKitDataCue||D.VTTCue;
b.forEach(g=>{const l=g.stream;g.content?g.content.forEach(p=>{const t=new e(g.startTime+c,g.endTime+c,p.text);t.line=p.line;t.align="left";t.position=p.position;t.positionAlign="line-left";a[l].addCue(t)}):a[l].addCue(new e(g.startTime+c,g.endTime+c,g.text))})}},Mq=function(a){Object.defineProperties(a.frame,{id:{get(){H.log.warn("cue.frame.id is deprecated. Use cue.value.key instead.");return a.value.key}},value:{get(){H.log.warn("cue.frame.value is deprecated. Use cue.value.data instead.");return a.value.data}},
privateData:{get(){H.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead.");return a.value.data}}})},Nq=({inbandTextTracks:a,metadataArray:b,timestampOffset:c,videoDuration:e})=>{if(b){var g=D.WebKitDataCue||D.VTTCue,l=a.metadataTrack_;if(l&&(b.forEach(x=>{const y=x.cueTime+c;!("number"!==typeof y||D.isNaN(y)||0>y)&&Infinity>y&&x.frames&&x.frames.length&&x.frames.forEach(A=>{const z=new g(y,y,A.value||A.url||A.data||"");z.frame=A;z.value=A;Mq(z);l.addCue(z)})}),l.cues&&l.cues.length)){a=
l.cues;b=[];for(let x=0;x{const A=x[y.startTime]||[];A.push(y);x[y.startTime]=A;return x},{}),t=Object.keys(p).sort((x,y)=>Number(x)-Number(y));t.forEach((x,y)=>{const A=p[x];x=isFinite(e)?e:x;const z=Number(t[y+1])||x;A.forEach(E=>{E.endTime=z})})}}},Oq={id:"ID",class:"CLASS",startDate:"START-DATE",duration:"DURATION",endDate:"END-DATE",endOnNext:"END-ON-NEXT",plannedDuration:"PLANNED-DURATION",scte35Out:"SCTE35-OUT",scte35In:"SCTE35-IN"},Pq=
new Set("id class startDate duration endDate endOnNext startTime endTime processDateRange".split(" ")),Qq=({inbandTextTracks:a,dateRanges:b})=>{const c=a.metadataTrack_;if(c){var e=D.WebKitDataCue||D.VTTCue;b.forEach(g=>{for(const l of Object.keys(g)){if(Pq.has(l))continue;const p=new e(g.startTime,g.endTime,"");p.id=g.id;p.type="com.apple.quicktime.HLS";p.value={key:Oq[l],data:g[l]};if("scte35Out"===l||"scte35In"===l)p.value.data=(new Uint8Array(p.value.data.match(/[\da-f]{2}/gi))).buffer;c.addCue(p)}g.processDateRange()})}},
Ol=(a,b,c)=>{a.metadataTrack_||(a.metadataTrack_=c.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,H.browser.IS_ANY_SAFARI||(a.metadataTrack_.inBandMetadataTrackDispatchType=b))},Fd=function(a,b,c){let e,g;if(c&&c.cues)for(e=c.cues.length;e--;)g=c.cues[e],g.startTime>=a&&g.endTime<=b&&c.removeCue(g)},Rq=function(a){const b=a.cues;if(b){var c={};for(let e=b.length-1;0<=e;e--){const g=b[e],l=`${g.startTime}-${g.endTime}-${g.text}`;c[l]?a.removeCue(g):c[l]=g}}},Sq=(a,b,c,e)=>{b=
Math.ceil(9E4*(b-e));var g=Math.ceil(9E4*(c-e));c=a.slice();for(e=a.length;e--&&!(a[e].pts<=g););if(-1===e)return c;for(g=e+1;g--&&!(a[g].pts<=b););g=Math.max(g,0);c.splice(g,e-g+1);return c},Tq=function(a,b){if(!a&&!b||!a&&b||a&&!b)return!1;if(a===b)return!0;const c=Object.keys(a).sort(),e=Object.keys(b).sort();if(c.length!==e.length)return!1;for(let g=0;g{const {startOfSegment:b,duration:c,segment:e,part:g,playlist:{mediaSequence:l,
id:p,segments:t=[]},mediaIndex:x,partIndex:y,timeline:A}=a,z=t.length-1;let E="mediaIndex/partIndex increment";a.getMediaInfoForTime?E=`getMediaInfoForTime (${a.getMediaInfoForTime})`:a.isSyncRequest&&(E="getSyncSegmentCandidate (isSyncRequest)");a.independent&&(E+=` with independent ${a.independent}`);const I="number"===typeof y;a=a.segment.uri?"segment":"pre-segment";const G=I?Ck({preloadSegment:e})-1:0;return`${a} [${l+x}/${l+z}]`+(I?` part [${y}/${G}]`:"")+` segment start/end [${e.start} => ${e.end}]`+
(I?` part start/end [${g.start} => ${g.end}]`:"")+` startOfSegment [${b}]`+` duration [${c}]`+` timeline [${A}]`+` selected by [${E}]`+` playlist [${p}]`},Uq=({segmentTimeline:a,currentTimeline:b,startOfSegment:c,buffered:e,overrideCheck:g})=>g||a!==b?ab===c?!1:"audio"===e?(a=a.lastTimelineChange({type:"main"}),!a||a.to!==c):"main"===e&&g?(a=a.pendingTimelineChange({type:"audio"}))&&
a.to===c?!1:!0:!1,Vq=a=>{let b=0;["video","audio"].forEach(function(c){if(c=a[`${c}TimingInfo`]){var {start:e,end:g}=c,l;"bigint"===typeof e||"bigint"===typeof g?l=D.BigInt(g)-D.BigInt(e):"number"===typeof e&&"number"===typeof g&&(l=g-e);"undefined"!==typeof l&&l>b&&(b=l)}});"bigint"===typeof b&&ba?Math.round(a)>b+Db:!1;class kh extends H.EventTarget{constructor(a,b){super();if(!a)throw new TypeError("Initialization settings are required");
if("function"!==typeof a.currentTime)throw new TypeError("No currentTime getter specified");if(!a.mediaSource)throw new TypeError("No MediaSource specified");this.bandwidth=a.bandwidth;this.throughput={rate:0,count:0};this.roundTrip=NaN;this.resetStats_();this.partIndex=this.mediaIndex=null;this.hasPlayed_=a.hasPlayed;this.currentTime_=a.currentTime;this.seekable_=a.seekable;this.seeking_=a.seeking;this.duration_=a.duration;this.mediaSource_=a.mediaSource;this.vhs_=a.vhs;this.loaderType_=a.loaderType;
this.startingMediaInfo_=this.currentMediaInfo_=void 0;this.segmentMetadataTrack_=a.segmentMetadataTrack;this.goalBufferLength_=a.goalBufferLength;this.sourceType_=a.sourceType;this.sourceUpdater_=a.sourceUpdater;this.inbandTextTracks_=a.inbandTextTracks;this.state_="INIT";this.timelineChangeController_=a.timelineChangeController;this.shouldSaveSegmentTimingInfo_=!0;this.parse708captions_=a.parse708captions;this.useDtsForTimestampOffset_=a.useDtsForTimestampOffset;this.captionServices_=a.captionServices;
this.exactManifestTimings=a.exactManifestTimings;this.addMetadataToTextTrack=a.addMetadataToTextTrack;this.checkBufferTimeout_=null;this.error_=void 0;this.currentTimeline_=-1;this.shouldForceTimestampOffsetAfterResync_=!1;this.xhrOptions_=this.pendingSegment_=null;this.pendingSegments_=[];this.isPendingTimestampOffset_=this.audioDisabled_=!1;this.gopBuffer_=[];this.timeMapping_=0;this.safeAppend_=!1;this.appendInitSegment_={audio:!0,video:!0};this.playlistOfLastInitSegment_={audio:null,video:null};
this.callQueue_=[];this.loadQueue_=[];this.metadataQueue_={id3:[],caption:[]};this.waitingOnRemove_=!1;this.activeInitSegmentId_=this.quotaExceededErrorRetryTimeout_=null;this.initSegments_={};this.cacheEncryptionKeys_=a.cacheEncryptionKeys;this.keyCache_={};this.decrypter_=a.decrypter;this.syncController_=a.syncController;this.syncPoint_={segmentIndex:0,time:0};this.transmuxer_=this.createTransmuxer_();this.triggerSyncInfoUpdate_=()=>this.trigger("syncinfoupdate");this.syncController_.on("syncinfoupdate",
this.triggerSyncInfoUpdate_);this.mediaSource_.addEventListener("sourceopen",()=>{this.isEndOfStream_()||(this.ended_=!1)});this.fetchAtBuffer_=!1;this.logger_=mb(`SegmentLoader[${this.loaderType_}]`);Object.defineProperty(this,"state",{get(){return this.state_},set(c){c!==this.state_&&(this.logger_(`${this.state_} -> ${c}`),this.state_=c,this.trigger("statechange"))}});this.sourceUpdater_.on("ready",()=>{this.hasEnoughInfoToAppend_()&&this.processCallQueue_()});if("main"===this.loaderType_)this.timelineChangeController_.on("pendingtimelinechange",
()=>{this.hasEnoughInfoToAppend_()&&this.processCallQueue_()});if("audio"===this.loaderType_)this.timelineChangeController_.on("timelinechange",()=>{this.hasEnoughInfoToLoad_()&&this.processLoadQueue_();this.hasEnoughInfoToAppend_()&&this.processCallQueue_()})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return gh.createTransmuxer({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,
captionServices:this.captionServices_})}resetStats_(){this.mediaAppends=this.mediaSecondsLoaded=this.mediaTransferDuration=this.mediaRequestsErrored=this.mediaRequestsTimedout=this.mediaRequestsAborted=this.mediaRequests=this.mediaBytesTransferred=0}dispose(){this.trigger("dispose");this.state="DISPOSED";this.pause();this.abort_();this.transmuxer_&&this.transmuxer_.terminate();this.resetStats_();this.checkBufferTimeout_&&D.clearTimeout(this.checkBufferTimeout_);this.syncController_&&this.triggerSyncInfoUpdate_&&
this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_);this.off()}setAudio(a){this.audioDisabled_=!a;a?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){"WAITING"!==this.state?this.pendingSegment_&&(this.pendingSegment_=null):(this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_())}abort_(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests();this.pendingSegment_=null;this.callQueue_=
[];this.loadQueue_=[];this.metadataQueue_.id3=[];this.metadataQueue_.caption=[];this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);this.waitingOnRemove_=!1;D.clearTimeout(this.quotaExceededErrorRetryTimeout_);this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(a){return"APPENDING"!==this.state||this.pendingSegment_?this.pendingSegment_&&this.pendingSegment_.requestId===a?!1:!0:(this.state="READY",!0)}error(a){"undefined"!==typeof a&&(this.logger_("error occurred:",a),
this.error_=a);this.pendingSegment_=null;return this.error_}endOfStream(){this.ended_=!0;this.transmuxer_&&gh.reset(this.transmuxer_);this.gopBuffer_.length=0;this.pause();this.trigger("ended")}buffered_(){const a=this.getMediaInfo_();if(!this.sourceUpdater_||!a)return Na();if("main"===this.loaderType_){const {hasAudio:b,hasVideo:c,isMuxed:e}=a;if(c&&b&&!this.audioDisabled_&&!e)return this.sourceUpdater_.buffered();if(c)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(a,
b=!1){if(!a)return null;const c=Be(a);let e=this.initSegments_[c];b&&!e&&a.bytes&&(this.initSegments_[c]=e={resolvedUri:a.resolvedUri,byterange:a.byterange,bytes:a.bytes,tracks:a.tracks,timescales:a.timescales});return e||a}segmentKey(a,b=!1){if(!a)return null;const c=a.resolvedUri;let e=this.keyCache_[c];this.cacheEncryptionKeys_&&b&&!e&&a.bytes&&(this.keyCache_[c]=e={resolvedUri:a.resolvedUri,bytes:a.bytes});a={resolvedUri:(e||a).resolvedUri};e&&(a.bytes=e.bytes);return a}couldBeginLoading_(){return this.playlist_&&
!this.paused()}load(){this.monitorBuffer_();if(this.playlist_){if("INIT"===this.state&&this.couldBeginLoading_())return this.init_();!this.couldBeginLoading_()||"READY"!==this.state&&"INIT"!==this.state||(this.state="READY")}}init_(){this.state="READY";this.resetEverything();return this.monitorBuffer_()}playlist(a,b={}){if(a){var c=this.playlist_,e=this.pendingSegment_;this.playlist_=a;this.xhrOptions_=b;"INIT"===this.state&&(a.syncInfo={mediaSequence:a.mediaSequence,time:0},"main"===this.loaderType_&&
this.syncController_.setDateTimeMappingForStart(a));b=null;c&&(c.id?b=c.id:c.uri&&(b=c.uri));this.logger_(`playlist update [${b} => ${a.id||a.uri}]`);this.mediaSequenceSync_&&(this.mediaSequenceSync_.update(a,this.currentTime_()),this.logger_(`Playlist update:\ncurrentTime: ${this.currentTime_()}\nbufferedEnd: ${Eg(this.buffered_())}\n`,this.mediaSequenceSync_.diagnostics));this.trigger("syncinfoupdate");if("INIT"===this.state&&this.couldBeginLoading_())return this.init_();if(c&&c.uri===a.uri){b=
a.mediaSequence-c.mediaSequence;this.logger_(`live window shift [${b}]`);if(null!==this.mediaIndex)if(this.mediaIndex-=b,0>this.mediaIndex)this.partIndex=this.mediaIndex=null;else{var g=this.playlist_.segments[this.mediaIndex];!this.partIndex||g.parts&&g.parts.length&&g.parts[this.partIndex]||(g=this.mediaIndex,this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=g)}e&&(e.mediaIndex-=b,0>e.mediaIndex?(e.mediaIndex=null,e.partIndex=
null):(0<=e.mediaIndex&&(e.segment=a.segments[e.mediaIndex]),0<=e.partIndex&&e.segment.parts&&(e.part=e.segment.parts[e.partIndex])));this.syncController_.saveExpiredSegmentInfo(c,a)}else null!==this.mediaIndex&&(a.endList||"number"!==typeof a.partTargetDuration?this.resyncLoader():this.resetLoader()),this.currentMediaInfo_=void 0,this.trigger("playlistupdate")}}pause(){this.checkBufferTimeout_&&(D.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=null)}paused(){return null===this.checkBufferTimeout_}resetEverything(a){this.ended_=
!1;this.activeInitSegmentId_=null;this.appendInitSegment_={audio:!0,video:!0};this.resetLoader();this.remove(0,Infinity,a);this.transmuxer_&&(this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.transmuxer_.postMessage({action:"reset"}))}resetLoader(){this.fetchAtBuffer_=!1;this.mediaSequenceSync_&&this.mediaSequenceSync_.resetAppendedStatus();this.resyncLoader()}resyncLoader(){this.transmuxer_&&gh.reset(this.transmuxer_);this.syncPoint_=this.partIndex=this.mediaIndex=null;this.isPendingTimestampOffset_=
!1;const a=this.currentMediaInfo_&&this.currentMediaInfo_.isFmp4;"hls"!==this.sourceType_||a||(this.shouldForceTimestampOffsetAfterResync_=!0);this.callQueue_=[];this.loadQueue_=[];this.metadataQueue_.id3=[];this.metadataQueue_.caption=[];this.abort();this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}remove(a,b,c=()=>{},e=!1){Infinity===b&&(b=this.duration_());if(b<=a)this.logger_("skipping remove because end ${end} is \x3c\x3d start ${start}");else if(this.sourceUpdater_&&
this.getMediaInfo_()){var g=1,l=()=>{g--;0===g&&c()};if(e||!this.audioDisabled_)g++,this.sourceUpdater_.removeAudio(a,b,l);if(e||"main"===this.loaderType_)this.gopBuffer_=Sq(this.gopBuffer_,a,b,this.timeMapping_),g++,this.sourceUpdater_.removeVideo(a,b,l);for(const p in this.inbandTextTracks_)Fd(a,b,this.inbandTextTracks_[p]);Fd(a,b,this.segmentMetadataTrack_);l()}else this.logger_("skipping remove because no source updater or starting media info")}monitorBuffer_(){this.checkBufferTimeout_&&D.clearTimeout(this.checkBufferTimeout_);
this.checkBufferTimeout_=D.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){"READY"===this.state&&this.fillBuffer_();this.checkBufferTimeout_&&D.clearTimeout(this.checkBufferTimeout_);this.checkBufferTimeout_=D.setTimeout(this.monitorBufferTick_.bind(this),500)}fillBuffer_(){if(!this.sourceUpdater_.updating()){var a=this.chooseNextRequest_();a&&("number"===typeof a.timestampOffset&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,
from:this.currentTimeline_,to:a.timeline})),this.loadSegment_(a))}}isEndOfStream_(a=this.mediaIndex,b=this.playlist_,c=this.partIndex){if(!b||!this.mediaSource_)return!1;const e="number"===typeof a&&b.segments[a];a=a+1===b.segments.length;c=!e||!e.parts||c+1===e.parts.length;return b.endList&&"open"===this.mediaSource_.readyState&&a&&c}chooseNextRequest_(){var a=this.buffered_(),b=Eg(a)||0,c=Fg(a,this.currentTime_()),e=!this.hasPlayed_()&&1<=c,g=c>=this.goalBufferLength_();a=this.playlist_.segments;
if(!a.length||e||g)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);e={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:!this.syncPoint_};if(e.isSyncRequest){a:{g=this.currentTimeline_;var l=a||[];var p=[];let t=0;for(let x=0;xb)){b=x;break a}}b=0===p.length?0:p[p.length-
1]}e.mediaIndex=b;this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${e.mediaIndex}`)}else if(null!==this.mediaIndex)g=a[this.mediaIndex],l="number"===typeof this.partIndex?this.partIndex:-1,e.startOfSegment=g.end?g.end:b,g.parts&&g.parts[l+1]?(e.mediaIndex=this.mediaIndex,e.partIndex=l+1):e.mediaIndex=this.mediaIndex+1;else{g=this.fetchAtBuffer_?b:this.currentTime_();this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch:\nFor TargetTime: ${g}.\nCurrentTime: ${this.currentTime_()}\nBufferedEnd: ${b}\nFetch At Buffer: ${this.fetchAtBuffer_}\n`,
this.mediaSequenceSync_.diagnostics);if(this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){p=this.getSyncInfoFromMediaSequenceSync_(g);if(!p)return this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null;this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${p.start} --\x3e ${p.end})`);b=p.segmentIndex;l=p.partIndex;p=p.start}else this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint."),p=Ya.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,
playlist:this.playlist_,currentTime:g,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time}),b=p.segmentIndex,l=p.partIndex,p=p.startTime;e.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${g}`:`currentTime ${g}`;e.mediaIndex=b;e.startOfSegment=p;e.partIndex=l;this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${e.mediaIndex} `)}g=(b=a[e.mediaIndex])&&"number"===typeof e.partIndex&&
b.parts&&b.parts[e.partIndex];if(!b||"number"===typeof e.partIndex&&!g)return null;"number"!==typeof e.partIndex&&b.parts&&(e.partIndex=0,g=b.parts[0]);l=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;c||!g||l||g.independent||(0===e.partIndex?(c=a[e.mediaIndex-1],(b=c.parts&&c.parts.length&&c.parts[c.parts.length-1])&&b.independent&&(--e.mediaIndex,e.partIndex=c.parts.length-1,e.independent="previous segment")):b.parts[e.partIndex-
1].independent&&(--e.partIndex,e.independent="previous part"));c=this.mediaSource_&&"ended"===this.mediaSource_.readyState;if(e.mediaIndex>=a.length-1&&c&&!this.seeking_())return null;this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,e.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync"));return this.generateSegmentInfo_(e)}getSyncInfoFromMediaSequenceSync_(a){if(!this.mediaSequenceSync_)return null;const b=
Math.max(a,this.mediaSequenceSync_.start);a!==b&&this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${a} to ${b}`);a=this.mediaSequenceSync_.getSyncInfoForTime(b);if(!a)return null;if(!a.isAppended)return a;a=this.mediaSequenceSync_.getSyncInfoForTime(a.end);if(!a)return null;a.isAppended&&this.logger_("getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!");return a}generateSegmentInfo_(a){const {independent:b,
playlist:c,mediaIndex:e,startOfSegment:g,isSyncRequest:l,partIndex:p,forceTimestampOffset:t,getMediaInfoForTime:x}=a;var y=c.segments[e];a="number"===typeof p&&y.parts[p];a={requestId:"segment-loader-"+Math.random(),uri:a&&a.resolvedUri||y.resolvedUri,mediaIndex:e,partIndex:a?p:null,isSyncRequest:l,startOfSegment:g,playlist:c,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:y.timeline,duration:a&&a.duration||y.duration,segment:y,part:a,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:x,
independent:b};var A="undefined"!==typeof t?t:this.isPendingTimestampOffset_;a.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:y.timeline,currentTimeline:this.currentTimeline_,startOfSegment:g,buffered:this.buffered_(),overrideCheck:A});y=Eg(this.sourceUpdater_.audioBuffered());"number"===typeof y&&(a.audioAppendStart=y-this.sourceUpdater_.audioTimestampOffset());if(this.sourceUpdater_.videoBuffered().length){y=this.gopBuffer_;A=this.currentTime_()-this.sourceUpdater_.videoTimestampOffset();
if("undefined"!==typeof A&&null!==A&&y.length){A=Math.ceil(9E4*(A-this.timeMapping_+3));var z;for(z=0;zA);z++);y=y.slice(z)}else y=[];a.gopsToAlignWith=y}return a}timestampOffsetForSegment_(a){return Uq(a)}earlyAbortWhenNeeded_(a){if(!this.vhs_.tech_.paused()&&this.xhrOptions_.timeout&&this.playlist_.attributes.BANDWIDTH&&!(1E3>Date.now()-(a.firstBytesReceivedAt||Date.now()))){var b=this.currentTime_(),c=a.bandwidth,e=this.pendingSegment_.duration,g=Ya.estimateSegmentRequestTime(e,
c,this.playlist_,a.bytesReceived);a=np(this.buffered_(),b,this.vhs_.tech_.playbackRate())-1;g<=a||!(b=Jq({main:this.vhs_.playlists.main,currentTime:b,bandwidth:c,duration:this.duration_(),segmentDuration:e,timeUntilRebuffer:a,currentTimeline:this.currentTimeline_,syncController:this.syncController_}))||(c=g-a-b.rebufferingImpact,e=.5,a<=Db&&(e=1),!b.playlist||b.playlist.uri===this.playlist_.uri||c{e[g.stream]=e[g.stream]||{startTime:Infinity,captions:[],endTime:0};const l=e[g.stream];l.startTime=Math.min(l.startTime,g.startTime+c);l.endTime=Math.max(l.endTime,g.endTime+c);l.captions.push(g)});Object.keys(e).forEach(g=>{const {startTime:l,endTime:p,captions:t}=e[g],x=this.inbandTextTracks_;
this.logger_(`adding cues from ${l} -> ${p} for ${g}`);var y=this.vhs_.tech_;if(!x[g]){y.trigger({type:"usage",name:"vhs-608"});let z=g;/^cc708_/.test(g)&&(z="SERVICE"+g.split("_")[1]);var A=y.textTracks().getTrackById(z);if(A)x[g]=A;else{let E=A=g,I=!1;const G=(y.options_.vhs&&y.options_.vhs.captionServices||{})[z];G&&(A=G.label,E=G.language,I=G.default);x[g]=y.addRemoteTextTrack({kind:"captions",id:z,default:I,label:A,language:E},!1).track}}Fd(l,p,x[g]);Lq({captionArray:t,inbandTextTracks:x,timestampOffset:c})});
this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}else this.metadataQueue_.caption.push(this.handleCaptions_.bind(this,a,b))}handleId3_(a,b,c){this.earlyAbortWhenNeeded_(a.stats);this.checkForAbort_(a.requestId)||(this.pendingSegment_.hasAppendedData_?this.addMetadataToTextTrack(c,b,this.duration_()):this.metadataQueue_.id3.push(this.handleId3_.bind(this,a,b,c)))}processMetadataQueue_(){this.metadataQueue_.id3.forEach(a=>a());this.metadataQueue_.caption.forEach(a=>
a());this.metadataQueue_.id3=[];this.metadataQueue_.caption=[]}processCallQueue_(){const a=this.callQueue_;this.callQueue_=[];a.forEach(b=>b())}processLoadQueue_(){const a=this.loadQueue_;this.loadQueue_=[];a.forEach(b=>b())}hasEnoughInfoToLoad_(){if("audio"!==this.loaderType_)return!0;const a=this.pendingSegment_;return a?this.getCurrentMediaInfo_()?Pl({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:a.timeline,loaderType:this.loaderType_,
audioDisabled:this.audioDisabled_})?!1:!0:!0:!1}getCurrentMediaInfo_(a=this.pendingSegment_){return a&&a.trackInfo||this.currentMediaInfo_}getMediaInfo_(a=this.pendingSegment_){return this.getCurrentMediaInfo_(a)||this.startingMediaInfo_}getPendingSegmentPlaylist(){return this.pendingSegment_?this.pendingSegment_.playlist:null}hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready()||this.waitingOnRemove_||this.quotaExceededErrorRetryTimeout_)return!1;const a=this.pendingSegment_,b=this.getCurrentMediaInfo_();
if(!a||!b)return!1;const {hasAudio:c,hasVideo:e,isMuxed:g}=b;return e&&!a.videoTimingInfo||c&&!this.audioDisabled_&&!g&&!a.audioTimingInfo||Pl({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:a.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_})?!1:!0}handleData_(a,b){this.earlyAbortWhenNeeded_(a.stats);if(!this.checkForAbort_(a.requestId))if(this.callQueue_.length||!this.hasEnoughInfoToAppend_())this.callQueue_.push(this.handleData_.bind(this,
a,b));else{var c=this.pendingSegment_;this.setTimeMapping_(c.timeline);this.updateMediaSecondsLoaded_(c.part||c.segment);if("closed"!==this.mediaSource_.readyState){a.map&&(a.map=this.initSegmentForMap(a.map,!0),c.segment.map=a.map);a.key&&this.segmentKey(a.key,!0);c.isFmp4=a.isFmp4;c.timingInfo=c.timingInfo||{};if(c.isFmp4)this.trigger("fmp4"),c.timingInfo.start=c[`${b.type}TimingInfo`].start;else{a=this.getCurrentMediaInfo_();a="main"===this.loaderType_&&a&&a.hasVideo;if(a)var e=c.videoTimingInfo.start;
c.timingInfo.start=this.trueSegmentStart_({currentStart:c.timingInfo.start,playlist:c.playlist,mediaIndex:c.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:a,firstVideoFrameTimeForData:e,videoTimingInfo:c.videoTimingInfo,audioTimingInfo:c.audioTimingInfo})}this.updateAppendInitSegmentStatus(c,b.type);this.updateSourceBufferTimestampOffset_(c);if(c.isSyncRequest){this.updateTimingInfoEnd_(c);this.syncController_.saveSegmentTimingInfo({segmentInfo:c,
shouldSaveTimelineMapping:"main"===this.loaderType_});e=this.chooseNextRequest_();if(e.mediaIndex!==c.mediaIndex||e.partIndex!==c.partIndex){this.logger_("sync segment was incorrect, not appending");return}this.logger_("sync segment was correct, appending")}c.hasAppendedData_=!0;this.processMetadataQueue_();this.appendData_(c,b)}}}updateAppendInitSegmentStatus(a,b){"main"!==this.loaderType_||"number"!==typeof a.timestampOffset||a.changedTimestampOffset||(this.appendInitSegment_={audio:!0,video:!0});
this.playlistOfLastInitSegment_[b]!==a.playlist&&(this.appendInitSegment_[b]=!0)}getInitSegmentAndUpdateState_({type:a,initSegment:b,map:c,playlist:e}){if(c){const g=Be(c);if(this.activeInitSegmentId_===g)return null;b=this.initSegmentForMap(c,!0).bytes;this.activeInitSegmentId_=g}return b&&this.appendInitSegment_[a]?(this.playlistOfLastInitSegment_[a]=e,this.appendInitSegment_[a]=!1,this.activeInitSegmentId_=null,b):null}handleQuotaExceededError_({segmentInfo:a,type:b,bytes:c},e){e=this.sourceUpdater_.audioBuffered();
const g=this.sourceUpdater_.videoBuffered();1=p-l&&1>=x-t?(this.logger_("On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. "+`Appended byte length: ${c.byteLength}, `+
`audio buffer: ${lc(e).join(", ")}, `+`video buffer: ${lc(g).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:Infinity,metadata:{errorType:H.Error.SegmentExceedsSourceBufferQuota}}),this.trigger("error")):(this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:a,type:b,bytes:c})),a=this.currentTime_()-1,this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${a}`),this.remove(0,
a,()=>{this.logger_("On QUOTA_EXCEEDED_ERR, retrying append in 1s");this.waitingOnRemove_=!1;this.quotaExceededErrorRetryTimeout_=D.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue");this.quotaExceededErrorRetryTimeout_=null;this.processCallQueue_()},1E3)},!0))}handleAppendError_({segmentInfo:a,type:b,bytes:c},e){e&&(22===e.code?this.handleQuotaExceededError_({segmentInfo:a,type:b,bytes:c}):(this.logger_("Received non QUOTA_EXCEEDED_ERR on append",e),this.error({message:`${b} append of ${c.length}b failed for segment `+
`#${a.mediaIndex} in playlist ${a.playlist.id}`,metadata:{errorType:H.Error.SegmentAppendError}}),this.trigger("appenderror")))}appendToSourceBuffer_({segmentInfo:a,type:b,initSegment:c,data:e,bytes:g}){g||(g=[e],e=e.byteLength,c&&(g.unshift(c),e+=c.byteLength),g=Kq({bytes:e,segments:g}));this.sourceUpdater_.appendBuffer({segmentInfo:a,type:b,bytes:g},this.handleAppendError_.bind(this,{segmentInfo:a,type:b,bytes:g}))}handleSegmentTimingInfo_(a,b,c){this.pendingSegment_&&b===this.pendingSegment_.requestId&&
(b=this.pendingSegment_.segment,a=`${a}TimingInfo`,b[a]||(b[a]={}),b[a].transmuxerPrependedSeconds=c.prependedContentDuration||0,b[a].transmuxedPresentationStart=c.start.presentation,b[a].transmuxedDecodeStart=c.start.decode,b[a].transmuxedPresentationEnd=c.end.presentation,b[a].transmuxedDecodeEnd=c.end.decode,b[a].baseMediaDecodeTime=c.baseMediaDecodeTime)}appendData_(a,b){const {type:c,data:e}=b;!e||!e.byteLength||"audio"===c&&this.audioDisabled_||(b=this.getInitSegmentAndUpdateState_({type:c,
initSegment:b.initSegment,playlist:a.playlist,map:a.isFmp4?a.segment.map:null}),this.appendToSourceBuffer_({segmentInfo:a,type:c,initSegment:b,data:e}))}loadSegment_(a){this.state="WAITING";this.pendingSegment_=a;this.trimBackBuffer_(a);"number"===typeof a.timestampOffset&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"});this.hasEnoughInfoToLoad_()?this.updateTransmuxerAndRequestSegment_(a):this.loadQueue_.push(()=>{const b=nb({},a,{forceTimestampOffset:!0});nb(a,this.generateSegmentInfo_(b));
this.isPendingTimestampOffset_=!1;this.updateTransmuxerAndRequestSegment_(a)})}updateTransmuxerAndRequestSegment_(a){this.shouldUpdateTransmuxerTimestampOffset_(a.timestampOffset)&&(this.gopBuffer_.length=0,a.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:a.timestampOffset}));const b=this.createSimplifiedSegmentObj_(a);var c=this.isEndOfStream_(a.mediaIndex,a.playlist,a.partIndex);const e=
null!==this.mediaIndex,g=a.timeline!==this.currentTimeline_&&0{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:l,level:p,stream:t})=>{this.logger_(`${Uc(a)} logged from transmuxer stream ${t} as a ${p}: ${l}`)}})}trimBackBuffer_(a){a=
this.seekable_();var b=this.currentTime_(),c=this.playlist_.targetDuration||10;let e=b-Ha.BACK_BUFFER_LENGTH;a.length&&(e=Math.max(e,a.start(0)));a=Math.min(b-c,e);0=
e);g++);b=b.slice(0,g).concat(c)}this.gopBuffer_=b}this.state="APPENDING";this.trigger("appending");this.waitForAppendsToComplete_(a)}}setTimeMapping_(a){a=this.syncController_.mappingForTimeline(a);null!==a&&(this.timeMapping_=a)}updateMediaSecondsLoaded_(a){this.mediaSecondsLoaded="number"===typeof a.start&&"number"===typeof a.end?this.mediaSecondsLoaded+(a.end-a.start):this.mediaSecondsLoaded+a.duration}shouldUpdateTransmuxerTimestampOffset_(a){return null===a?!1:"main"===this.loaderType_&&a!==
this.sourceUpdater_.videoTimestampOffset()||!this.audioDisabled_&&a!==this.sourceUpdater_.audioTimestampOffset()?!0:!1}trueSegmentStart_({currentStart:a,playlist:b,mediaIndex:c,firstVideoFrameTimeForData:e,currentVideoTimestampOffset:g,useVideoTimingInfo:l,videoTimingInfo:p,audioTimingInfo:t}){if("undefined"!==typeof a)return a;if(!l)return t.start;a=b.segments[c-1];return 0!==c&&a&&"undefined"!==typeof a.start&&a.end===e+g?p.start:e}waitForAppendsToComplete_(a){var b=this.getCurrentMediaInfo_(a);
if(b){var {hasAudio:c,hasVideo:e,isMuxed:g}=b;b="main"===this.loaderType_&&e;var l=!this.audioDisabled_&&c&&!g;a.waitingOnAppends=0;a.hasAppendedData_?(b&&a.waitingOnAppends++,l&&a.waitingOnAppends++,b&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,a)),l&&this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this,a))):(a.timingInfo||"number"!==typeof a.timestampOffset||(this.isPendingTimestampOffset_=!0),a.timingInfo={start:0},a.waitingOnAppends++,this.isPendingTimestampOffset_||
(this.updateSourceBufferTimestampOffset_(a),this.processMetadataQueue_()),this.checkAppendsDone_(a))}else this.error({message:"No starting media returned, likely due to an unsupported media format.",playlistExclusionDuration:Infinity,metadata:{errorType:H.Error.SegmentUnsupportedMediaFormat}}),this.trigger("error")}checkAppendsDone_(a){this.checkForAbort_(a.requestId)||(a.waitingOnAppends--,0===a.waitingOnAppends&&this.handleAppendsDone_())}checkForIllegalMediaSwitch(a){var b=this.getCurrentMediaInfo_();
return(a="main"===this.loaderType_&&b&&a?a.hasAudio||a.hasVideo?b.hasVideo&&!a.hasVideo?"Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.":!b.hasVideo&&a.hasVideo?"Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.":null:"Neither audio nor video found in segment.":
null)?(this.error({message:a,playlistExclusionDuration:Infinity,metadata:{errorType:H.Error.SegmentSwitchError}}),this.trigger("error"),!0):!1}updateSourceBufferTimestampOffset_(a){if(null!==a.timestampOffset&&"number"===typeof a.timingInfo.start&&!a.changedTimestampOffset&&"main"===this.loaderType_){var b=!1;a.timestampOffset-=this.getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:a.segment.videoTimingInfo,audioTimingInfo:a.segment.audioTimingInfo,timingInfo:a.timingInfo});a.changedTimestampOffset=
!0;a.timestampOffset!==this.sourceUpdater_.videoTimestampOffset()&&(this.sourceUpdater_.videoTimestampOffset(a.timestampOffset),b=!0);a.timestampOffset!==this.sourceUpdater_.audioTimestampOffset()&&(this.sourceUpdater_.audioTimestampOffset(a.timestampOffset),b=!0);b&&this.trigger("timestampoffset")}}getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:a,audioTimingInfo:b,timingInfo:c}){return this.useDtsForTimestampOffset_?a&&"number"===typeof a.transmuxedDecodeStart?a.transmuxedDecodeStart:
b&&"number"===typeof b.transmuxedDecodeStart?b.transmuxedDecodeStart:c.start:c.start}updateTimingInfoEnd_(a){a.timingInfo=a.timingInfo||{};var b=this.getMediaInfo_();if(b="main"===this.loaderType_&&b&&b.hasVideo&&a.videoTimingInfo?a.videoTimingInfo:a.audioTimingInfo)a.timingInfo.end="number"===typeof b.end?b.end:b.start+a.duration}handleAppendsDone_(){this.pendingSegment_&&this.trigger("appendsdone");if(this.pendingSegment_){var a=this.pendingSegment_;a.part&&a.part.syncInfo?a.part.syncInfo.markAppended():
a.segment.syncInfo&&a.segment.syncInfo.markAppended();this.updateTimingInfoEnd_(a);this.shouldSaveSegmentTimingInfo_&&this.syncController_.saveSegmentTimingInfo({segmentInfo:a,shouldSaveTimelineMapping:"main"===this.loaderType_});if("hls"!==this.sourceType_)var b=null;else{var c=Vq({audioTimingInfo:a.audioTimingInfo,videoTimingInfo:a.videoTimingInfo});if(c){var e=a.playlist.targetDuration;b=Ql({segmentDuration:c,maxDuration:2*e});var g=Ql({segmentDuration:c,maxDuration:e});c=`Segment with index ${a.mediaIndex} `+
`from playlist ${a.playlist.id} `+`has a duration of ${c} `+`when the reported duration is ${a.duration} `+`and the target duration is ${e}. `+"For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1";b=b||g?{severity:b?"warn":"info",message:c}:null}else b=null}b&&("warn"===b.severity?H.log.warn(b.message):this.logger_(b.message));
this.recordThroughput_(a);this.pendingSegment_=null;this.state="READY";if(a.isSyncRequest&&(this.trigger("syncinfoupdate"),!a.hasAppendedData_)){this.logger_(`Throwing away un-appended sync request ${Uc(a)}`);return}this.logger_(`Appended ${Uc(a)}`);this.addSegmentMetadataCue_(a);this.fetchAtBuffer_=!0;this.currentTimeline_!==a.timeline&&(this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:a.timeline}),"main"!==this.loaderType_||this.audioDisabled_||
this.timelineChangeController_.lastTimelineChange({type:"audio",from:this.currentTimeline_,to:a.timeline}));this.currentTimeline_=a.timeline;this.trigger("syncinfoupdate");g=a.segment;b=a.part;g=g.end&&this.currentTime_()-g.end>3*a.playlist.targetDuration;b=b&&b.end&&this.currentTime_()-b.end>3*a.playlist.partTargetDuration;g||b?(this.logger_(`bad ${g?"segment":"part"} ${Uc(a)}`),this.resetEverything()):(null!==this.mediaIndex&&this.trigger("bandwidthupdate"),this.trigger("progress"),this.mediaIndex=
a.mediaIndex,this.partIndex=a.partIndex,this.isEndOfStream_(a.mediaIndex,a.playlist,a.partIndex)&&this.endOfStream(),this.trigger("appended"),a.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitorBuffer_())}else this.state="READY",this.paused()||this.monitorBuffer_()}recordThroughput_(a){if(a.durationb.toUpperCase())},Wq=["video","audio"],lh=(a,b)=>{const c=b[`${a}Buffer`];return c&&c.updating||b.queuePending[a]},Vc=(a,b)=>{if(0!==b.queue.length){var c=0,e=b.queue[c];if("mediaSource"===e.type)b.updating()||"closed"===b.mediaSource.readyState||
(b.queue.shift(),e.action(b),e.doneFn&&e.doneFn(),Vc("audio",b),Vc("video",b));else if("mediaSource"!==a&&b.ready()&&"closed"!==b.mediaSource.readyState&&!lh(a,b)){if(e.type!==a){a:{c=b.queue;for(e=0;e{const c=b[`${a}Buffer`],e=Rl(a);c&&(c.removeEventListener("updateend",
b[`on${e}UpdateEnd_`]),c.removeEventListener("error",b[`on${e}Error_`]),b.codecs[a]=null,b[`${a}Buffer`]=null)},Hb=(a,b)=>a&&b&&-1!==Array.prototype.indexOf.call(a.sourceBuffers,b),hb={appendBuffer:(a,b,c)=>(e,g)=>{const l=g[`${e}Buffer`];if(Hb(g.mediaSource,l)){g.logger_(`Appending segment ${b.mediaIndex}'s ${a.length} bytes to ${e}Buffer`);try{l.appendBuffer(a)}catch(p){g.logger_(`Error with code ${p.code} `+(22===p.code?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${b.mediaIndex} to ${e}Buffer`),
g.queuePending[e]=null,c(p)}}},remove:(a,b)=>(c,e)=>{const g=e[`${c}Buffer`];if(Hb(e.mediaSource,g)){e.logger_(`Removing ${a} to ${b} from ${c}Buffer`);try{g.remove(a,b)}catch(l){e.logger_(`Remove ${a} to ${b} from ${c}Buffer failed`)}}},timestampOffset:a=>(b,c)=>{const e=c[`${b}Buffer`];Hb(c.mediaSource,e)&&(c.logger_(`Setting ${b}timestampOffset to ${a}`),e.timestampOffset=a)},callback:a=>(b,c)=>{a()},endOfStream:a=>b=>{if("open"===b.mediaSource.readyState){b.logger_(`Calling mediaSource endOfStream(${a||
""})`);try{b.mediaSource.endOfStream(a)}catch(c){H.log.warn("Failed to call media source endOfStream",c)}}},duration:a=>b=>{b.logger_(`Setting mediaSource duration to ${a}`);try{b.mediaSource.duration=a}catch(c){H.log.warn("Failed to set media source duration",c)}},abort:()=>(a,b)=>{if("open"===b.mediaSource.readyState){var c=b[`${a}Buffer`];if(Hb(b.mediaSource,c)){b.logger_(`calling abort on ${a}Buffer`);try{c.abort()}catch(e){H.log.warn(`Failed to abort on ${a}Buffer`,e)}}}},addSourceBuffer:(a,
b)=>c=>{const e=Rl(a);var g=id(b);c.logger_(`Adding ${a}Buffer with codec ${b} to mediaSource`);g=c.mediaSource.addSourceBuffer(g);g.addEventListener("updateend",c[`on${e}UpdateEnd_`]);g.addEventListener("error",c[`on${e}Error_`]);c.codecs[a]=b;c[`${a}Buffer`]=g},removeSourceBuffer:a=>b=>{const c=b[`${a}Buffer`];Sl(a,b);if(Hb(b.mediaSource,c)){b.logger_(`Removing ${a}Buffer with codec ${b.codecs[a]} from mediaSource`);try{b.mediaSource.removeSourceBuffer(c)}catch(e){H.log.warn(`Failed to removeSourceBuffer ${a}Buffer`,
e)}}},changeType:a=>(b,c)=>{const e=c[`${b}Buffer`],g=id(a);if(Hb(c.mediaSource,e)){var l=a.substring(0,a.indexOf(".")),p=c.codecs[b];if(p.substring(0,p.indexOf("."))!==l){c.logger_(`changing ${b}Buffer codec from ${c.codecs[b]} to ${a}`);try{e.changeType(g),c.codecs[b]=a}catch(t){H.log.warn(`Failed to changeType on ${b}Buffer`,t)}}}}},ib=({type:a,sourceUpdater:b,action:c,doneFn:e,name:g})=>{b.queue.push({type:a,action:c,doneFn:e,name:g});Vc(a,b)},Tl=(a,b)=>c=>{c=b[`${a}Buffered`]();if(0===c.length)c=
"Buffered Ranges are empty";else{var e="Buffered Ranges: \n";for(let g=0;gVc("mediaSource",this);this.mediaSource.addEventListener("sourceopen",
this.sourceopenListener_);this.logger_=mb("SourceUpdater");this.videoTimestampOffset_=this.audioTimestampOffset_=0;this.queue=[];this.queuePending={audio:null,video:null};this.delayedAudioAppendQueue_=[];this.videoAppendQueued_=!1;this.codecs={};this.onVideoUpdateEnd_=Tl("video",this);this.onAudioUpdateEnd_=Tl("audio",this);this.onVideoError_=b=>{this.videoError_=b};this.onAudioError_=b=>{this.audioError_=b};this.triggeredReady_=this.initializedEme_=this.createdSourceBuffers_=!1}initializedEme(){this.initializedEme_=
!0;this.triggerReady()}hasCreatedSourceBuffers(){return this.createdSourceBuffers_}hasInitializedAnyEme(){return this.initializedEme_}ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme()}createSourceBuffers(a){this.hasCreatedSourceBuffers()||(this.addOrChangeSourceBuffers(a),this.createdSourceBuffers_=!0,this.trigger("createdsourcebuffers"),this.triggerReady())}triggerReady(){this.ready()&&!this.triggeredReady_&&(this.triggeredReady_=!0,this.trigger("ready"))}addSourceBuffer(a,
b){ib({type:"mediaSource",sourceUpdater:this,action:hb.addSourceBuffer(a,b),name:"addSourceBuffer"})}abort(a){ib({type:a,sourceUpdater:this,action:hb.abort(a),name:"abort"})}removeSourceBuffer(a){this.canRemoveSourceBuffer()?ib({type:"mediaSource",sourceUpdater:this,action:hb.removeSourceBuffer(a),name:"removeSourceBuffer"}):H.log.error("removeSourceBuffer is not supported!")}canRemoveSourceBuffer(){return!H.browser.IS_FIREFOX&&D.MediaSource&&D.MediaSource.prototype&&"function"===typeof D.MediaSource.prototype.removeSourceBuffer}static canChangeType(){return D.SourceBuffer&&
D.SourceBuffer.prototype&&"function"===typeof D.SourceBuffer.prototype.changeType}canChangeType(){return this.constructor.canChangeType()}changeType(a,b){this.canChangeType()?ib({type:a,sourceUpdater:this,action:hb.changeType(b),name:"changeType"}):H.log.error("changeType is not supported!")}addOrChangeSourceBuffers(a){if(!a||"object"!==typeof a||0===Object.keys(a).length)throw Error("Cannot addOrChangeSourceBuffers to undefined codecs");Object.keys(a).forEach(b=>{const c=a[b];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(b,
c);this.canChangeType()&&this.changeType(b,c)})}appendBuffer(a,b){const {segmentInfo:c,type:e,bytes:g}=a;this.processedAppend_=!0;"audio"===e&&this.videoBuffer&&!this.videoAppendQueued_?(this.delayedAudioAppendQueue_.push([a,b]),this.logger_(`delayed audio append of ${g.length} until video append`)):(ib({type:e,sourceUpdater:this,action:hb.appendBuffer(g,c||{mediaIndex:-1},b),doneFn:b,name:"appendBuffer"}),"video"===e&&(this.videoAppendQueued_=!0,this.delayedAudioAppendQueue_.length&&(a=this.delayedAudioAppendQueue_.slice(),
this.logger_(`queuing delayed audio ${a.length} appendBuffers`),this.delayedAudioAppendQueue_.length=0,a.forEach(l=>{this.appendBuffer.apply(this,l)}))))}audioBuffered(){return Hb(this.mediaSource,this.audioBuffer)?this.audioBuffer.buffered?this.audioBuffer.buffered:Na():Na()}videoBuffered(){return Hb(this.mediaSource,this.videoBuffer)?this.videoBuffer.buffered?this.videoBuffer.buffered:Na():Na()}buffered(){const a=Hb(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,b=Hb(this.mediaSource,
this.audioBuffer)?this.audioBuffer:null;return b&&!a?this.audioBuffered():a&&!b?this.videoBuffered():mp(this.audioBuffered(),this.videoBuffered())}setDuration(a,b=Lb){ib({type:"mediaSource",sourceUpdater:this,action:hb.duration(a),name:"duration",doneFn:b})}endOfStream(a=null,b=Lb){"string"!==typeof a&&(a=void 0);ib({type:"mediaSource",sourceUpdater:this,action:hb.endOfStream(a),name:"endOfStream",doneFn:b})}removeAudio(a,b,c=Lb){this.audioBuffered().length&&0!==this.audioBuffered().end(0)?ib({type:"audio",
sourceUpdater:this,action:hb.remove(a,b),doneFn:c,name:"remove"}):c()}removeVideo(a,b,c=Lb){this.videoBuffered().length&&0!==this.videoBuffered().end(0)?ib({type:"video",sourceUpdater:this,action:hb.remove(a,b),doneFn:c,name:"remove"}):c()}updating(){return lh("audio",this)||lh("video",this)?!0:!1}audioTimestampOffset(a){"undefined"!==typeof a&&this.audioBuffer&&this.audioTimestampOffset_!==a&&(ib({type:"audio",sourceUpdater:this,action:hb.timestampOffset(a),name:"timestampOffset"}),this.audioTimestampOffset_=
a);return this.audioTimestampOffset_}videoTimestampOffset(a){"undefined"!==typeof a&&this.videoBuffer&&this.videoTimestampOffset!==a&&(ib({type:"video",sourceUpdater:this,action:hb.timestampOffset(a),name:"timestampOffset"}),this.videoTimestampOffset_=a);return this.videoTimestampOffset_}audioQueueCallback(a){this.audioBuffer&&ib({type:"audio",sourceUpdater:this,action:hb.callback(a),name:"callback"})}videoQueueCallback(a){this.videoBuffer&&ib({type:"video",sourceUpdater:this,action:hb.callback(a),
name:"callback"})}dispose(){this.trigger("dispose");Wq.forEach(a=>{this.abort(a);if(this.canRemoveSourceBuffer())this.removeSourceBuffer(a);else this[`${a}QueueCallback`](()=>Sl(a,this))});this.videoAppendQueued_=!1;this.delayedAudioAppendQueue_.length=0;this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_);this.off()}}const Xq=a=>{a=new Uint8Array(a);return Array.from(a).map(b=>b.toString(16).padStart(2,"0")).join("")},Vl=new Uint8Array(["\n","\n"].map(a=>
a.charCodeAt(0)));class Yq extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class Zq extends kh{constructor(a,b={}){super(a,b);this.subtitlesTrack_=this.mediaSource_=null;this.featuresNativeTextTracks_=a.featuresNativeTextTracks;this.loadVttJs=a.loadVttJs;this.shouldSaveSegmentTimingInfo_=!1}createTransmuxer_(){return null}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return Na();
const a=this.subtitlesTrack_.cues;return Na([[a[0].startTime,a[a.length-1].startTime]])}initSegmentForMap(a,b=!1){if(!a)return null;const c=Be(a);let e=this.initSegments_[c];b&&!e&&a.bytes&&(b=new Uint8Array(Vl.byteLength+a.bytes.byteLength),b.set(a.bytes),b.set(Vl,a.bytes.byteLength),this.initSegments_[c]=e={resolvedUri:a.resolvedUri,byterange:a.byterange,bytes:b});return e||a}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){this.state="READY";this.resetEverything();
return this.monitorBuffer_()}track(a){if("undefined"===typeof a)return this.subtitlesTrack_;this.subtitlesTrack_=a;"INIT"===this.state&&this.couldBeginLoading_()&&this.init_();return this.subtitlesTrack_}remove(a,b){Fd(a,b,this.subtitlesTrack_)}fillBuffer_(){const a=this.chooseNextRequest_();a&&(null===this.syncController_.timestampOffsetForTimeline(a.timeline)?(this.syncController_.one("timestampoffset",()=>{this.state="READY";this.paused()||this.monitorBuffer_()}),this.state="WAITING_ON_TIMELINE"):
this.loadSegment_(a))}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(a){for(;a&&a.segment.empty;){if(a.mediaIndex+1>=a.playlist.segments.length){a=null;break}a=this.generateSegmentInfo_({playlist:a.playlist,mediaIndex:a.mediaIndex+1,startOfSegment:a.startOfSegment+a.duration,isSyncRequest:a.isSyncRequest})}return a}stopForError(a){this.error(a);this.state="READY";this.pause();this.trigger("error")}segmentRequestFinished_(a,
b,c){if(this.subtitlesTrack_)if(this.saveTransferStats_(b.stats),this.pendingSegment_)if(a)-101===a.code&&this.handleTimeout_(),-102===a.code?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,this.stopForError(a);else{var e=this.pendingSegment_;this.saveBandwidthRelatedStats_(e.duration,b.stats);b.key&&this.segmentKey(b.key,!0);this.state="APPENDING";this.trigger("appending");var g=e.segment;g.map&&(g.map.bytes=b.map.bytes);e.bytes=b.bytes;if("function"!==typeof D.WebVTT&&"function"===typeof this.loadVttJs)this.state=
"WAITING_ON_VTTJS",this.loadVttJs().then(()=>this.segmentRequestFinished_(a,b,c),()=>this.stopForError({message:"Error loading vtt.js",metadata:{errorType:H.Error.VttLoadError}}));else{g.requested=!0;try{this.parseVTTCues_(e)}catch(l){this.stopForError({message:l.message,metadata:{errorType:H.Error.VttCueParsingError}});return}this.updateTimeMapping_(e,this.syncController_.timelines[e.timeline],this.playlist_);e.timingInfo=e.cues.length?{start:e.cues[0].startTime,end:e.cues[e.cues.length-1].endTime}:
{start:e.startOfSegment,end:e.startOfSegment+e.duration};e.isSyncRequest?(this.trigger("syncinfoupdate"),this.pendingSegment_=null,this.state="READY"):(e.byteLength=e.bytes.byteLength,this.mediaSecondsLoaded+=g.duration,e.cues.forEach(l=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new D.VTTCue(l.startTime,l.endTime,l.text):l)}),Rq(this.subtitlesTrack_),this.handleAppendsDone_())}}else this.state="READY",this.mediaRequestsAborted+=1;else this.state="READY"}handleData_(){}updateTimingInfoEnd_(){}parseVTTCues_(a){let b=
!1;if("function"!==typeof D.WebVTT)throw new Yq;if("function"===typeof D.TextDecoder)var c=new D.TextDecoder("utf8");else c=D.WebVTT.StringDecoder(),b=!0;c=new D.WebVTT.Parser(D,D.vttjs,c);a.cues=[];a.timestampmap={MPEGTS:0,LOCAL:0};c.oncue=a.cues.push.bind(a.cues);c.ontimestampmap=g=>{a.timestampmap=g};c.onparsingerror=g=>{H.log.warn("Error encountered when parsing cues: "+g.message)};if(a.segment.map){var e=a.segment.map.bytes;b&&(e=decodeURIComponent(escape(String.fromCharCode.apply(null,e))));
c.parse(e)}e=a.bytes;b&&(e=decodeURIComponent(escape(String.fromCharCode.apply(null,e))));c.parse(e);c.flush()}updateTimeMapping_(a,b,c){const e=a.segment;if(b)if(a.cues.length){var {MPEGTS:g,LOCAL:l}=a.timestampmap,p=g/9E4-l+b.mapping;a.cues.forEach(t=>{const x=t.endTime-t.startTime,y=0===g?t.startTime+p:this.handleRollover_(t.startTime+p,b.time);t.startTime=Math.max(y,0);t.endTime=Math.max(y+x,0)});c.syncInfo||(c.syncInfo={mediaSequence:c.mediaSequence+a.mediaIndex,time:Math.min(a.cues[0].startTime,
a.cues[a.cues.length-1].startTime-e.duration)})}else e.empty=!0}handleRollover_(a,b){if(null===b)return a;a*=9E4;b*=9E4;let c;for(c=b=x.adStartTime&&e<=x.adEndTime){e=x;break a}}e=null}if(e){if("cueIn"in l){e.endTime=c;e.adEndTime=c;c+=l.duration;
e=null;continue}if(c=this.start&&aa.resetAppendedStatus())}}class mh{constructor(){this.storage_=new Map;this.diagnostics_="";this.isReliable_=!1;this.start_=-Infinity;this.end_=Infinity}get start(){return this.start_}get end(){return this.end_}get diagnostics(){return this.diagnostics_}get isReliable(){return this.isReliable_}resetAppendedStatus(){this.storage_.forEach(a=>a.resetAppendStatus())}update(a,b){const {mediaSequence:c,
segments:e}=a;if(this.isReliable_=this.isReliablePlaylist_(c,e))return this.updateStorage_(e,c,this.calculateBaseTime_(c,b))}getSyncInfoForTime(a){for(const {segmentSyncInfo:b,partsSyncInfo:c}of this.storage_.values())if(c.length)for(const e of c){if(e.isInRange(a))return e}else if(b.isInRange(a))return b;return null}updateStorage_(a,b,c){const e=new Map;let g="\n",l=c,p=b;this.start_=l;a.forEach((t,x)=>{const y=this.storage_.get(p),A=l,z=A+t.duration,E=!!(y&&y.segmentSyncInfo&&y.segmentSyncInfo.isAppended),
I=new Wl({start:A,end:z,appended:E,segmentIndex:x});t.syncInfo=I;let G=l;const O=(t.parts||[]).map((Q,V)=>{const T=G,ca=G+Q.duration,K=!!(y&&y.partsSyncInfo&&y.partsSyncInfo[V]&&y.partsSyncInfo[V].isAppended),ba=new Wl({start:T,end:ca,appended:K,segmentIndex:x,partIndex:V});G=ca;g+=`Media Sequence: ${p}.${V} | Range: ${T} --\x3e ${ca} | Appended: ${K}\n`;return Q.syncInfo=ba});e.set(p,new ar(I,O));g+=`${yi(t.resolvedUri)} | Media Sequence: ${p} | Range: ${A} --\x3e ${z} | Appended: ${E}\n`;p++;l=
z});this.end_=l;this.storage_=e;this.diagnostics_=g}calculateBaseTime_(a,b){return this.storage_.size?this.storage_.has(a)?this.storage_.get(a).segmentSyncInfo.start:b:0}isReliablePlaylist_(a,b){return void 0!==a&&null!==a&&Array.isArray(b)&&b.length}}const nh=[{name:"VOD",run:(a,b,c,e,g)=>Infinity!==c?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(a,b,c,e,g,l)=>{a=a.getMediaSequenceSync(l);return a&&a.isReliable?(g=a.getSyncInfoForTime(g))?{time:g.start,partIndex:g.partIndex,
segmentIndex:g.segmentIndex}:null:null}},{name:"ProgramDateTime",run:(a,b,c,e,g)=>{if(!Object.keys(a.timelineToDatetimeMappings).length)return null;e=c=null;const l=Hg(b);g=g||0;for(let x=0;x{c=a=null;g=g||0;const l=Hg(b);for(let t=0;t=p)c=p,a={time:y,segmentIndex:x.segmentIndex,partIndex:x.partIndex}}}return a}},{name:"Discontinuity",run:(a,b,c,e,g)=>
{c=null;g=g||0;if(b.discontinuityStarts&&b.discontinuityStarts.length){e=null;for(let l=0;l=x)e=x,c={time:t.time,segmentIndex:p,partIndex:null}}}}return c}},{name:"Playlist",run:(a,b,c,e,g)=>b.syncInfo?{time:b.syncInfo.time,segmentIndex:b.syncInfo.mediaSequence-b.mediaSequence,partIndex:null}:null}];class br extends H.EventTarget{constructor(a){super();
this.timelines=[];this.discontinuities=[];this.timelineToDatetimeMappings={};this.mediaSequenceStorage_={main:new mh,audio:new mh,vtt:new mh};this.logger_=mb("SyncController")}getMediaSequenceSync(a){return this.mediaSequenceStorage_[a]||null}getSyncPoint(a,b,c,e,g){if(Infinity!==b)return nh.find(({name:l})=>"VOD"===l).run(this,a,b);b=this.runStrategies_(a,b,c,e,g);if(!b.length)return null;for(const l of b){const {syncPoint:p,strategy:t}=l,{segmentIndex:x,time:y}=p;if(!(0>x)&&(c=y,g=c+a.segments[x].duration,
this.logger_(`Strategy: ${t}. Current time: ${e}. selected segment: ${x}. Time: [${c} -> ${g}]}`),e>=c&&et)e=0>p?c.start-sd({defaultDuration:b.targetDuration,durationList:b.segments,startIndex:a.mediaIndex,endIndex:e}):c.end+sd({defaultDuration:b.targetDuration,durationList:b.segments,startIndex:a.mediaIndex+1,
endIndex:e}),this.discontinuities[l]={time:e,accuracy:t}}}dispose(){this.trigger("dispose");this.off()}}class cr extends H.EventTarget{constructor(){super();this.pendingTimelineChanges_={};this.lastTimelineChanges_={}}clearPendingTimelineChange(a){this.pendingTimelineChanges_[a]=null;this.trigger("pendingtimelinechange")}pendingTimelineChange({type:a,from:b,to:c}){"number"===typeof b&&"number"===typeof c&&(this.pendingTimelineChanges_[a]={type:a,from:b,to:c},this.trigger("pendingtimelinechange"));
return this.pendingTimelineChanges_[a]}lastTimelineChange({type:a,from:b,to:c}){"number"===typeof b&&"number"===typeof c&&(this.lastTimelineChanges_[a]={type:a,from:b,to:c},delete this.pendingTimelineChanges_[a],this.trigger("timelinechange"));return this.lastTimelineChanges_[a]}dispose(){this.trigger("dispose");this.pendingTimelineChanges_={};this.lastTimelineChanges_={};this.off()}}const dr=al(bl(function(){var a=function(){function x(){this.listeners={}}var y=x.prototype;y.on=function(A,z){this.listeners[A]||
(this.listeners[A]=[]);this.listeners[A].push(z)};y.off=function(A,z){if(!this.listeners[A])return!1;z=this.listeners[A].indexOf(z);this.listeners[A]=this.listeners[A].slice(0);this.listeners[A].splice(z,1);return-1G;G++)ca[(T[G]=G<<1^283*(G>>7))^G]=G;for(O=Q=0;!E[O];O^=K||1,Q=ca[Q]||1){ba=Q^Q<<1^Q<<2^Q<<3^Q<<4;ba=ba>>8^ba&255^99;E[O]=ba;I[ba]=O;var V=T[G=T[K=T[O]]];ta=16843009*V^65537*G^257*K^16843008*O;V=257*T[ba]^16843008*ba;for(G=0;4>G;G++)A[G][O]=V=V<<24^V>>>8,z[G][ba]=ta=ta<<24^ta>>>8}for(G=0;5>G;G++)A[G]=
A[G].slice(0),z[G]=z[G].slice(0);b=y}this._tables=[[b[0][0].slice(),b[0][1].slice(),b[0][2].slice(),b[0][3].slice(),b[0][4].slice()],[b[1][0].slice(),b[1][1].slice(),b[1][2].slice(),b[1][3].slice(),b[1][4].slice()]];y=this._tables[0][4];A=this._tables[1];E=x.length;I=1;if(4!==E&&6!==E&&8!==E)throw Error("Invalid aes key size");O=x.slice(0);Q=[];this._key=[O,Q];for(x=E;x<4*E+28;x++){z=O[x-1];if(0===x%E||8===E&&4===x%E)z=y[z>>>24]<<24^y[z>>16&255]<<16^y[z>>8&255]<<8^y[z&255],0===x%E&&(z=z<<8^z>>>24^
I<<24,I=I<<1^283*(I>>7));O[x]=O[x-E]^z}for(E=0;x;E++,x--)z=O[E&3?x:x-4],Q[E]=4>=x||4>E?z:A[0][y[z>>>24]]^A[1][y[z>>16&255]]^A[2][y[z>>8&255]]^A[3][y[z&255]]}decrypt(x,y,A,z,E,I){const G=this._key[1];x^=G[0];z^=G[1];A^=G[2];y^=G[3];let O,Q;const V=G.length/4-2;let T,ca=4;var K=this._tables[1];const ba=K[0],ta=K[1],Fa=K[2],W=K[3],Da=K[4];for(T=0;T>>24]^ta[z>>16&255]^Fa[A>>8&255]^W[y&255]^G[ca],O=ba[z>>>24]^ta[A>>16&255]^Fa[y>>8&255]^W[x&255]^G[ca+1],Q=ba[A>>>24]^ta[y>>16&255]^Fa[x>>8&
255]^W[z&255]^G[ca+2],y=ba[y>>>24]^ta[x>>16&255]^Fa[z>>8&255]^W[A&255]^G[ca+3],ca+=4,x=K,z=O,A=Q;for(T=0;4>T;T++)E[(3&-T)+I]=Da[x>>>24]<<24^Da[z>>16&255]<<16^Da[A>>8&255]<<8^Da[y&255]^G[ca++],K=x,x=z,z=A,A=y,y=K}}class e extends a{constructor(){super(a);this.jobs=[];this.delay=1;this.timeout_=null}processJob_(){this.jobs.shift()();this.timeout_=this.jobs.length?setTimeout(this.processJob_.bind(this),this.delay):null}push(x){this.jobs.push(x);this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),
this.delay))}}const g=function(x){return x<<24|(x&65280)<<8|(x&16711680)>>8|x>>>24};class l{constructor(x,y,A,z){const E=l.STEP,I=new Int32Array(x.buffer),G=new Uint8Array(x.byteLength);x=0;this.asyncStream_=new e;this.asyncStream_.push(this.decryptChunk_(I.subarray(x,x+E),y,A,G));for(x=E;x>2),I=new c(Array.prototype.slice.call(y)),G=new Uint8Array(x.byteLength),O=new Int32Array(G.buffer);let Q,V,T,ca,K,ba,ta,Fa,W;Q=A[0];V=A[1];T=A[2];ca=A[3];for(W=0;W{const z=x[A];var E="function"===ArrayBuffer.isView?ArrayBuffer.isView(z):z&&z.buffer instanceof ArrayBuffer;y[A]=E?{bytes:z.buffer,byteOffset:z.byteOffset,byteLength:z.byteLength}:z});return y};self.onmessage=function(x){const y=x.data;x=new Uint8Array(y.encrypted.bytes,y.encrypted.byteOffset,y.encrypted.byteLength);const A=new Uint32Array(y.key.bytes,y.key.byteOffset,
y.key.byteLength/4),z=new Uint32Array(y.iv.bytes,y.iv.byteOffset,y.iv.byteLength/4);new l(x,A,z,function(E,I){self.postMessage(t({source:y.source,decrypted:I}),[I.buffer])})}}));var er=$k(dr);const Xl=(a,b)=>{a.abort();a.pause();b&&b.activePlaylistLoader&&(b.activePlaylistLoader.pause(),b.activePlaylistLoader=null)},fr=(a,b)=>()=>{const {segmentLoaders:{[a]:c,main:e},mediaTypes:{[a]:g}}=b;var l=g.activeTrack();const p=g.getActiveGroup(),t=g.activePlaylistLoader,x=g.lastGroup_;p&&x&&p.id===x.id||(g.lastGroup_=
p,g.lastTrack_=l,Xl(c,g),p&&!p.isMainPlaylist&&(p.playlistLoader?(c.resyncLoader(),l=p.playlistLoader,g.activePlaylistLoader=l,l.load()):t&&e.resetEverything()))},gr=(a,b)=>()=>{const {segmentLoaders:{[a]:c},mediaTypes:{[a]:e}}=b;e.lastGroup_=null;c.abort();c.pause()},hr=(a,b)=>()=>{const {mainPlaylistLoader:c,segmentLoaders:{[a]:e,main:g},mediaTypes:{[a]:l}}=b;var p=l.activeTrack(),t=l.getActiveGroup(),x=l.activePlaylistLoader;const y=l.lastTrack_;if(!y||!p||y.id!==p.id)if(l.lastGroup_=t,l.lastTrack_=
p,Xl(e,l),t)if(t.isMainPlaylist)p&&y&&p.id!==y.id&&(t=b.vhs.playlistController_,x=t.selectPlaylist(),t.media()!==x&&(l.logger_(`track change. Switching main audio from ${y.id} to ${p.id}`),c.pause(),g.resetEverything(),t.fastQualityChange_(x)));else{if("AUDIO"===a){if(!t.playlistLoader){g.setAudio(!0);g.resetEverything();return}e.setAudio(!0);g.setAudio(!1)}x===t.playlistLoader?(p=t.playlistLoader,l.activePlaylistLoader=p,p.load()):(e.track&&e.track(p),e.resetEverything(),p=t.playlistLoader,l.activePlaylistLoader=
p,p.load())}},Ue={AUDIO:(a,b)=>()=>{const {mediaTypes:{[a]:c},excludePlaylist:e}=b,g=c.activeTrack();var l=c.activeGroup();l=(l.filter(p=>p.default)[0]||l[0]).id;l=c.tracks[l];if(g===l)e({error:{message:"Problem encountered loading the default audio track."}});else{H.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const p in c.tracks)c.tracks[p].enabled=c.tracks[p]===l;c.onTrackChanged()}},SUBTITLES:(a,b)=>()=>{const {mediaTypes:{[a]:c}}=b;H.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");
const e=c.activeTrack();e&&(e.mode="disabled");c.onTrackChanged()}},Yl={AUDIO:(a,b,c)=>{if(b){var {tech:e,requestOptions:g,segmentLoaders:{[a]:l}}=c;b.on("loadedmetadata",()=>{const p=b.media();l.playlist(p,g);(!e.paused()||p.endList&&"none"!==e.preload())&&l.load()});b.on("loadedplaylist",()=>{l.playlist(b.media(),g);e.paused()||l.load()});b.on("error",Ue[a](a,c))}},SUBTITLES:(a,b,c)=>{const {tech:e,requestOptions:g,segmentLoaders:{[a]:l},mediaTypes:{[a]:p}}=c;b.on("loadedmetadata",()=>{const t=
b.media();l.playlist(t,g);l.track(p.activeTrack());(!e.paused()||t.endList&&"none"!==e.preload())&&l.load()});b.on("loadedplaylist",()=>{l.playlist(b.media(),g);e.paused()||l.load()});b.on("error",Ue[a](a,c))}},ir={AUDIO:(a,b)=>{const {vhs:c,sourceType:e,segmentLoaders:{[a]:g},requestOptions:l,main:{mediaGroups:p},mediaTypes:{[a]:{groups:t,tracks:x,logger_:y}},mainPlaylistLoader:A}=b,z=td(A.main);p[a]&&0!==Object.keys(p[a]).length||(p[a]={main:{default:{default:!0}}},z&&(p[a].main.default.playlists=
A.main.playlists));for(const G in p[a]){t[G]||(t[G]=[]);for(const O in p[a][G]){var E=p[a][G][O],I=void 0;z?(y(`AUDIO group '${G}' label '${O}' is a main playlist`),E.isMainPlaylist=!0,I=null):I="vhs-json"===e&&E.playlists?new Rc(E.playlists[0],c,l):E.resolvedUri?new Rc(E.resolvedUri,c,l):E.playlists&&"dash"===e?new Pg(E.playlists[0],c,l,A):null;E=ia({id:O,playlistLoader:I},E);Yl[a](a,E.playlistLoader,b);t[G].push(E);if("undefined"===typeof x[O]){I=H.AudioTrack;let Q=E.default?"main":"alternative";
E.characteristics&&0<=E.characteristics.indexOf("public.accessibility.describes-video")&&(Q="main-desc");E=new I({id:O,kind:Q,enabled:!1,language:E.language,default:E.default,label:O});x[O]=E}}}g.on("error",Ue[a](a,b))},SUBTITLES:(a,b)=>{const {tech:c,vhs:e,sourceType:g,segmentLoaders:{[a]:l},requestOptions:p,main:{mediaGroups:t},mediaTypes:{[a]:{groups:x,tracks:y}},mainPlaylistLoader:A}=b;for(const E in t[a]){x[E]||(x[E]=[]);for(const I in t[a][E]){if(!e.options_.useForcedSubtitles&&t[a][E][I].forced)continue;
var z=t[a][E][I];let G;if("hls"===g)G=new Rc(z.resolvedUri,e,p);else if("dash"===g){if(!z.playlists.filter(O=>Infinity!==O.excludeUntil).length)return;G=new Pg(z.playlists[0],e,p,A)}else"vhs-json"===g&&(G=new Rc(z.playlists?z.playlists[0]:z.resolvedUri,e,p));z=ia({id:I,playlistLoader:G},z);Yl[a](a,z.playlistLoader,b);x[E].push(z);"undefined"===typeof y[I]&&(z=c.addRemoteTextTrack({id:I,kind:"subtitles",default:z.default&&z.autoselect,language:z.language,label:I},!1).track,y[I]=z)}}l.on("error",Ue[a](a,
b))},"CLOSED-CAPTIONS":(a,b)=>{const {tech:c,main:{mediaGroups:e},mediaTypes:{[a]:{groups:g,tracks:l}}}=b;for(const p in e[a]){g[p]||(g[p]=[]);for(const t in e[a][p]){b=e[a][p][t];if(!/^(?:CC|SERVICE)/.test(b.instreamId))continue;const x=c.options_.vhs&&c.options_.vhs.captionServices||{};let y={label:t,language:b.language,instreamId:b.instreamId,default:b.default&&b.autoselect};x[y.instreamId]&&(y=ia(y,x[y.instreamId]));void 0===y.default&&delete y.default;g[p].push(ia({id:t},b));"undefined"===typeof l[t]&&
(b=c.addRemoteTextTrack({id:y.instreamId,kind:"captions",default:y.default,language:y.language,label:y.label},!1).track,l[t]=b)}}}},Zl=(a,b)=>{for(let c=0;cc=>{const {mainPlaylistLoader:e,mediaTypes:{[a]:{groups:g}}}=b,l=e.media();if(!l)return null;let p=null;l.attributes[a]&&(p=g[l.attributes[a]]);const t=Object.keys(g);if(!p)if("AUDIO"===a&&1x.id===c.id)[0]||null:null},kr={AUDIO:(a,b)=>()=>{const {mediaTypes:{[a]:{tracks:c}}}=b;for(const e in c)if(c[e].enabled)return c[e];return null},SUBTITLES:(a,b)=>()=>{const {mediaTypes:{[a]:{tracks:c}}}=b;for(const e in c)if("showing"===c[e].mode||"hidden"===c[e].mode)return c[e];return null}},lr=(a,{mediaTypes:b})=>()=>{const c=b[a].activeTrack();return c?b[a].activeGroup(c):
null},mr=a=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(y=>{ir[y](y,a)});const {mediaTypes:b,mainPlaylistLoader:c,tech:e,vhs:g,segmentLoaders:{AUDIO:l,main:p}}=a;["AUDIO","SUBTITLES"].forEach(y=>{b[y].activeGroup=jr(y,a);b[y].activeTrack=kr[y](y,a);b[y].onGroupChanged=fr(y,a);b[y].onGroupChanging=gr(y,a);b[y].onTrackChanged=hr(y,a);b[y].getActiveGroup=lr(y,a)});var t=b.AUDIO.activeGroup();t&&(t=(t.filter(y=>y.default)[0]||t[0]).id,b.AUDIO.tracks[t].enabled=!0,b.AUDIO.onGroupChanged(),b.AUDIO.onTrackChanged(),
b.AUDIO.getActiveGroup().playlistLoader?(p.setAudio(!1),l.setAudio(!0)):p.setAudio(!0));c.on("mediachange",()=>{["AUDIO","SUBTITLES"].forEach(y=>b[y].onGroupChanged())});c.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(y=>b[y].onGroupChanging())});const x=()=>{b.AUDIO.onTrackChanged();e.trigger({type:"usage",name:"vhs-audio-change"})};e.audioTracks().addEventListener("change",x);e.remoteTextTracks().addEventListener("change",b.SUBTITLES.onTrackChanged);g.on("dispose",()=>{e.audioTracks().removeEventListener("change",
x);e.remoteTextTracks().removeEventListener("change",b.SUBTITLES.onTrackChanged)});e.clearTracks("audio");for(const y in b.AUDIO.tracks)e.audioTracks().addTrack(b.AUDIO.tracks[y])},nr=()=>{const a={};["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(b=>{a[b]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:Lb,activeTrack:Lb,getActiveGroup:Lb,onGroupChanged:Lb,onTrackChanged:Lb,lastTrack_:null,logger_:mb(`MediaGroups[${b}]`)}});return a};class $l{constructor(){this.priority_=[];this.pathwayClones_=
new Map}set version(a){1===a&&(this.version_=a)}set ttl(a){this.ttl_=a||300}set reloadUri(a){a&&(this.reloadUri_=Ja(this.reloadUri_,a))}set priority(a){a&&a.length&&(this.priority_=a)}set pathwayClones(a){a&&a.length&&(this.pathwayClones_=new Map(a.map(b=>[b.ID,b])))}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 or extends H.EventTarget{constructor(a,b){super();
this.defaultPathway=this.currentPathway=null;this.queryBeforeStart=!1;this.availablePathways_=new Set;this.steeringManifest=new $l;this.request_=this.ttlTimeout_=this.manifestType_=this.proxyServerUrl_=null;this.currentPathwayClones=new Map;this.nextPathwayClones=new Map;this.excludedSteeringManifestURLs=new Set;this.logger_=mb("Content Steering");this.xhr_=a;this.getBandwidth_=b}assignTagProperties(a,b){this.manifestType_=b.serverUri?"HLS":"DASH";const c=b.serverUri||b.serverURL;c?c.startsWith("data:")?
this.decodeDataUriManifest_(c.substring(c.indexOf(",")+1)):(this.steeringManifest.reloadUri=Ja(a,c),this.defaultPathway=b.pathwayId||b.defaultServiceLocation,this.queryBeforeStart=b.queryBeforeStart,this.proxyServerUrl_=b.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering")):(this.logger_(`steering manifest URL is ${c}, cannot request steering manifest.`),this.trigger("error"))}requestSteeringManifest(a){const b=this.steeringManifest.reloadUri;if(b){var c=a?
b:this.getRequestURI(b);c?this.request_=this.xhr_({uri:c,requestType:"content-steering-manifest"},(e,g)=>{e?410===g.status?(this.logger_(`manifest request 410 ${e}.`),this.logger_(`There will be no more content steering requests to ${c} this session.`),this.excludedSteeringManifestURLs.add(c)):429===g.status?(g=g.responseHeaders["retry-after"],this.logger_(`manifest request 429 ${e}.`),this.logger_(`content steering will retry in ${g} seconds.`),this.startTTLTimeout_(parseInt(g,10))):(this.logger_(`manifest failed to load ${e}.`),
this.startTTLTimeout_()):(e=JSON.parse(this.request_.responseText),this.assignSteeringProperties_(e),this.startTTLTimeout_())}):(this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),this.dispose())}}setProxyServerUrl_(a){a=new D.URL(a);const b=new D.URL(this.proxyServerUrl_);b.searchParams.set("url",encodeURI(a.toString()));return this.setSteeringParams_(b.toString())}decodeDataUriManifest_(a){a=JSON.parse(D.atob(a));this.assignSteeringProperties_(a)}setSteeringParams_(a){a=
new D.URL(a);const b=this.getPathway(),c=this.getBandwidth_();b&&a.searchParams.set(`_${this.manifestType_}_pathway`,b);c&&a.searchParams.set(`_${this.manifestType_}_throughput`,c);return a.toString()}assignSteeringProperties_(a){this.steeringManifest.version=a.VERSION;this.steeringManifest.version?(this.steeringManifest.ttl=a.TTL,this.steeringManifest.reloadUri=a["RELOAD-URI"],this.steeringManifest.priority=a["PATHWAY-PRIORITY"]||a["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=
a["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()),a=(b=>{for(const c of b)if(this.availablePathways_.has(c))return c;return[...this.availablePathways_][0]})(this.steeringManifest.priority),this.currentPathway!==a&&(this.currentPathway=a,this.trigger("content-steering"))):(this.logger_(`manifest version is ${a.VERSION}, which is not supported.`),
this.trigger("error"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(a){if(!a)return null;const b=c=>this.excludedSteeringManifestURLs.has(c);if(this.proxyServerUrl_){const c=this.setProxyServerUrl_(a);if(!b(c))return c}a=this.setSteeringParams_(a);return b(a)?null:a}startTTLTimeout_(a=this.steeringManifest.ttl){this.ttlTimeout_=D.setTimeout(()=>{this.requestSteeringManifest()},1E3*a)}clearTTLTimeout_(){D.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.request_=this.ttlTimeout_=this.manifestType_=this.proxyServerUrl_=this.queryBeforeStart=this.defaultPathway=this.currentPathway=null;this.excludedSteeringManifestURLs=new Set;this.availablePathways_=new Set;this.steeringManifest=new $l}addAvailablePathway(a){a&&this.availablePathways_.add(a)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(a){return this.availablePathways_.delete(a)}didDASHTagChange(a,
b){return!b&&this.steeringManifest.reloadUri||b&&(Ja(a,b.serverURL)!==this.steeringManifest.reloadUri||b.defaultServiceLocation!==this.defaultPathway||b.queryBeforeStart!==this.queryBeforeStart||b.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}}let Rb;const pr="mediaRequests mediaRequestsAborted mediaRequestsTimedout mediaRequestsErrored mediaTransferDuration mediaBytesTransferred mediaAppends".split(" "),qr=function(a){return this.audioSegmentLoader_[a]+
this.mainSegmentLoader_[a]},rr=function({currentPlaylist:a,buffered:b,currentTime:c,nextPlaylist:e,bufferLowWaterLine:g,bufferHighWaterLine:l,duration:p,bufferBasedABR:t,log:x}){if(!e)return H.log.warn("We received no playlist to switch to. Please check your stream."),!1;const y=`allowing switch ${a&&a.id||"null"} -> ${e.id}`;if(!a)return x(`${y} as current playlist is not set`),!0;if(e.id===a.id)return!1;const A=!!Pc(b,c).length;if(!a.endList){if(!A&&"number"===typeof a.partTargetDuration)return x(`not ${y} as current playlist is live llhls, but currentTime isn't in buffered.`),
!1;x(`${y} as current playlist is live`);return!0}b=Fg(b,c);c=t?Ha.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:Ha.MAX_BUFFER_LOW_WATER_LINE;if(pa)&&b>=g)return l=`${y} as forwardBuffer >= bufferLowWaterLine (${b} >= ${g})`,
t&&(l+=` and next bandwidth > current bandwidth (${e} > ${a})`),x(l),!0;x(`not ${y} as no switching criteria met`);return!1};class sr extends H.EventTarget{constructor(a){super();const {src:b,withCredentials:c,tech:e,bandwidth:g,externVhs:l,useCueTags:p,playlistExclusionDuration:t,enableLowInitialPlaylist:x,sourceType:y,cacheEncryptionKeys:A,bufferBasedABR:z,leastPixelDiffSelector:E,captionServices:I}=a;if(!b)throw Error("A non-empty playlist URL or JSON manifest string is required");var {maxPlaylistRetries:G}=
a;if(null===G||"undefined"===typeof G)G=Infinity;Rb=l;this.bufferBasedABR=!!z;this.leastPixelDiffSelector=!!E;this.withCredentials=c;this.tech_=e;this.vhs_=e.vhs;this.sourceType_=y;this.useCueTags_=p;this.playlistExclusionDuration=t;this.maxPlaylistRetries=G;this.enableLowInitialPlaylist=x;this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType="");this.requestOptions_={withCredentials:c,maxPlaylistRetries:G,timeout:null};
this.on("error",this.pauseLoading);this.mediaTypes_=nr();this.mediaSource=new D.MediaSource;this.handleDurationChange_=this.handleDurationChange_.bind(this);this.handleSourceOpen_=this.handleSourceOpen_.bind(this);this.handleSourceEnded_=this.handleSourceEnded_.bind(this);this.mediaSource.addEventListener("durationchange",this.handleDurationChange_);this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_);this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_);this.seekable_=
Na();this.hasPlayed_=!1;this.syncController_=new br(a);this.segmentMetadataTrack_=e.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track;this.decrypter_=new er;this.sourceUpdater_=new Ul(this.mediaSource);this.inbandTextTracks_={};this.timelineChangeController_=new cr;this.keyStatusMap_=new Map;G={vhs:this.vhs_,parse708captions:a.parse708captions,useDtsForTimestampOffset:a.useDtsForTimestampOffset,captionServices:I,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:g,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:A,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:a.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};
this.mainPlaylistLoader_="dash"===this.sourceType_?new Pg(b,this.vhs_,ia(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new Rc(b,this.vhs_,ia(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)}));this.setupMainPlaylistLoaderListeners_();this.mainSegmentLoader_=new kh(ia(G,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),a);this.audioSegmentLoader_=new kh(ia(G,{loaderType:"audio"}),a);this.subtitleSegmentLoader_=
new Zq(ia(G,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((O,Q)=>{function V(){e.off("vttjserror",T);O()}function T(){e.off("vttjsloaded",V);Q()}e.one("vttjsloaded",V);e.one("vttjserror",T);e.addWebVttScript_()})}),a);this.contentSteeringController_=new or(this.vhs_.xhr,()=>this.mainSegmentLoader_.bandwidth);this.setupSegmentLoaderListeners_();this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",
()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_()));pr.forEach(O=>{this[O+"_"]=qr.bind(this,O)});this.logger_=mb("pc");this.triggeredFmp4Usage=!1;"none"===this.tech_.preload()?(this.loadOnPlay_=()=>{this.loadOnPlay_=null;this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load();this.audioAppendsToLoadedData__=this.mainAppendsToLoadedData__=this.timeToLoadedData__=-1;a="none"===this.tech_.preload()?"play":"loadstart";this.tech_.one(a,
()=>{const O=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-O;this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends;this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const a=this.mainAppendsToLoadedData_(),b=this.audioAppendsToLoadedData_();return-1===a||-1===b?-1:a+b}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(a=
"abr"){const b=this.selectPlaylist();b&&this.shouldSwitchToMedia_(b)&&this.switchMedia_(b,a)}switchMedia_(a,b,c){var e=this.media();e=e&&(e.id||e.uri);const g=a&&(a.id||a.uri);e&&e!==g&&(this.logger_(`switch media ${e} -> ${g} from ${b}`),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${b}`}));this.mainPlaylistLoader_.media(a,c)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(a=>{var b=this.mediaTypes_[a];b=b?b.activeGroup():null;const c=this.contentSteeringController_.getPathway();
b&&c&&(b=(b.length?b[0].playlists:b.playlists).filter(e=>e.attributes.serviceLocation===c),b.length&&this.mediaTypes_[a].activePlaylistLoader.media(b[0]))})}startABRTimer_(){this.stopABRTimer_();this.abrTimer_=D.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(D.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const a=this.main(),b=a&&a.playlists||[];if(!a||!a.mediaGroups||!a.mediaGroups.AUDIO)return b;const c=a.mediaGroups.AUDIO;
var e=Object.keys(c);let g;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)g=this.mediaTypes_.AUDIO.activeTrack();else{e=c.main||e.length&&c[e[0]];for(var l in e)if(e[l].default){g={label:l};break}}if(!g)return b;l=[];for(const p in c)if(c[p][g.label])if(e=c[p][g.label],e.playlists&&e.playlists.length)l.push.apply(l,e.playlists);else if(e.uri)l.push(e);else if(a.playlists.length)for(e=0;e{const a=this.mainPlaylistLoader_.media(),b=1500*a.targetDuration;Jg(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=b;a.endList&&"none"!==this.tech_.preload()&&(this.mainSegmentLoader_.playlist(a,this.requestOptions_),this.mainSegmentLoader_.load());mr({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(),a);this.setupFirstPlay();if(!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media())this.trigger("selectedinitialmedia");else this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",
()=>{this.trigger("selectedinitialmedia")})});this.mainPlaylistLoader_.on("loadedplaylist",()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let a=this.mainPlaylistLoader_.media();if(!a){this.attachContentSteeringListeners_();this.initContentSteeringController_();this.excludeUnsupportedVariants_();let b;this.enableLowInitialPlaylist&&(b=this.selectInitialPlaylist());b||=this.selectPlaylist();if(!b||!this.shouldSwitchToMedia_(b))return;this.initialMedia_=b;this.switchMedia_(this.initialMedia_,
"initial");if("vhs-json"!==this.sourceType_||!this.initialMedia_.segments)return;a=this.initialMedia_}this.handleUpdatedMediaPlaylist(a)});this.mainPlaylistLoader_.on("error",()=>{const a=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:a.playlist,error:a})});this.mainPlaylistLoader_.on("mediachanging",()=>{this.mainSegmentLoader_.abort();this.mainSegmentLoader_.pause()});this.mainPlaylistLoader_.on("mediachange",()=>{const a=this.mainPlaylistLoader_.media(),b=1500*a.targetDuration;
Jg(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=b;"dash"===this.sourceType_&&this.mainPlaylistLoader_.load();this.mainSegmentLoader_.pause();this.mainSegmentLoader_.playlist(a,this.requestOptions_);this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load();this.tech_.trigger({type:"mediachange",bubbles:!0})});this.mainPlaylistLoader_.on("playlistunchanged",()=>{const a=this.mainPlaylistLoader_.media();
"playlist-unchanged"!==a.lastExcludeReason_&&this.stuckAtPlaylistEnd_(a)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))});this.mainPlaylistLoader_.on("renditiondisabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})});this.mainPlaylistLoader_.on("renditionenabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-enabled"})})}handleUpdatedMediaPlaylist(a){this.useCueTags_&&this.updateAdCues_(a);
this.mainSegmentLoader_.pause();this.mainSegmentLoader_.playlist(a,this.requestOptions_);this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_();this.updateDuration(!a.endList);this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(a,b){a=a.mediaGroups||{};let c=!0;const e=Object.keys(a.AUDIO);for(const g in a.AUDIO)for(const l in a.AUDIO[g])a.AUDIO[g][l].uri||(c=!1);c&&this.tech_.trigger({type:"usage",
name:"vhs-demuxed"});Object.keys(a.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"});Rb.Playlist.isAes(b)&&this.tech_.trigger({type:"usage",name:"vhs-aes"});e.length&&1{this.checkABR_("bandwidthupdate");this.tech_.trigger("bandwidthupdate")});this.mainSegmentLoader_.on("timeout",()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()});
if(!this.bufferBasedABR)this.mainSegmentLoader_.on("progress",()=>{this.trigger("progress")});this.mainSegmentLoader_.on("error",()=>{const b=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:b.playlist,error:b})});this.mainSegmentLoader_.on("appenderror",()=>{this.error=this.mainSegmentLoader_.error_;this.trigger("error")});this.mainSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()});this.mainSegmentLoader_.on("timestampoffset",()=>{this.tech_.trigger({type:"usage",
name:"vhs-timestamp-offset"})});this.audioSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()});this.audioSegmentLoader_.on("appenderror",()=>{this.error=this.audioSegmentLoader_.error_;this.trigger("error")});this.mainSegmentLoader_.on("ended",()=>{this.logger_("main segment loader ended");this.onEndOfStream()});this.mainSegmentLoader_.on("earlyabort",b=>{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:10}))});const a=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const b=this.getCodecsOrExclude_();b&&this.sourceUpdater_.addOrChangeSourceBuffers(b)};this.mainSegmentLoader_.on("trackinfo",a);this.audioSegmentLoader_.on("trackinfo",a);this.mainSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)});this.audioSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||
(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)});this.audioSegmentLoader_.on("ended",()=>{this.logger_("audioSegmentLoader ended");this.onEndOfStream()})}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load();this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load();this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}fastQualityChange_(a=
this.selectPlaylist()){a&&a===this.mainPlaylistLoader_.media()?this.logger_("skipping fastQualityChange because new media is same as old"):(this.switchMedia_(a,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0)}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1;this.mainSegmentLoader_.pause();this.mainSegmentLoader_.resetEverything(()=>{this.tech_.setCurrentTime(this.tech_.currentTime())})}play(){if(!this.setupFirstPlay()){this.tech_.ended()&&this.tech_.setCurrentTime(0);
this.hasPlayed_&&this.load();var a=this.tech_.seekable();if(Infinity===this.tech_.duration()&&this.tech_.currentTime()a?Math.max(c+a,b.start(0)):Math.min(c,a));this.trigger("firstplay");this.tech_.setCurrentTime(e)}this.hasPlayed_=
!0;this.load();return!0}handleSourceOpen_(){this.tryToCreateSourceBuffers_();if(this.tech_.autoplay()){const a=this.tech_.play();"undefined"!==typeof a&&"function"===typeof a.then&&a.then(null,b=>{})}this.trigger("sourceopen")}handleSourceEnded_(){if(this.inbandTextTracks_.metadataTrack_){var a=this.inbandTextTracks_.metadataTrack_.cues;if(a&&a.length){var b=this.duration();a[a.length-1].endTime=isNaN(b)||Infinity===Math.abs(b)?Number.MAX_VALUE:b}}}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let a=
this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){const b=this.mainSegmentLoader_.getCurrentMediaInfo_();a=!b||b.hasVideo?a&&this.audioSegmentLoader_.ended_:this.audioSegmentLoader_.ended_}a&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(a){if(!this.seekable().length)return!1;var b=this.syncController_.getExpiredTime(a,this.duration());if(null===b)return!1;a=Rb.Playlist.playlistEnd(a,b);b=this.tech_.currentTime();var c=this.tech_.buffered();
if(!c.length)return a-b<=Eb;c=c.end(c.length-1);return c-b<=Eb&&a-c<=Eb}excludePlaylist({playlistToExclude:a=this.mainPlaylistLoader_.media(),error:b={},playlistExclusionDuration:c}){a=a||this.mainPlaylistLoader_.media();c=c||b.playlistExclusionDuration||this.playlistExclusionDuration;if(a){a.playlistErrors_++;var e=this.mainPlaylistLoader_.main.playlists,g=e.filter(Ae);g=1===g.length&&g[0]===a;if(1===e.length&&Infinity!==c)return H.log.warn(`Problem encountered with playlist ${a.id}. `+"Trying again since it is the only playlist."),
this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(g);if(g){if(this.main().contentSteering){const p=this.pathwayAttribute_(a);g=1E3*this.contentSteeringController_.steeringManifest.ttl;this.contentSteeringController_.excludePathway(p);this.excludeThenChangePathway_();setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(p)},g);return}let l=!1;e.forEach(p=>{if(p!==a){var t=p.excludeUntil;"undefined"!==typeof t&&Infinity!==t&&(l=!0,delete p.excludeUntil)}});l&&(H.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),
this.tech_.trigger("retryplaylist"))}c=a.playlistErrors_>this.maxPlaylistRetries?Infinity:Date.now()+1E3*c;a.excludeUntil=c;b.reason&&(a.lastExcludeReason_=b.reason);this.tech_.trigger("excludeplaylist");this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});if(c=this.selectPlaylist())return(b.internal?this.logger_:H.log.warn)(`${b.internal?"Internal problem":"Problem"} encountered with playlist ${a.id}.`+`${b.message?" "+b.message:""} Switching to playlist ${c.id}.`),c.attributes.AUDIO!==
a.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),c.attributes.SUBTITLES!==a.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]),b=c.targetDuration/2*1E3||5E3,b="number"===typeof c.lastRequest&&Date.now()-c.lastRequest<=b,this.switchMedia_(c,"exclude",g||b);this.error="Playback cannot continue. No available working or supported playlists.";this.trigger("error")}else this.error=b,"open"!==this.mediaSource.readyState?
this.trigger("error"):this.sourceUpdater_.endOfStream("network")}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]);this.stopABRTimer_()}delegateLoaders_(a,b){const c=[],e="all"===a;(e||"main"===a)&&c.push(this.mainPlaylistLoader_);const g=[];(e||"audio"===a)&&g.push("AUDIO");if(e||"subtitle"===a)g.push("CLOSED-CAPTIONS"),g.push("SUBTITLES");g.forEach(l=>{(l=this.mediaTypes_[l]&&this.mediaTypes_[l].activePlaylistLoader)&&c.push(l)});["main","audio","subtitle"].forEach(l=>{const p=this[`${l}SegmentLoader_`];
!p||a!==l&&"all"!==a||c.push(p)});c.forEach(l=>b.forEach(p=>{if("function"===typeof l[p])l[p]()}))}setCurrentTime(a){const b=Pc(this.tech_.buffered(),a);if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.media()||!this.mainPlaylistLoader_.media().segments)return 0;if(b&&b.length)return a;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 a=this.mainPlaylistLoader_.media();return a?a.endList?this.mediaSource?this.mediaSource.duration:Rb.Playlist.duration(a):Infinity:0}seekable(){return this.seekable_}onSyncInfoUpdate_(){let a;if(this.mainPlaylistLoader_){var b=this.mainPlaylistLoader_.media();if(b){var c=this.syncController_.getExpiredTime(b,this.duration());if(null!==c){var e=this.mainPlaylistLoader_.main,
g=Rb.Playlist.seekable(b,c,Rb.Playlist.liveEdgeDelay(e,b));if(0!==g.length){if(this.mediaTypes_.AUDIO.activePlaylistLoader){b=this.mediaTypes_.AUDIO.activePlaylistLoader.media();c=this.syncController_.getExpiredTime(b,this.duration());if(null===c)return;a=Rb.Playlist.seekable(b,c,Rb.Playlist.liveEdgeDelay(e,b));if(0===a.length)return}if(this.seekable_&&this.seekable_.length){var l=this.seekable_.end(0);var p=this.seekable_.start(0)}a?a.start(0)>g.end(0)||g.start(0)>a.end(0)?this.seekable_=g:this.seekable_=
Na([[a.start(0)>g.start(0)?a.start(0):g.start(0),a.end(0){a=this.mediaTypes_[a].groups;for(const b in a)a[b].forEach(c=>{c.playlistLoader&&c.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_(){var a=!!this.mediaTypes_.AUDIO.activePlaylistLoader;
const b=!!this.mainSegmentLoader_.getCurrentMediaInfo_();a=a?!!this.audioSegmentLoader_.getCurrentMediaInfo_():!0;return b&&a?!0:!1}getCodecsOrExclude_(){const a={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},b=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();a.video=a.main;var c=Ed(this.main(),b);const e={},g=!!this.mediaTypes_.AUDIO.activePlaylistLoader;a.main.hasVideo&&(e.video=c.video||a.main.videoCodec||"avc1.4d400d");
a.main.isMuxed&&(e.video+=`,${c.audio||a.main.audioCodec||"mp4a.40.2"}`);if(a.main.hasAudio&&!a.main.isMuxed||a.audio.hasAudio||g)e.audio=c.audio||a.main.audioCodec||a.audio.audioCodec||"mp4a.40.2",a.audio.isFmp4=a.main.hasAudio&&!a.main.isMuxed?a.main.isFmp4:a.audio.isFmp4;if(e.audio||e.video){var l={},p;["video","audio"].forEach(function(t){var x;if(x=e.hasOwnProperty(t))x=e[t],x=!(a[t].isFmp4?be(x):Kf(x));x&&(x=a[t].isFmp4?"browser":"muxer",l[x]=l[x]||[],l[x].push(e[t]),"audio"===t&&(p=x))});if(g&&
p&&b.attributes.AUDIO){const t=b.attributes.AUDIO;this.main().playlists.forEach(x=>{(x.attributes&&x.attributes.AUDIO)===t&&x!==b&&(x.excludeUntil=Infinity)});this.logger_(`excluding audio group ${t} as ${p} does not support codec(s): "${e.audio}"`)}if(Object.keys(l).length)c=Object.keys(l).reduce((t,x)=>{t&&(t+=", ");return t+=`${x} does not support codec(s): "${l[x].join(",")}"`},"")+".",this.excludePlaylist({playlistToExclude:b,error:{internal:!0,message:c},playlistExclusionDuration:Infinity});
else{if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const t=[];["video","audio"].forEach(x=>{const y=(zb(this.sourceUpdater_.codecs[x]||"")[0]||{}).type,A=(zb(e[x]||"")[0]||{}).type;y&&A&&y.toLowerCase()!==A.toLowerCase()&&t.push(`"${this.sourceUpdater_.codecs[x]}" -> "${e[x]}"`)});if(t.length){this.excludePlaylist({playlistToExclude:b,error:{message:`Codec switching not supported: ${t.join(", ")}.`,internal:!0},playlistExclusionDuration:Infinity});return}}return e}}else this.excludePlaylist({playlistToExclude:b,
error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:Infinity})}tryToCreateSourceBuffers_(){if("open"===this.mediaSource.readyState&&!this.sourceUpdater_.hasCreatedSourceBuffers()&&this.areMediaTypesKnown_()){var a=this.getCodecsOrExclude_();a&&(this.sourceUpdater_.createSourceBuffers(a),a=[a.video,a.audio].filter(Boolean).join(","),this.excludeIncompatibleVariants_(a))}}excludeUnsupportedVariants_(){const a=this.main().playlists,b=[];Object.keys(a).forEach(c=>{c=a[c];
if(-1===b.indexOf(c.id)){b.push(c.id);var e=Ed(this.main,c),g=[];!e.audio||Kf(e.audio)||be(e.audio)||g.push(`audio codec ${e.audio}`);!e.video||Kf(e.video)||be(e.video)||g.push(`video codec ${e.video}`);e.text&&"stpp.ttml.im1t"===e.text&&g.push(`text codec ${e.text}`);g.length&&(c.excludeUntil=Infinity,this.logger_(`excluding ${c.id} for unsupported: ${g.join(", ")}`))}})}excludeIncompatibleVariants_(a){const b=[],c=this.main().playlists;a=Qe(zb(a));const e=Kl(a),g=a.video&&zb(a.video)[0]||null,l=
a.audio&&zb(a.audio)[0]||null;Object.keys(c).forEach(p=>{p=c[p];if(-1===b.indexOf(p.id)&&Infinity!==p.excludeUntil){b.push(p.id);var t=[],x=Ed(this.mainPlaylistLoader_.main,p),y=Kl(x);if(x.audio||x.video)y!==e&&t.push(`codec count "${y}" !== "${e}"`),this.sourceUpdater_.canChangeType()||(y=x.video&&zb(x.video)[0]||null,x=x.audio&&zb(x.audio)[0]||null,y&&g&&y.type.toLowerCase()!==g.type.toLowerCase()&&t.push(`video codec "${y.type}" !== "${g.type}"`),x&&l&&x.type.toLowerCase()!==l.type.toLowerCase()&&
t.push(`audio codec "${x.type}" !== "${l.type}"`)),t.length&&(p.excludeUntil=Infinity,this.logger_(`excluding ${p.id}: ${t.join(" \x26\x26 ")}`))}})}updateAdCues_(a){let b=0;const c=this.seekable();c.length&&(b=c.start(0));$q(a,this.cueTagsTrack_,b)}goalBufferLength(){const a=this.tech_.currentTime(),b=Ha.GOAL_BUFFER_LENGTH;return Math.min(b+a*Ha.GOAL_BUFFER_LENGTH_RATE,Math.max(b,Ha.MAX_GOAL_BUFFER_LENGTH))}bufferLowWaterLine(){const a=this.tech_.currentTime(),b=Ha.BUFFER_LOW_WATER_LINE,c=Math.max(b,
Ha.MAX_BUFFER_LOW_WATER_LINE),e=Math.max(b,Ha.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(b+a*Ha.BUFFER_LOW_WATER_LINE_RATE,this.bufferBasedABR?e:c)}bufferHighWaterLine(){return Ha.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(a){Ol(this.inbandTextTracks_,"com.apple.streaming",this.tech_);Qq({inbandTextTracks:this.inbandTextTracks_,dateRanges:a})}addMetadataToTextTrack(a,b,c){const e=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();
Ol(this.inbandTextTracks_,a,this.tech_);Nq({inbandTextTracks:this.inbandTextTracks_,metadataArray:b,timestampOffset:e,videoDuration:c})}pathwayAttribute_(a){return a.attributes["PATHWAY-ID"]||a.attributes.serviceLocation}initContentSteeringController_(){const a=this.main();if(a.contentSteering){for(const b of a.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(b));this.contentSteeringController_.assignTagProperties(a.uri,a.contentSteering);if(this.contentSteeringController_.queryBeforeStart)this.contentSteeringController_.requestSteeringManifest(!0);
else 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));if("dash"===this.sourceType_)this.mainPlaylistLoader_.on("loadedplaylist",()=>{const a=this.main(),b=()=>
{const c=this.contentSteeringController_.getAvailablePathways(),e=[];for(const g of a.playlists){const l=g.attributes.serviceLocation;if(l&&(e.push(l),!c.has(l)))return!0}return!e.length&&c.size?!0:!1};(this.contentSteeringController_.didDASHTagChange(a.uri,a.contentSteering)||b())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){const a=this.contentSteeringController_.getPathway();if(a){this.handlePathwayClones_();var b=this.main().playlists,c=new Set,e=!1;Object.keys(b).forEach(g=>
{g=b[g];var l=this.pathwayAttribute_(g);l=l&&a!==l;Infinity!==g.excludeUntil||"content-steering"!==g.lastExcludeReason_||l||(delete g.excludeUntil,delete g.lastExcludeReason_,e=!0);const p=!g.excludeUntil&&Infinity!==g.excludeUntil;!c.has(g.id)&&l&&p&&(c.add(g.id),g.excludeUntil=Infinity,g.lastExcludeReason_="content-steering",this.logger_(`excluding ${g.id} for ${g.lastExcludeReason_}`))});"DASH"===this.contentSteeringController_.manifestType_&&Object.keys(this.mediaTypes_).forEach(g=>{g=this.mediaTypes_[g];
g.activePlaylistLoader&&(g=g.activePlaylistLoader.media_)&&g.attributes.serviceLocation!==a&&(e=!0)});e&&this.changeSegmentPathway_()}}handlePathwayClones_(){const a=this.main().playlists,b=this.contentSteeringController_.currentPathwayClones,c=this.contentSteeringController_.nextPathwayClones;if(b&&b.size||c&&c.size){for(const [e,g]of b.entries())c.get(e)||(this.mainPlaylistLoader_.updateOrDeleteClone(g),this.contentSteeringController_.excludePathway(e));for(const [e,g]of c.entries()){const l=b.get(e);
l?this.equalPathwayClones_(l,g)||(this.mainPlaylistLoader_.updateOrDeleteClone(g,!0),this.contentSteeringController_.addAvailablePathway(e)):(a.filter(p=>p.attributes["PATHWAY-ID"]===g["BASE-ID"]).forEach(p=>{this.mainPlaylistLoader_.addClonePathway(g,p)}),this.contentSteeringController_.addAvailablePathway(e))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...c])))}}equalPathwayClones_(a,b){if(a["BASE-ID"]!==b["BASE-ID"]||a.ID!==b.ID||a["URI-REPLACEMENT"].HOST!==
b["URI-REPLACEMENT"].HOST)return!1;a=a["URI-REPLACEMENT"].PARAMS;b=b["URI-REPLACEMENT"].PARAMS;for(const c in a)if(a[c]!==b[c])return!1;for(const c in b)if(a[c]!==b[c])return!1;return!0}changeSegmentPathway_(){const a=this.selectPlaylist();this.pauseLoading();"DASH"===this.contentSteeringController_.manifestType_&&this.switchMediaForDASHContentSteering_();this.switchMedia_(a,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(this.mainPlaylistLoader_&&this.mainPlaylistLoader_.main){var a=0;
this.mainPlaylistLoader_.main.playlists.forEach(b=>{const c=this.mainPlaylistLoader_.getKeyIdSet(b);c&&c.size&&c.forEach(e=>{const g=this.keyStatusMap_.has(e)&&"usable"===this.keyStatusMap_.get(e),l="non-usable"===b.lastExcludeReason_&&Infinity===b.excludeUntil;g?g&&l&&(delete b.excludeUntil,delete b.lastExcludeReason_,this.logger_(`enabling playlist ${b.id} because key ID ${e} is ${"usable"}`)):(Infinity!==b.excludeUntil&&"non-usable"!==b.lastExcludeReason_&&(b.excludeUntil=Infinity,b.lastExcludeReason_=
"non-usable",this.logger_(`excluding playlist ${b.id} because the key ID ${e} doesn't exist in the keyStatusMap or is not ${"usable"}`)),a++)})});a>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(b=>{const c=Infinity===b.excludeUntil&&"non-usable"===b.lastExcludeReason_;b&&b.attributes&&b.attributes.RESOLUTION&&720>b.attributes.RESOLUTION.height&&c&&(delete b.excludeUntil,H.log.warn(`enabling non-HD playlist ${b.id} because all playlists were excluded due to ${"non-usable"} key IDs`))})}}addKeyStatus_(a,
b){a=("string"===typeof a?a:Xq(a)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${b}' with key ID ${a} added to the keyStatusMap`);this.keyStatusMap_.set(a,b)}updatePlaylistByKeyStatus(a,b){this.addKeyStatus_(a,b);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 tr=(a,b,c)=>e=>{const g=a.main.playlists[b],l=Ig(g),p=Ae(g);if("undefined"===typeof e)return p;e?delete g.disabled:g.disabled=!0;e===p||l||(c(g),e?a.trigger("renditionenabled"):a.trigger("renditiondisabled"));return e};class ur{constructor(a,b,c){const {playlistController_:e}=a,g=e.fastQualityChange_.bind(e);if(b.attributes){const l=b.attributes.RESOLUTION;this.width=l&&l.width;this.height=l&&l.height;this.bandwidth=b.attributes.BANDWIDTH;this.frameRate=b.attributes["FRAME-RATE"]}this.codecs=
Ed(e.main(),b);this.playlist=b;this.id=c;this.enabled=tr(a.playlists,b.id,g)}}const vr=function(a){a.representations=()=>{var b=a.playlistController_.main();return(b=td(b)?a.playlistController_.getAudioTrackPlaylists_():b.playlists)?b.filter(c=>!Ig(c)).map((c,e)=>new ur(a,c,c.id)):[]}},am=["seeking","seeked","pause","playing","error"];class wr{constructor(a){this.playlistController_=a.playlistController;this.tech_=a.tech;this.seekable=a.seekable;this.allowSeeksWithinUnsafeLiveWindow=a.allowSeeksWithinUnsafeLiveWindow;
this.liveRangeSafeTimeDelta=a.liveRangeSafeTimeDelta;this.media=a.media;this.consecutiveUpdates=0;this.checkCurrentTimeTimeout_=this.lastRecordedTime=null;this.logger_=mb("PlaybackWatcher");this.logger_("initialize");const b=()=>this.monitorCurrentTime_(),c=()=>this.monitorCurrentTime_(),e=()=>this.techWaiting_(),g=()=>this.resetTimeUpdate_(),l=this.playlistController_,p=["main","subtitle","audio"],t={};p.forEach(y=>{t[y]={reset:()=>this.resetSegmentDownloads_(y),updateend:()=>this.checkSegmentDownloads_(y)};
l[`${y}SegmentLoader_`].on("appendsdone",t[y].updateend);l[`${y}SegmentLoader_`].on("playlistupdate",t[y].reset);this.tech_.on(["seeked","seeking"],t[y].reset)});const x=y=>{["main","audio"].forEach(A=>{l[`${A}SegmentLoader_`][y]("appended",this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),x("off"))};this.clearSeekingAppendCheck_=()=>x("off");this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_();
x("on")};this.tech_.on("seeked",this.clearSeekingAppendCheck_);this.tech_.on("seeking",this.watchForBadSeeking_);this.tech_.on("waiting",e);this.tech_.on(am,g);this.tech_.on("canplay",c);this.tech_.one("play",b);this.dispose=()=>{this.clearSeekingAppendCheck_();this.logger_("dispose");this.tech_.off("waiting",e);this.tech_.off(am,g);this.tech_.off("canplay",c);this.tech_.off("play",b);this.tech_.off("seeking",this.watchForBadSeeking_);this.tech_.off("seeked",this.clearSeekingAppendCheck_);p.forEach(y=>
{l[`${y}SegmentLoader_`].off("appendsdone",t[y].updateend);l[`${y}SegmentLoader_`].off("playlistupdate",t[y].reset);this.tech_.off(["seeked","seeking"],t[y].reset)});this.checkCurrentTimeTimeout_&&D.clearTimeout(this.checkCurrentTimeTimeout_);this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_();this.checkCurrentTimeTimeout_&&D.clearTimeout(this.checkCurrentTimeTimeout_);this.checkCurrentTimeTimeout_=D.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(a){const b=
this.playlistController_[`${a}SegmentLoader_`];0this[`${a}StalledDownloads_`]||(this.logger_(`${a} loader stalled download exclusion`),this.resetSegmentDownloads_(a),this.tech_.trigger({type:"usage",name:`vhs-${a}-download-exclusion`}),"subtitle"!==a&&b.excludePlaylist({error:{message:`Excessive ${a} segment downloading detected.`},playlistExclusionDuration:Infinity})))}checkCurrentTime_(){if(!this.tech_.paused()&&!this.tech_.seeking()){var a=this.tech_.currentTime(),b=this.tech_.buffered();
if(this.lastRecordedTime===a&&(!b.length||a+Eb>=b.end(b.length-1)))return this.techWaiting_();5<=this.consecutiveUpdates&&a===this.lastRecordedTime?(this.consecutiveUpdates++,this.waiting_()):a===this.lastRecordedTime?this.consecutiveUpdates++:(this.consecutiveUpdates=0,this.lastRecordedTime=a)}}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;var a=this.seekable();const b=this.tech_.currentTime();var c;this.afterSeekableWindow_(a,b,this.media(),this.allowSeeksWithinUnsafeLiveWindow)&&
(c=a.end(a.length-1));this.beforeSeekableWindow_(a,b)&&(c=a.start(0),c+=c===a.end(0)?0:Eb);if("undefined"!==typeof c)return this.logger_(`Trying to seek outside of seekable at time ${b} with `+`seekable range ${Ak(a)}. Seeking to `+`${c}.`),this.tech_.setCurrentTime(c),!0;var e=this.playlistController_.sourceUpdater_;a=this.tech_.buffered();c=e.audioBuffer?e.audioBuffered():null;var g=e.videoBuffer?e.videoBuffered():null;e=this.media();e=e.partTargetDuration?e.partTargetDuration:2*(e.targetDuration-
Db);c=[c,g];for(g=0;g ${b.end(0)}]. Attempting to resume `+"playback by seeking to the current time."),this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"}))}}techWaiting_(){var a=this.seekable();const b=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(a,b))return a=a.end(a.length-1),this.logger_(`Fell out of live window at time ${b}. Seeking to `+`live point (seekable end) ${a}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(a),this.tech_.trigger({type:"usage",
name:"vhs-live-resync"}),!0;a=this.tech_.vhs.playlistController_.sourceUpdater_;const c=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:a.audioBuffered(),videoBuffered:a.videoBuffered(),currentTime:b}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(b),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;a=ze(c,b);return 0g?!0:!1}beforeSeekableWindow_(a,b){return a.length&&0a.length)a=Na();else{var c=[];for(var e=1;eb-e&&2{a.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const l=function(){e&&
a.currentTime(e)},p=function(y){null!==y&&void 0!==y&&(e=Infinity!==a.duration()&&a.currentTime()||0,a.one("loadedmetadata",l),a.src(y),a.trigger({type:"usage",name:"vhs-error-reload"}),a.play())},t=function(){if(Date.now()-c<1E3*g.errorInterval)a.trigger({type:"usage",name:"vhs-error-reload-canceled"});else{if(g.getSource&&"function"===typeof g.getSource)return c=Date.now(),g.getSource.call(a,p);H.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!")}},x=function(){a.off("loadedmetadata",
l);a.off("error",t);a.off("dispose",x)};a.on("error",t);a.on("dispose",x);a.reloadSourceOnError=function(y){x();bm(a,y)}},yr=function(a){bm(this,a)},va={PlaylistLoader:Rc,Playlist:Ya,utils:Bp,STANDARD_PLAYLIST_SELECTOR:Nl,INITIAL_PLAYLIST_SELECTOR:function(){const a=this.playlists.main.playlists.filter(Ya.isEnabled);Tc(a,(b,c)=>jh(b,c));return a.filter(b=>!!Ed(this.playlists.main,b).video)[0]||null},lastBandwidthSelector:Nl,movingAverageBandwidthSelector:function(a){let b=-1,c=-1;if(0>a||1b&&(c=b=this.systemBandwidth);0{Object.defineProperty(va,a,{get(){H.log.warn(`using Vhs.${a} is UNSAFE be sure you know what you are doing`);return Ha[a]},
set(b){H.log.warn(`using Vhs.${a} is UNSAFE be sure you know what you are doing`);"number"!==typeof b||0>b?H.log.warn(`value of Vhs.${a} must be greater than or equal to 0`):Ha[a]=b}})});const cm=function(a,b){b=b.media();let c=-1;for(let e=0;e{a.addQualityLevel(c)});cm(a,b.playlists)};va.canPlaySource=function(){return H.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};
const Ar=(a,b)=>a.reduce((c,e)=>{if(!e.contentProtection)return c;const g=b.reduce((l,p)=>{const t=e.contentProtection[p];t&&t.pssh&&(l[p]={pssh:t.pssh});return l},{});Object.keys(g).length&&c.push(g);return c},[]),Br=({player:a,sourceKeySystems:b,audioMedia:c,mainPlaylists:e})=>{if(!a.eme.initializeMediaKeys)return Promise.resolve();c=c?e.concat([c]):e;const g=[],l=[];Ar(c,Object.keys(b)).forEach(p=>{l.push(new Promise((t,x)=>{a.tech_.one("keysessioncreated",t)}));g.push(new Promise((t,x)=>{a.eme.initializeMediaKeys({keySystems:p},
y=>{y?x(y):t()})}))});return Promise.race([Promise.all(g),Promise.race(l)])},Cr=({player:a,sourceKeySystems:b,media:c,audioMedia:e})=>{if(b){var g={};c&&c.attributes&&c.attributes.CODECS&&(g=Qe(zb(c.attributes.CODECS)));e&&e.attributes&&e.attributes.CODECS&&(g.audio=e.attributes.CODECS);e=id(g.video);g=id(g.audio);var l={};for(const p in b)l[p]={},g&&(l[p].audioContentType=g),e&&(l[p].videoContentType=e),c.contentProtection&&c.contentProtection[p]&&c.contentProtection[p].pssh&&(l[p].pssh=c.contentProtection[p].pssh),
"string"===typeof b[p]&&(l[p].url=b[p]);b=ia(b,l)}return b?(a.currentSource().keySystems=b)&&!a.eme?(H.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1):!0:!1},dm=()=>{if(!D.localStorage)return null;const a=D.localStorage.getItem("videojs-vhs");if(!a)return null;try{return JSON.parse(a)}catch(b){return null}},Dr=a=>0===a.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")?JSON.parse(a.substring(a.indexOf(",")+1)):a;va.supportsNativeHls=function(){if(!P||!P.createElement)return!1;
const a=P.createElement("video");return H.getTech("Html5").isSupported()?"application/vnd.apple.mpegurl audio/mpegurl audio/x-mpegurl application/x-mpegurl video/x-mpegurl video/mpegurl application/mpegurl".split(" ").some(function(b){return/maybe|probably/i.test(a.canPlayType(b))}):!1}();var Er=P&&P.createElement&&H.getTech("Html5").isSupported()?/maybe|probably/i.test(P.createElement("video").canPlayType("application/dash+xml")):!1;va.supportsNativeDash=Er;va.supportsTypeNatively=a=>"hls"===a?va.supportsNativeHls:
"dash"===a?va.supportsNativeDash:!1;va.isSupported=function(){return H.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};va.xhr.onRequest=function(a){var b=va.xhr;b._requestCallbackSet||(b._requestCallbackSet=new Set);b._requestCallbackSet.add(a)};va.xhr.onResponse=function(a){var b=va.xhr;b._responseCallbackSet||(b._responseCallbackSet=new Set);b._responseCallbackSet.add(a)};va.xhr.offRequest=function(a){var b=va.xhr;b._requestCallbackSet&&(b._requestCallbackSet.delete(a),
b._requestCallbackSet.size||delete b._requestCallbackSet)};va.xhr.offResponse=function(a){var b=va.xhr;b._responseCallbackSet&&(b._responseCallbackSet.delete(a),b._responseCallbackSet.size||delete b._responseCallbackSet)};const Fr=H.getComponent("Component");class em extends Fr{constructor(a,b,c){super(b,c.vhs);"number"===typeof c.initialBandwidth&&(this.options_.bandwidth=c.initialBandwidth);this.logger_=mb("VhsHandler");b.options_&&b.options_.playerId&&(this.player_=H.getPlayer(b.options_.playerId));
this.tech_=b;this.source_=a;this.stats={};this.ignoreNextSeekingEvent_=!1;this.setOptions_();if(this.options_.overrideNative&&b.overrideNativeAudioTracks&&b.overrideNativeVideoTracks)b.overrideNativeAudioTracks(!0),b.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(b.featuresNativeVideoTracks||b.featuresNativeAudioTracks))throw Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on(P,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange",
"MSFullscreenChange"],e=>{(e=P.fullscreenElement||P.webkitFullscreenElement||P.mozFullScreenElement||P.msFullscreenElement)&&e.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()});this.on(this.tech_,"seeking",function(){this.ignoreNextSeekingEvent_?this.ignoreNextSeekingEvent_=!1: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_(a={}){this.options_=ia(this.options_,a);this.options_.withCredentials=this.options_.withCredentials||!1;this.options_.limitRenditionByPlayerDimensions=!1===this.options_.limitRenditionByPlayerDimensions?!1:!0;this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1;this.options_.useBandwidthFromLocalStorage="undefined"!==typeof this.source_.useBandwidthFromLocalStorage?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=!1===this.options_.llhls?!1:!0;this.options_.bufferBasedABR=
this.options_.bufferBasedABR||!1;"number"!==typeof this.options_.playlistExclusionDuration&&(this.options_.playlistExclusionDuration=60);"number"!==typeof this.options_.bandwidth&&this.options_.useBandwidthFromLocalStorage&&((a=dm())&&a.bandwidth&&(this.options_.bandwidth=a.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),a&&a.throughput&&(this.options_.throughput=a.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"})));"number"!==
typeof this.options_.bandwidth&&(this.options_.bandwidth=Ha.INITIAL_BANDWIDTH);this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===Ha.INITIAL_BANDWIDTH;"withCredentials useDevicePixelRatio customPixelRatio limitRenditionByPlayerDimensions bandwidth customTagParsers customTagMappers cacheEncryptionKeys playlistSelector initialPlaylistSelector bufferBasedABR liveRangeSafeTimeDelta llhls useForcedSubtitles useNetworkInformationApi useDtsForTimestampOffset exactManifestTimings leastPixelDiffSelector".split(" ").forEach(b=>
{"undefined"!==typeof this.source_[b]&&(this.options_[b]=this.source_[b])});this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions;this.useDevicePixelRatio=this.options_.useDevicePixelRatio;a=this.options_.customPixelRatio;"number"===typeof a&&0<=a&&(this.customPixelRatio=a)}setOptions(a={}){this.setOptions_(a)}src(a,b){a&&(this.setOptions_(),this.options_.src=Dr(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=va,this.options_.sourceType=Ni(b),
this.options_.seekTo=c=>{this.tech_.setCurrentTime(c)},this.playlistController_=new sr(this.options_),a=ia({liveRangeSafeTimeDelta:Eb},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_}),this.playbackWatcher_=new wr(a),this.playlistController_.on("error",()=>{const c=H.players[this.tech_.options_.playerId];let e=this.playlistController_.error;"object"!==typeof e||e.code?"string"===typeof e&&(e={message:e,code:3}):e.code=
3;c.error(e)}),a=this.options_.bufferBasedABR?va.movingAverageBandwidthSelector(.55):va.STANDARD_PLAYLIST_SELECTOR,this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):a.bind(this),this.playlistController_.selectInitialPlaylist=va.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(c){this.playlistController_.selectPlaylist=c.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(c){this.playlistController_.mainSegmentLoader_.throughput.rate=c;this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let c=this.playlistController_.mainSegmentLoader_.bandwidth;var e=D.navigator.connection||D.navigator.mozConnection||D.navigator.webkitConnection;this.options_.useNetworkInformationApi&&e&&(e=1E6*e.downlink,
c=1E7<=e&&1E7<=c?Math.max(c,e):e);return c},set(c){this.playlistController_.mainSegmentLoader_.bandwidth=c;this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){return Math.floor(1/(1/(this.bandwidth||1)+(0this.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:()=>lc(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:()=>lc(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",()=>{if(this.options_.useBandwidthFromLocalStorage){var c={bandwidth:this.bandwidth,throughput:Math.round(this.throughput)};if(D.localStorage){var e=
dm();e=e?ia(e,c):c;try{D.localStorage.setItem("videojs-vhs",JSON.stringify(e))}catch(g){}}}}),this.playlistController_.on("selectedinitialmedia",()=>{vr(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_=D.URL.createObjectURL(this.playlistController_.mediaSource),
this.tech_.src(this.mediaSourceUrl_)))}createKeySessions_(){const a=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation");Br({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:a&&a.media(),mainPlaylists:this.playlists.main.playlists}).then(()=>{this.logger_("created EME key session");this.playlistController_.sourceUpdater_.initializedEme()}).catch(b=>{this.logger_("error while creating EME key session",b);this.player_.error({message:"Failed to initialize media keys for EME",
code:3,metadata:{errorType:H.Error.EMEKeySessionCreationError}})})}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions");this.createKeySessions_()}setupEme_(){var a=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;a=Cr({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:a&&a.media()});this.player_.tech_.on("keystatuschange",b=>{this.playlistController_.updatePlaylistByKeyStatus(b.keyId,
b.status)});this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this);this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_);a?this.createKeySessions_():this.playlistController_.sourceUpdater_.initializedEme()}setupQualityLevels_(){const a=H.players[this.tech_.options_.playerId];a&&a.qualityLevels&&!this.qualityLevels_&&(this.qualityLevels_=a.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{zr(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{cm(this.qualityLevels_,
this.playlists)}))}static version(){return{"@videojs/http-streaming":"3.12.1","mux.js":"7.0.3","mpd-parser":"1.3.0","m3u8-parser":"7.1.0","aes-decrypter":"4.0.1"}}version(){return this.constructor.version()}canChangeType(){return Ul.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(a){this.playlistController_.setCurrentTime(a)}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_&&D.URL.revokeObjectURL&&(D.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null);this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_);super.dispose()}convertToProgramTime(a,b){return Gp({playlist:this.playlistController_.media(),time:a,callback:b})}seekToProgramTime(a,b,c=!0,e=2){return Vk({programTime:a,
playlist:this.playlistController_.media(),retryCount:e,pauseAfterSeek:c,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:b})}setupXhrHooks_(){this.xhr.onRequest=a=>{var b=this.xhr;b._requestCallbackSet||(b._requestCallbackSet=new Set);b._requestCallbackSet.add(a)};this.xhr.onResponse=a=>{var b=this.xhr;b._responseCallbackSet||(b._responseCallbackSet=new Set);b._responseCallbackSet.add(a)};this.xhr.offRequest=a=>{var b=this.xhr;b._requestCallbackSet&&(b._requestCallbackSet.delete(a),b._requestCallbackSet.size||
delete b._requestCallbackSet)};this.xhr.offResponse=a=>{var b=this.xhr;b._responseCallbackSet&&(b._responseCallbackSet.delete(a),b._responseCallbackSet.size||delete b._responseCallbackSet)};this.player_.trigger("xhr-hooks-ready")}}const Ve={name:"videojs-http-streaming",VERSION:"3.12.1",canHandleSource(a,b={}){b=ia(H.options,b);return Ve.canPlayType(a.type,b)},handleSource(a,b,c={}){c=ia(H.options,c);b.vhs=new em(a,b,c);b.vhs.xhr=Sk();b.vhs.setupXhrHooks_();b.vhs.src(a.src,a.type);return b.vhs},canPlayType(a,
b){a=Ni(a);if(!a)return"";b=Ve.getOverrideNative(b);return!va.supportsTypeNatively(a)||b?"maybe":""},getOverrideNative(a={}){({vhs:a={}}=a);const b=!(H.browser.IS_ANY_SAFARI||H.browser.IS_IOS);({overrideNative:a=b}=a);return a}};be("avc1.4d400d,mp4a.40.2")&&H.getTech("Html5").registerSourceHandler(Ve,0);H.VhsHandler=em;H.VhsSourceHandler=Ve;H.Vhs=va;H.use||H.registerComponent("Vhs",va);H.options.vhs=H.options.vhs||{};H.getPlugin&&H.getPlugin("reloadSourceOnError")||H.registerPlugin("reloadSourceOnError",
yr);let xa=class extends fm{constructor(){super();this._defaultConfigs={autoplay:!1,fluid:!1,fullscreen:!1,loop:!1,muted:!1,preload:"auto",responsive:!1,startTime:0};this._prevPlayingState=!1;this.sensorModel=this.element=this.currentMetadata=null;this.state="not-ready";this.waitingTimestamp=null;this._initController=()=>{!this._controller&&this.playerUrl&&(this.element=document.createElement("video"),H.log.level("error"),this._controller=H(this.element,this._defaultConfigs),this._controller.muted(this.muted),
this._controller.loop(this.loop),this._controller.playbackRate(this.rate),this._controller.ready(this._handleReady),this._controller.on("canplay",this._handleCanPlay),this._controller.on("durationchange",this._handleDurationChange),this._controller.on("ended",this._handleEnded),this._controller.on("error",this._handleError),this._controller.on("loadeddata",this._handleDataLoaded),this._controller.on("loadedmetadata",this._handleLoadedMetadata),this._controller.on("loadstart",this._handleLoadStart),
this._controller.on("play",this._handlePlay),this._controller.on("timeupdate",this._handleTimeUpdate),this._controller.on("waiting",this._handleWaiting),this._controller.on("xhr-hooks-ready",this._handleXHRhooksReady))};this._handleReady=()=>{this.state="ready"};this._handleCanPlay=()=>{this._prevPlayingState="playing"===this.state;this.state="can-play"};this._handleCueChange=()=>{if(this.subtitleTrack?.activeCues?.length){var a=this.subtitleTrack?.activeCues[0];a=a.text?JSON.parse(a.text):null;if(a?.data?.length){a=
a.data[0]?.value??[];var b=new Map;for(const c of a)Array.isArray(c.value)?90064===c.tagId?b.set(c.tagId,c):c.value.forEach(e=>{b.set(e.tagId,e)}):b.set(c.tagId,c);b.set(Hd.videoMetadataEntryId.EsriVideoWidth,{name:"Video Width",tagId:Hd.videoMetadataEntryId.EsriVideoWidth,value:this._controller?.videoWidth()});b.set(Hd.videoMetadataEntryId.EsriVideoHeight,{name:"Video Height",tagId:Hd.videoMetadataEntryId.EsriVideoHeight,value:this._controller?.videoHeight()});this.currentMetadata=new Map(b);this.sensorModel=
new km({videoMetadata:this.currentMetadata})}}};this._handleDataLoaded=()=>{this.state="data-loaded";this._set("videoWidth",this._controller?.videoWidth());this._set("videoHeight",this._controller?.videoHeight())};this._handleDurationChange=()=>this.notifyChange("duration");this._handleEnded=()=>{this.loop?(this.setCurrentTime(0),this.play()):(this._set("ended",!0),this.notifyChange("buffered"),this.notifyChange("currentTime"),this.notifyChange("duration"),this.notifyChange("waiting"),this.state=
"can-play")};this._handleError=()=>{gm.getLogger(this).error("video stream error ::",this._controller?.error())};this._handleLoadStart=()=>{this.state="can-play"};this._handleLoadedMetadata=()=>{this.notifyChange("subtitleTrack");this.notifyChange("buffered")};this._handlePlay=()=>this.notifyChange("ended");this._handleTimeUpdate=()=>{this.notifyChange("currentTime");this.notifyChange("buffered");this.notifyChange("bufferedPercent");this._set("videoWidth",this._controller?.videoWidth());this._set("videoHeight",
this._controller?.videoHeight())};this._handleWaiting=()=>{this.waitingTimestamp=this._controller?.currentTime()};this._handleXHRhooksReady=()=>{const a=b=>{b.xhr=new im.XHRAdapter;return b};this._controller?.tech(!0)?.vhs.xhr.onRequest(a)}}initialize(){this.addHandles([Gd.watch(()=>this.playerUrl,a=>{a&&(this._initController(),this._controller?.src({type:"application/x-mpegURL",src:this.playerUrl}))},Gd.initial),Gd.watch(()=>this.subtitleTrack,()=>{this.subtitleTrack&&(this.subtitleTrack.mode="showing")})]);
this.addHandles(Gd.on(()=>this.subtitleTrack,"cuechange",this._handleCueChange))}destroy(){this._controller?.dispose()}get buffered(){return this._controller?.bufferedEnd()??0}get bufferedPercent(){return this._controller?.bufferedPercent()??0}get currentTime(){return this._controller?.currentTime()??0}get duration(){return this._controller?.duration()??0}get ended(){return this._controller?.ended()??this._get("ended")??!0}set ended(a){this._controller?.ended(a);this._set("ended",a)}get loop(){return this._controller?.loop()??
this._get("loop")??!1}set loop(a){this._controller?.loop(a);this._set("loop",a)}get muted(){return this._controller?.muted()??this._get("muted")??!1}set muted(a){this._controller?.muted(a);this._set("muted",a)}get playerUrl(){return this._controller?.src()||""}set playerUrl(a){this._set("playerUrl",a)}get playing(){return this.ended?!1:"can-play"===this.state?this._prevPlayingState:"playing"===this.state}get rate(){return this._controller?.playbackRate()??this._get("rate")??1}set rate(a){this._controller?.playbackRate(a);
this._set("rate",a)}get started(){return this._controller?.hasStarted()||!1}get subtitleTrack(){const a=this._controller?.textTracks();return a?.length?Array.from(a).find(b=>"subtitles"===b.kind):null}get waiting(){return this.waitingTimestamp?!1:this.waitingTimestamp!==this.currentTime?(this.waitingTimestamp=null,!1):!0}pause(){this._controller?.pause();this.state="paused"}play(){this._controller?.play();this.state="playing"}reset(){this._controller&&(this.pause(),this.setCurrentTime(0),this._set("ended",
!0))}setCurrentTime(a){a=hm.clamp(a,0,this.duration);this._controller?.currentTime(a);this.notifyChange("currentTime")}};ya.__decorate([Aa.property()],xa.prototype,"buffered",null);ya.__decorate([Aa.property()],xa.prototype,"bufferedPercent",null);ya.__decorate([Aa.property({readOnly:!0})],xa.prototype,"currentTime",null);ya.__decorate([Aa.property()],xa.prototype,"currentMetadata",void 0);ya.__decorate([Aa.property({readOnly:!0})],xa.prototype,"duration",null);ya.__decorate([Aa.property()],xa.prototype,
"element",void 0);ya.__decorate([Aa.property({readOnly:!0})],xa.prototype,"ended",null);ya.__decorate([Aa.property()],xa.prototype,"loop",null);ya.__decorate([Aa.property()],xa.prototype,"muted",null);ya.__decorate([Aa.property()],xa.prototype,"playerUrl",null);ya.__decorate([Aa.property({readOnly:!0})],xa.prototype,"playing",null);ya.__decorate([Aa.property()],xa.prototype,"rate",null);ya.__decorate([Aa.property()],xa.prototype,"sensorModel",void 0);ya.__decorate([Aa.property({readOnly:!0})],xa.prototype,
"started",null);ya.__decorate([Aa.property()],xa.prototype,"state",void 0);ya.__decorate([Aa.property()],xa.prototype,"subtitleTrack",null);ya.__decorate([Aa.property({readOnly:!0})],xa.prototype,"videoHeight",void 0);ya.__decorate([Aa.property({readOnly:!0})],xa.prototype,"videoWidth",void 0);ya.__decorate([Aa.property({readOnly:!0})],xa.prototype,"waiting",null);ya.__decorate([Aa.property()],xa.prototype,"waitingTimestamp",void 0);return xa=ya.__decorate([jm.subclass("esri.layers.video.VideoController")],
xa)});