@srgssr/pillarbox-web 1.25.0 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -26,5 +26,5 @@ class qo{constructor(e){let t=this;return t.id=e.id,t.label=t.id,t.width=e.width
26
26
  const Ho=K,zo=(e,t)=>t&&t.responseURL&&e!==t.responseURL?t.responseURL:e,Wo=e=>Fo.log.debug?Fo.log.debug.bind(Fo,"VHS:",`${e} >`):function(){};function Go(...e){const t=Fo.obj||Fo;return(t.merge||t.mergeOptions).apply(t,e)}function Xo(...e){const t=Fo.time||Fo;return(t.createTimeRanges||t.createTimeRanges).apply(t,e)}const Ko=1/30,Yo=.1,Qo=function(e,t){const i=[];let s;if(e&&e.length)for(s=0;s<e.length;s++)t(e.start(s),e.end(s))&&i.push([e.start(s),e.end(s)]);return Xo(i)},Jo=function(e,t){return Qo(e,function(e,i){return e-Yo<=t&&i+Yo>=t})},Zo=function(e,t){return Qo(e,function(e){return e-Ko>=t})},el=e=>{const t=[];if(!e||!e.length)return"";for(let i=0;i<e.length;i++)t.push(e.start(i)+" => "+e.end(i));return t.join(", ")},tl=e=>{const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t},il=function(e){if(e&&e.length&&e.end)return e.end(e.length-1)},sl=function(e,t){let i=0;if(!e||!e.length)return i;for(let s=0;s<e.length;s++){const r=e.start(s),n=e.end(s);t>n||(i+=t>r&&t<=n?n-t:n-r)}return i},rl=(e,t)=>{if(!t.preload)return t.duration;let i=0;return(t.parts||[]).forEach(function(e){i+=e.duration}),(t.preloadHints||[]).forEach(function(t){"PART"===t.type&&(i+=e.partTargetDuration)}),i},nl=e=>(e.segments||[]).reduce((e,t,i)=>(t.parts?t.parts.forEach(function(s,r){e.push({duration:s.duration,segmentIndex:i,partIndex:r,part:s,segment:t})}):e.push({duration:t.duration,segmentIndex:i,partIndex:null,segment:t,part:null}),e),[]),al=e=>{const t=e.segments&&e.segments.length&&e.segments[e.segments.length-1];return t&&t.parts||[]},ol=({preloadSegment:e})=>{if(!e)return;const{parts:t,preloadHints:i}=e;let s=(i||[]).reduce((e,t)=>e+("PART"===t.type?1:0),0);return s+=t&&t.length?t.length:0,s},ll=(e,t)=>{if(t.endList)return 0;if(e&&e.suggestedPresentationDelay)return e.suggestedPresentationDelay;const i=al(t).length>0;return i&&t.serverControl&&t.serverControl.partHoldBack?t.serverControl.partHoldBack:i&&t.partTargetDuration?3*t.partTargetDuration:t.serverControl&&t.serverControl.holdBack?t.serverControl.holdBack:t.targetDuration?3*t.targetDuration:0},dl=function(e,t,i){if(void 0===t&&(t=e.mediaSequence+e.segments.length),t<e.mediaSequence)return 0;const s=function(e,t){let i=0,s=t-e.mediaSequence,r=e.segments[s];if(r){if(void 0!==r.start)return{result:r.start,precise:!0};if(void 0!==r.end)return{result:r.end-r.duration,precise:!0}}for(;s--;){if(r=e.segments[s],void 0!==r.end)return{result:i+r.end,precise:!0};if(i+=rl(e,r),void 0!==r.start)return{result:i+r.start,precise:!0}}return{result:i,precise:!1}}(e,t);if(s.precise)return s.result;const r=function(e,t){let i,s=0,r=t-e.mediaSequence;for(;r<e.segments.length;r++){if(i=e.segments[r],void 0!==i.start)return{result:i.start-s,precise:!0};if(s+=rl(e,i),void 0!==i.end)return{result:i.end-s,precise:!0}}return{result:-1,precise:!1}}(e,t);return r.precise?r.result:s.result+i},ul=function(e,t,i){if(!e)return 0;if("number"!=typeof i&&(i=0),void 0===t){if(e.totalDuration)return e.totalDuration;if(!e.endList)return p.Infinity}return dl(e,t,i)},cl=function({defaultDuration:e,durationList:t,startIndex:i,endIndex:s}){let r=0;if(i>s&&([i,s]=[s,i]),i<0){for(let t=i;t<Math.min(0,s);t++)r+=e;i=0}for(let e=i;e<s;e++)r+=t[e].duration;return r},hl=function(e,t,i,s){if(!e||!e.segments)return null;if(e.endList)return ul(e);if(null===t)return null;t=t||0;let r=dl(e,e.mediaSequence+e.segments.length,t);return i&&(r-=s="number"==typeof s?s:ll(null,e)),Math.max(0,r)},pl=function(e){return e.excludeUntil&&e.excludeUntil>Date.now()},ml=function(e){return e.excludeUntil&&e.excludeUntil===1/0},gl=function(e){const t=pl(e);return!e.disabled&&!t},fl=function(e,t){return t.attributes&&t.attributes[e]},yl=(e,t)=>{if(1===e.playlists.length)return!0;const i=t.attributes.BANDWIDTH||Number.MAX_VALUE;return 0===e.playlists.filter(e=>!!gl(e)&&(e.attributes.BANDWIDTH||0)<i).length},_l=(e,t)=>!(!e&&!t||!e&&t||e&&!t)&&(e===t||(!(!e.id||!t.id||e.id!==t.id)||(!(!e.resolvedUri||!t.resolvedUri||e.resolvedUri!==t.resolvedUri)||!(!e.uri||!t.uri||e.uri!==t.uri)))),bl=function(e,t){const i=e&&e.mediaGroups&&e.mediaGroups.AUDIO||{};let s=!1;for(const e in i){for(const r in i[e])if(s=t(i[e][r]),s)break;if(s)break}return!!s},vl=e=>{if(!e||!e.playlists||!e.playlists.length){return bl(e,e=>e.playlists&&e.playlists.length||e.uri)}for(let t=0;t<e.playlists.length;t++){const i=e.playlists[t],s=i.attributes&&i.attributes.CODECS;if(s&&s.split(",").every(e=>me(e)))continue;if(!bl(e,e=>_l(i,e)))return!1}return!0};var Tl={liveEdgeDelay:ll,duration:ul,seekable:function(e,t,i){const s=t||0;let r=hl(e,t,!0,i);return null===r?Xo():(r<s&&(r=s),Xo(s,r))},getMediaInfoForTime:function({playlist:e,currentTime:t,startingSegmentIndex:i,startingPartIndex:s,startTime:r,exactManifestTimings:n}){let a=t-r;const o=nl(e);let l=0;for(let e=0;e<o.length;e++){const t=o[e];if(i===t.segmentIndex&&("number"!=typeof s||"number"!=typeof t.partIndex||s===t.partIndex)){l=e;break}}if(a<0){if(l>0)for(let t=l-1;t>=0;t--){const i=o[t];if(a+=i.duration,n){if(a<0)continue}else if(a+Ko<=0)continue;return{partIndex:i.partIndex,segmentIndex:i.segmentIndex,startTime:r-cl({defaultDuration:e.targetDuration,durationList:o,startIndex:l,endIndex:t})}}return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:t}}if(l<0){for(let i=l;i<0;i++)if(a-=e.targetDuration,a<0)return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:t};l=0}for(let t=l;t<o.length;t++){const i=o[t];a-=i.duration;const s=i.duration>Ko;if(!(0===a)&&!(s&&a+Ko>=0)||t===o.length-1){if(n){if(a>0)continue}else if(a-Ko>=0)continue;return{partIndex:i.partIndex,segmentIndex:i.segmentIndex,startTime:r+cl({defaultDuration:e.targetDuration,durationList:o,startIndex:l,endIndex:t})}}}return{segmentIndex:o[o.length-1].segmentIndex,partIndex:o[o.length-1].partIndex,startTime:t}},isEnabled:gl,isDisabled:function(e){return e.disabled},isExcluded:pl,isIncompatible:ml,playlistEnd:hl,isAes:function(e){for(let t=0;t<e.segments.length;t++)if(e.segments[t].key)return!0;return!1},hasAttribute:fl,estimateSegmentRequestTime:function(e,t,i,s=0){if(!fl("BANDWIDTH",i))return NaN;return(e*i.attributes.BANDWIDTH-8*s)/t},isLowestEnabledRendition:yl,isAudioOnly:vl,playlistMatch:_l,segmentDurationWithParts:rl};const{log:Sl}=Fo,El=(e,t)=>`${e}-${t}`,wl=(e,t,i)=>`placeholder-uri-${e}-${t}-${i}`,kl=(e,t)=>{e.mediaGroups&&["AUDIO","SUBTITLES"].forEach(i=>{if(e.mediaGroups[i])for(const s in e.mediaGroups[i])for(const r in e.mediaGroups[i][s]){const n=e.mediaGroups[i][s][r];t(n,i,s,r)}})},Cl=({playlist:e,uri:t,id:i})=>{e.id=i,e.playlistErrors_=0,t&&(e.uri=t),e.attributes=e.attributes||{}},Il=(e,t,i=wl)=>{e.uri=t;for(let t=0;t<e.playlists.length;t++)if(!e.playlists[t].uri){const i=`placeholder-uri-${t}`;e.playlists[t].uri=i}const s=vl(e);kl(e,(t,r,n,a)=>{if(!t.playlists||!t.playlists.length){if(s&&"AUDIO"===r&&!t.uri)for(let t=0;t<e.playlists.length;t++){const i=e.playlists[t];if(i.attributes&&i.attributes.AUDIO&&i.attributes.AUDIO===n)return}t.playlists=[G({},t)]}t.playlists.forEach(function(t,s){const o=i(r,n,a,t),l=El(s,o);t.uri?t.resolvedUri=t.resolvedUri||Ho(e.uri,t.uri):(t.uri=0===s?o:l,t.resolvedUri=t.uri),t.id=t.id||l,t.attributes=t.attributes||{},e.playlists[t.id]=t,e.playlists[t.uri]=t})}),(e=>{let t=e.playlists.length;for(;t--;){const i=e.playlists[t];Cl({playlist:i,id:El(t,i.uri)}),i.resolvedUri=Ho(e.uri,i.uri),e.playlists[i.id]=i,e.playlists[i.uri]=i,i.attributes.BANDWIDTH||Sl.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}})(e),(e=>{kl(e,t=>{t.uri&&(t.resolvedUri=Ho(e.uri,t.uri))})})(e)};class xl{constructor(){this.offset_=null,this.pendingDateRanges_=new Map,this.processedDateRanges_=new Map}setOffset(e=[]){if(null!==this.offset_)return;if(!e.length)return;const[t]=e;void 0!==t.programDateTime&&(this.offset_=t.programDateTime/1e3)}setPendingDateRanges(e=[]){if(!e.length)return;const[t]=e,i=t.startDate.getTime();this.trimProcessedDateRanges_(i),this.pendingDateRanges_=e.reduce((e,t)=>(e.set(t.id,t),e),new Map)}processDateRange(e){this.pendingDateRanges_.delete(e.id),this.processedDateRanges_.set(e.id,e)}getDateRangesToProcess(){if(null===this.offset_)return[];const e={},t=[];this.pendingDateRanges_.forEach((i,s)=>{if(!this.processedDateRanges_.has(s)&&(i.startTime=i.startDate.getTime()/1e3-this.offset_,i.processDateRange=()=>this.processDateRange(i),t.push(i),i.class))if(e[i.class]){const t=e[i.class].push(i);i.classListIndex=t-1}else e[i.class]=[i],i.classListIndex=0});for(const i of t){const t=e[i.class]||[];i.endDate?i.endTime=i.endDate.getTime()/1e3-this.offset_:i.endOnNext&&t[i.classListIndex+1]?i.endTime=t[i.classListIndex+1].startTime:i.duration?i.endTime=i.startTime+i.duration:i.plannedDuration?i.endTime=i.startTime+i.plannedDuration:i.endTime=i.startTime}return t}trimProcessedDateRanges_(e){new Map(this.processedDateRanges_).forEach((t,i)=>{t.startDate.getTime()<e&&this.processedDateRanges_.delete(i)})}}const Al=({requestType:e,request:t,error:i,parseFailure:s})=>{const r=t.status<200||t.status>299,n=t.status>=400&&t.status<=499,a={uri:t.uri,requestType:e},o=r&&!n||s;if(i&&n)a.error=G({},i),a.errorType=Fo.Error.NetworkRequestFailed;else if(t.aborted)a.errorType=Fo.Error.NetworkRequestAborted;else if(t.timedout)a.erroType=Fo.Error.NetworkRequestTimeout;else if(o){const e=s?Fo.Error.NetworkBodyParserFailed:Fo.Error.NetworkBadStatus;a.errorType=e,a.status=t.status,a.headers=t.headers}return a},{EventTarget:Dl}=Fo,Pl=(e,t)=>{if(!e)return t;const i=Go(e,t);if(e.preloadHints&&!t.preloadHints&&delete i.preloadHints,e.parts&&!t.parts)delete i.parts;else if(e.parts&&t.parts)for(let s=0;s<t.parts.length;s++)e.parts&&e.parts[s]&&(i.parts[s]=Go(e.parts[s],t.parts[s]));return!e.skipped&&t.skipped&&(i.skipped=!1),e.preload&&!t.preload&&(i.preload=!1),i},Ll=(e,t)=>{!e.resolvedUri&&e.uri&&(e.resolvedUri=Ho(t,e.uri)),e.key&&!e.key.resolvedUri&&(e.key.resolvedUri=Ho(t,e.key.uri)),e.map&&!e.map.resolvedUri&&(e.map.resolvedUri=Ho(t,e.map.uri)),e.map&&e.map.key&&!e.map.key.resolvedUri&&(e.map.key.resolvedUri=Ho(t,e.map.key.uri)),e.parts&&e.parts.length&&e.parts.forEach(e=>{e.resolvedUri||(e.resolvedUri=Ho(t,e.uri))}),e.preloadHints&&e.preloadHints.length&&e.preloadHints.forEach(e=>{e.resolvedUri||(e.resolvedUri=Ho(t,e.uri))})},Ol=function(e){const t=e.segments||[],i=e.preloadSegment;if(i&&i.parts&&i.parts.length){if(i.preloadHints)for(let e=0;e<i.preloadHints.length;e++)if("MAP"===i.preloadHints[e].type)return t;i.duration=e.targetDuration,i.preload=!0,t.push(i)}return t},Ml=(e,t)=>e===t||e.segments&&t.segments&&e.segments.length===t.segments.length&&e.endList===t.endList&&e.mediaSequence===t.mediaSequence&&e.preloadSegment===t.preloadSegment,Rl=(e,t,i=Ml)=>{const s=Go(e,{}),r=s.playlists[t.id];if(!r)return null;if(i(r,t))return null;t.segments=Ol(t);const n=Go(r,t);if(n.preloadSegment&&!t.preloadSegment&&delete n.preloadSegment,r.segments){if(t.skip){t.segments=t.segments||[];for(let e=0;e<t.skip.skippedSegments;e++)t.segments.unshift({skipped:!0})}n.segments=((e,t,i)=>{const s=e.slice(),r=t.slice();i=i||0;const n=[];let a;for(let e=0;e<r.length;e++){const t=s[e+i],o=r[e];t?(a=t.map||a,n.push(Pl(t,o))):(a&&!o.map&&(o.map=a),n.push(o))}return n})(r.segments,t.segments,t.mediaSequence-r.mediaSequence)}n.segments.forEach(e=>{Ll(e,n.resolvedUri)});for(let e=0;e<s.playlists.length;e++)s.playlists[e].id===t.id&&(s.playlists[e]=n);return s.playlists[t.id]=n,s.playlists[t.uri]=n,kl(e,(e,i,s,r)=>{if(e.playlists)for(let i=0;i<e.playlists.length;i++)t.id===e.playlists[i].id&&(e.playlists[i]=n)}),s},Nl=(e,t)=>{const i=e.segments||[],s=i[i.length-1],r=s&&s.parts&&s.parts[s.parts.length-1],n=r&&r.duration||s&&s.duration;return t&&n?1e3*n:500*(e.partTargetDuration||e.targetDuration||10)},Ul=(e,t,i)=>{if(!e)return;const s=[];return e.forEach(e=>{if(!e.attributes)return;const{BANDWIDTH:t,RESOLUTION:i,CODECS:r}=e.attributes;s.push({id:e.id,bandwidth:t,resolution:i,codecs:r})}),{type:t,isLive:i,renditions:s}};class Bl extends Dl{constructor(e,t,i={}){if(super(),!e)throw new Error("A non-empty playlist URL or object is required");this.logger_=Wo("PlaylistLoader");const{withCredentials:s=!1}=i;this.src=e,this.vhs_=t,this.withCredentials=s,this.addDateRangesToTextTrack_=i.addDateRangesToTextTrack;const r=t.options_;this.customTagParsers=r&&r.customTagParsers||[],this.customTagMappers=r&&r.customTagMappers||[],this.llhls=r&&r.llhls,this.dateRangesStorage_=new xl,this.state="HAVE_NOTHING",this.handleMediaupdatetimeout_=this.handleMediaupdatetimeout_.bind(this),this.on("mediaupdatetimeout",this.handleMediaupdatetimeout_),this.on("loadedplaylist",this.handleLoadedPlaylist_.bind(this))}handleLoadedPlaylist_(){const e=this.media();if(!e)return;this.dateRangesStorage_.setOffset(e.segments),this.dateRangesStorage_.setPendingDateRanges(e.dateRanges);const t=this.dateRangesStorage_.getDateRangesToProcess();t.length&&this.addDateRangesToTextTrack_&&this.addDateRangesToTextTrack_(t)}handleMediaupdatetimeout_(){if("HAVE_METADATA"!==this.state)return;const e=this.media();let t=Ho(this.main.uri,e.uri);this.llhls&&(t=((e,t)=>{if(t.endList||!t.serverControl)return e;const i={};if(t.serverControl.canBlockReload){const{preloadSegment:e}=t;let s=t.mediaSequence+t.segments.length;if(e){const r=e.parts||[],n=ol(t)-1;n>-1&&n!==r.length-1&&(i._HLS_part=n),(n>-1||r.length)&&s--}i._HLS_msn=s}if(t.serverControl&&t.serverControl.canSkipUntil&&(i._HLS_skip=t.serverControl.canSkipDateranges?"v2":"YES"),Object.keys(i).length){const t=new p.URL(e);["_HLS_skip","_HLS_msn","_HLS_part"].forEach(function(e){i.hasOwnProperty(e)&&t.searchParams.set(e,i[e])}),e=t.toString()}return e})(t,e)),this.state="HAVE_CURRENT_METADATA",this.request=this.vhs_.xhr({uri:t,withCredentials:this.withCredentials,requestType:"hls-playlist"},(e,t)=>{if(this.request)return e?this.playlistRequestError(this.request,this.media(),"HAVE_METADATA"):void this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})})}playlistRequestError(e,t,i){const{uri:s,id:r}=t;this.request=null,i&&(this.state=i),this.error={playlist:this.main.playlists[r],status:e.status,message:`HLS playlist request error at URL: ${s}.`,responseText:e.responseText,code:e.status>=500?4:2,metadata:Al({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{return(({onwarn:e,oninfo:t,manifestString:i,customTagParsers:s=[],customTagMappers:r=[],llhls:n})=>{const a=new ae;e&&a.on("warn",e),t&&a.on("info",t),s.forEach(e=>a.addParser(e)),r.forEach(e=>a.addTagMapper(e)),a.push(i),a.end();const o=a.manifest;if(n||(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach(function(e){o.hasOwnProperty(e)&&delete o[e]}),o.segments&&o.segments.forEach(function(e){["parts","preloadHints"].forEach(function(t){e.hasOwnProperty(t)&&delete e[t]})})),!o.targetDuration){let t=10;o.segments&&o.segments.length&&(t=o.segments.reduce((e,t)=>Math.max(e,t.duration),0)),e&&e({message:`manifest has no targetDuration defaulting to ${t}`}),o.targetDuration=t}const l=al(o);if(l.length&&!o.partTargetDuration){const t=l.reduce((e,t)=>Math.max(e,t.duration),0);e&&(e({message:`manifest has no partTargetDuration defaulting to ${t}`}),Sl.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),o.partTargetDuration=t}return o})({onwarn:({message:t})=>this.logger_(`m3u8-parser warn for ${e}: ${t}`),oninfo:({message:t})=>this.logger_(`m3u8-parser info for ${e}: ${t}`),manifestString:t,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,llhls:this.llhls})}catch(e){this.error=e,this.error.metadata={errorType:Fo.Error.StreamingHlsPlaylistParserError,error:e}}}haveMetadata({playlistString:e,playlistObject:t,url:i,id:s}){this.request=null,this.state="HAVE_METADATA";const r={playlistInfo:{type:"media",uri:i}};this.trigger({type:"playlistparsestart",metadata:r});const n=t||this.parseManifest_({url:i,manifestString:e});n.lastRequest=Date.now(),Cl({playlist:n,uri:i,id:s});const a=Rl(this.main,n);this.targetDuration=n.partTargetDuration||n.targetDuration,this.pendingMedia_=null,a?(this.main=a,this.media_=this.main.playlists[s]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(Nl(this.media(),!!a)),r.parsedPlaylist=Ul(this.main.playlists,r.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:r}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),p.clearTimeout(this.mediaUpdateTimeout),p.clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new xl,this.off()}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e,t){if(!e)return this.media_;if("HAVE_NOTHING"===this.state)throw new Error("Cannot switch media playlist from "+this.state);if("string"==typeof e){if(!this.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.main.playlists[e]}if(p.clearTimeout(this.finalRenditionTimeout),t){const t=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;return void(this.finalRenditionTimeout=p.setTimeout(this.media.bind(this,e,!1),t))}const i=this.state,s=!this.media_||e.id!==this.media_.id,r=this.main.playlists[e.id];if(r&&r.endList||e.endList&&e.segments.length)return this.request&&(this.request.onreadystatechange=null,this.request.abort(),this.request=null),this.state="HAVE_METADATA",this.media_=e,void(s&&(this.trigger("mediachanging"),"HAVE_MAIN_MANIFEST"===i?this.trigger("loadedmetadata"):this.trigger("mediachange")));if(this.updateMediaUpdateTimeout_(Nl(e,!0)),!s)return;if(this.state="SWITCHING_MEDIA",this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.pendingMedia_=e;const n={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:n}),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},(t,s)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=zo(e.resolvedUri,s),t)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:n}),this.haveMetadata({playlistString:s.responseText,url:e.uri,id:e.id}),"HAVE_MAIN_MANIFEST"===i?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}pause(){this.mediaUpdateTimeout&&(p.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.stopRequest(),"HAVE_NOTHING"===this.state&&(this.started=!1),"SWITCHING_MEDIA"===this.state?this.media_?this.state="HAVE_METADATA":this.state="HAVE_MAIN_MANIFEST":"HAVE_CURRENT_METADATA"===this.state&&(this.state="HAVE_METADATA")}load(e){this.mediaUpdateTimeout&&(p.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);const t=this.media();if(e){const e=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;return void(this.mediaUpdateTimeout=p.setTimeout(()=>{this.mediaUpdateTimeout=null,this.load()},e))}this.started?t&&!t.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist"):this.start()}updateMediaUpdateTimeout_(e){this.mediaUpdateTimeout&&(p.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.media()&&!this.media().endList&&(this.mediaUpdateTimeout=p.setTimeout(()=>{this.mediaUpdateTimeout=null,this.trigger("mediaupdatetimeout"),this.updateMediaUpdateTimeout_(e)},e))}start(){if(this.started=!0,"object"==typeof this.src)return this.src.uri||(this.src.uri=p.location.href),this.src.resolvedUri=this.src.uri,void setTimeout(()=>{this.setupInitialPlaylist(this.src)},0);const e={playlistInfo:{type:"multivariant",uri:this.src}};this.trigger({type:"playlistrequeststart",metadata:e}),this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials,requestType:"hls-playlist"},(t,i)=>{if(!this.request)return;if(this.request=null,t)return this.error={status:i.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:i.responseText,code:2,metadata:Al({requestType:i.requestType,request:i,error:t})},"HAVE_NOTHING"===this.state&&(this.started=!1),this.trigger("error");this.trigger({type:"playlistrequestcomplete",metadata:e}),this.src=zo(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});const s=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=Ul(s.playlists,e.playlistInfo.type,!1),this.trigger({type:"playlistparsecomplete",metadata:e}),this.setupInitialPlaylist(s)})}srcUri(){return"string"==typeof this.src?this.src:this.src.uri}setupInitialPlaylist(e){if(this.state="HAVE_MAIN_MANIFEST",e.playlists)return this.main=e,Il(this.main,this.srcUri()),e.playlists.forEach(e=>{e.segments=Ol(e),e.segments.forEach(t=>{Ll(t,e.resolvedUri)})}),this.trigger("loadedplaylist"),void(this.request||this.media(this.main.playlists[0]));const t=this.srcUri()||p.location.href;this.main=((e,t)=>{const i=El(0,t),s={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:p.location.href,resolvedUri:p.location.href,playlists:[{uri:t,id:i,resolvedUri:t,attributes:{}}]};return s.playlists[i]=s.playlists[0],s.playlists[t]=s.playlists[0],s})(0,t),this.haveMetadata({playlistObject:e,url:t,id:this.main.playlists[0].id}),this.trigger("loadedmetadata")}updateOrDeleteClone(e,t){const i=this.main,s=e.ID;let r=i.playlists.length;for(;r--;){const n=i.playlists[r];if(n.attributes["PATHWAY-ID"]===s){const a=n.resolvedUri,o=n.id;if(t){const t=this.createCloneURI_(n.resolvedUri,e),a=El(s,t),o=this.createCloneAttributes_(s,n.attributes),l=this.createClonePlaylist_(n,a,e,o);i.playlists[r]=l,i.playlists[a]=l,i.playlists[t]=l}else i.playlists.splice(r,1);delete i.playlists[o],delete i.playlists[a]}}this.updateOrDeleteCloneMedia(e,t)}updateOrDeleteCloneMedia(e,t){const i=this.main,s=e.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{if(i.mediaGroups[e]&&i.mediaGroups[e][s])for(const t in i.mediaGroups[e])if(t===s){for(const s in i.mediaGroups[e][t]){i.mediaGroups[e][t][s].playlists.forEach((e,t)=>{const s=i.playlists[e.id],r=s.id,n=s.resolvedUri;delete i.playlists[r],delete i.playlists[n]})}delete i.mediaGroups[e][t]}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){const i=this.main,s=i.playlists.length,r=this.createCloneURI_(t.resolvedUri,e),n=El(e.ID,r),a=this.createCloneAttributes_(e.ID,t.attributes),o=this.createClonePlaylist_(t,n,e,a);i.playlists[s]=o,i.playlists[n]=o,i.playlists[r]=o,this.createClonedMediaGroups_(e)}createClonedMediaGroups_(e){const t=e.ID,i=e["BASE-ID"],s=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(s.mediaGroups[r]&&!s.mediaGroups[r][t])for(const n in s.mediaGroups[r])if(n===i){s.mediaGroups[r][t]={};for(const i in s.mediaGroups[r][n]){const a=s.mediaGroups[r][n][i];s.mediaGroups[r][t][i]=G({},a);const o=s.mediaGroups[r][t][i],l=this.createCloneURI_(a.resolvedUri,e);o.resolvedUri=l,o.uri=l,o.playlists=[],a.playlists.forEach((n,a)=>{const l=s.playlists[n.id],d=wl(r,t,i),u=El(t,d);if(l&&!s.playlists[u]){const t=this.createClonePlaylist_(l,u,e),i=t.resolvedUri;s.playlists[u]=t,s.playlists[i]=t}o.playlists[a]=this.createClonePlaylist_(n,u,e)})}}})}createClonePlaylist_(e,t,i,s){const r=this.createCloneURI_(e.resolvedUri,i),n={resolvedUri:r,uri:r,id:t};return e.segments&&(n.segments=[]),s&&(n.attributes=s),Go(e,n)}createCloneURI_(e,t){const i=new URL(e);i.hostname=t["URI-REPLACEMENT"].HOST;const s=t["URI-REPLACEMENT"].PARAMS;for(const e of Object.keys(s))i.searchParams.set(e,s[e]);return i.href}createCloneAttributes_(e,t){const i={"PATHWAY-ID":e};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(s=>{t[s]&&(i[s]=e)}),i}getKeyIdSet(e){if(e.contentProtection){const t=new Set;for(const i in e.contentProtection){const s=e.contentProtection[i].attributes.keyId;s&&t.add(s.toLowerCase())}return t}}}const Fl=function(e,t,i,s){const r="arraybuffer"===e.responseType?e.response:e.responseText;!t&&r&&(e.responseTime=Date.now(),e.roundTripTime=e.responseTime-e.requestTime,e.bytesReceived=r.byteLength||r.length,e.bandwidth||(e.bandwidth=Math.floor(e.bytesReceived/e.roundTripTime*8*1e3))),i.headers&&(e.responseHeaders=i.headers),t&&"ETIMEDOUT"===t.code&&(e.timedout=!0),t||e.aborted||200===i.statusCode||206===i.statusCode||0===i.statusCode||(t=new Error("XHR Failed with a response of: "+(e&&(r||e.responseText)))),s(t,e)},ql=function(){const e=function e(t,i){t=Go({timeout:45e3},t);const s=e.beforeRequest||Fo.Vhs.xhr.beforeRequest,r=e._requestCallbackSet||Fo.Vhs.xhr._requestCallbackSet||new Set,n=e._responseCallbackSet||Fo.Vhs.xhr._responseCallbackSet;s&&"function"==typeof s&&(Fo.log.warn("beforeRequest is deprecated, use onRequest instead."),r.add(s));const a=!0===Fo.Vhs.xhr.original?Fo.xhr:Fo.Vhs.xhr,o=((e,t)=>{if(!e||!e.size)return;let i=t;return e.forEach(e=>{i=e(i)}),i})(r,t);r.delete(s);const l=a(o||t,function(e,t){return((e,t,i,s)=>{e&&e.size&&e.forEach(e=>{e(t,i,s)})})(n,l,e,t),Fl(l,e,t,i)}),d=l.abort;return l.abort=function(){return l.aborted=!0,d.apply(l,arguments)},l.uri=t.uri,l.requestType=t.requestType,l.requestTime=Date.now(),l};return e.original=!0,e},jl=function(e){const t={};return e.byterange&&(t.Range=function(e){let t;const i=e.offset;return t="bigint"==typeof e.offset||"bigint"==typeof e.length?p.BigInt(e.offset)+p.BigInt(e.length)-p.BigInt(1):e.offset+e.length-1,"bytes="+i+"-"+t}(e.byterange)),t},Vl=function(e,t){return e.start(t)+"-"+e.end(t)},$l=function(e,t){const i=e.toString(16);return"00".substring(0,2-i.length)+i+(t%2?" ":"")},Hl=function(e){return e>=32&&e<126?String.fromCharCode(e):"."},zl=function(e){const t={};return Object.keys(e).forEach(i=>{const s=e[i];Se(s)?t[i]={bytes:s.buffer,byteOffset:s.byteOffset,byteLength:s.byteLength}:t[i]=s}),t},Wl=function(e){const t=e.byterange||{length:1/0,offset:0};return[t.length,t.offset,e.resolvedUri].join(",")},Gl=function(e){return e.resolvedUri},Xl=e=>{const t=Array.prototype.slice.call(e),i=16;let s,r,n="";for(let e=0;e<t.length/i;e++)s=t.slice(e*i,e*i+i).map($l).join(""),r=t.slice(e*i,e*i+i).map(Hl).join(""),n+=s+" "+r+"\n";return n};var Kl=Object.freeze({__proto__:null,createTransferableMessage:zl,initSegmentId:Wl,segmentKeyId:Gl,hexDump:Xl,tagDump:({bytes:e})=>Xl(e),textRanges:e=>{let t,i="";for(t=0;t<e.length;t++)i+=Vl(e,t)+" ";return i}});const Yl=({playlist:e,time:t,callback:i})=>{if(!i)throw new Error("getProgramTime: callback must be provided");if(!e||void 0===t)return i({message:"getProgramTime: playlist and time must be provided"});const s=((e,t)=>{if(!t||!t.segments||0===t.segments.length)return null;let i,s=0;for(let r=0;r<t.segments.length&&(i=t.segments[r],s=i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationEnd:s+i.duration,!(e<=s));r++);const r=t.segments[t.segments.length-1];if(r.videoTimingInfo&&r.videoTimingInfo.transmuxedPresentationEnd<e)return null;if(e>s){if(e>s+.25*r.duration)return null;i=r}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:s-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}})(t,e);if(!s)return i({message:"valid programTime was not found"});if("estimate"===s.type)return i({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:s.estimatedStart});const r={mediaSeconds:t},n=((e,t)=>{if(!t.dateTimeObject)return null;const i=t.videoTimingInfo.transmuxerPrependedSeconds,s=e-(t.videoTimingInfo.transmuxedPresentationStart+i);return new Date(t.dateTimeObject.getTime()+1e3*s)})(t,s.segment);return n&&(r.programDateTime=n.toISOString()),i(null,r)},Ql=({programTime:e,playlist:t,retryCount:i=2,seekTo:s,pauseAfterSeek:r=!0,tech:n,callback:a})=>{if(!a)throw new Error("seekToProgramTime: callback must be provided");if(void 0===e||!t||!s)return a({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!t.endList&&!n.hasStarted_)return a({message:"player must be playing a live stream to start buffering"});if(!(e=>{if(!e.segments||0===e.segments.length)return!1;for(let t=0;t<e.segments.length;t++)if(!e.segments[t].dateTimeObject)return!1;return!0})(t))return a({message:"programDateTime tags must be provided in the manifest "+t.resolvedUri});const o=((e,t)=>{let i;try{i=new Date(e)}catch(e){return null}if(!t||!t.segments||0===t.segments.length)return null;let s=t.segments[0];if(i<new Date(s.dateTimeObject))return null;for(let e=0;e<t.segments.length-1&&(s=t.segments[e],!(i<new Date(t.segments[e+1].dateTimeObject)));e++);const r=t.segments[t.segments.length-1],n=r.dateTimeObject,a=r.videoTimingInfo?(o=r.videoTimingInfo).transmuxedPresentationEnd-o.transmuxedPresentationStart-o.transmuxerPrependedSeconds:r.duration+.25*r.duration;var o;return i>new Date(n.getTime()+1e3*a)?null:(i>new Date(n)&&(s=r),{segment:s,estimatedStart:s.videoTimingInfo?s.videoTimingInfo.transmuxedPresentationStart:Tl.duration(t,t.mediaSequence+t.segments.indexOf(s)),type:s.videoTimingInfo?"accurate":"estimate"})})(e,t);if(!o)return a({message:`${e} was not found in the stream`});const l=o.segment,d=((e,t)=>{let i,s;try{i=new Date(e),s=new Date(t)}catch(e){}const r=i.getTime();return(s.getTime()-r)/1e3})(l.dateTimeObject,e);if("estimate"===o.type)return 0===i?a({message:`${e} is not buffered yet. Try again`}):(s(o.estimatedStart+d),void n.one("seeked",()=>{Ql({programTime:e,playlist:t,retryCount:i-1,seekTo:s,pauseAfterSeek:r,tech:n,callback:a})}));const u=l.start+d;n.one("seeked",()=>a(null,n.currentTime())),r&&n.pause(),s(u)},Jl=(e,t)=>{if(4===e.readyState)return t()},Zl=(e,t,i,s)=>{let r,n=[],a=!1;const o=function(e,t,s,r){return t.abort(),a=!0,i(e,t,s,r)},l=function(e,t){if(a)return;if(e)return e.metadata=Al({requestType:s,request:t,error:e}),o(e,t,"",n);const i=t.responseText.substring(n&&n.byteLength||0,t.responseText.length);if(n=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(t=t.filter(function(e){return e&&(e.byteLength||e.length)&&"string"!=typeof e}),t.length<=1)return Ee(t[0]);var s=t.reduce(function(e,t,i){return e+(t.byteLength||t.length)},0),r=new Uint8Array(s),n=0;return t.forEach(function(e){e=Ee(e),r.set(e,n),n+=e.byteLength}),r}(n,De(i,!0)),r=r||ti(n),n.length<10||r&&n.length<r+2)return Jl(t,()=>o(e,t,"",n));const l=Ti(n);return"ts"===l&&n.length<188||!l&&n.length<376?Jl(t,()=>o(e,t,"",n)):o(null,t,l,n)},d={uri:e,beforeSend(e){e.overrideMimeType("text/plain; charset=x-user-defined"),e.addEventListener("progress",function({total:t,loaded:i}){return Fl(e,null,{statusCode:e.status},l)})}},u=t(d,function(e,t){return Fl(u,e,t,l)});return u},{EventTarget:ed}=Fo,td=function(e,t){if(!Ml(e,t))return!1;if(e.sidx&&t.sidx&&(e.sidx.offset!==t.sidx.offset||e.sidx.length!==t.sidx.length))return!1;if(!e.sidx&&t.sidx||e.sidx&&!t.sidx)return!1;if(e.segments&&!t.segments||!e.segments&&t.segments)return!1;if(!e.segments&&!t.segments)return!0;for(let i=0;i<e.segments.length;i++){const s=e.segments[i],r=t.segments[i];if(s.uri!==r.uri)return!1;if(!s.byterange&&!r.byterange)continue;const n=s.byterange,a=r.byterange;if(n&&!a||!n&&a)return!1;if(n.offset!==a.offset||n.length!==a.length)return!1}return!0},id=(e,t,i,s)=>`placeholder-uri-${e}-${t}-${s.attributes.NAME||i}`,sd=(e,t,i)=>{let s=!0,r=Go(e,{duration:t.duration,minimumUpdatePeriod:t.minimumUpdatePeriod,timelineStarts:t.timelineStarts});for(let e=0;e<t.playlists.length;e++){const n=t.playlists[e];if(n.sidx){const e=yt(n.sidx);i&&i[e]&&i[e].sidx&&ut(n,i[e].sidx,n.sidx.resolvedUri)}const a=Rl(r,n,td);a&&(r=a,s=!1)}return kl(t,(e,t,i,n)=>{if(e.playlists&&e.playlists.length){const a=e.playlists[0].id,o=Rl(r,e.playlists[0],td);o&&(r=o,n in r.mediaGroups[t][i]||(r.mediaGroups[t][i][n]=e),r.mediaGroups[t][i][n].playlists[0]=r.playlists[a],s=!1)}}),((e,t)=>{kl(e,(i,s,r,n)=>{t.mediaGroups[s][r]&&n in t.mediaGroups[s][r]||delete e.mediaGroups[s][r][n]})})(r,t),t.minimumUpdatePeriod!==e.minimumUpdatePeriod&&(s=!1),s?null:r},rd=(e,t)=>(Boolean(!e.map&&!t.map)||Boolean(e.map&&t.map&&e.map.byterange.offset===t.map.byterange.offset&&e.map.byterange.length===t.map.byterange.length))&&e.uri===t.uri&&e.byterange.offset===t.byterange.offset&&e.byterange.length===t.byterange.length,nd=(e,t)=>{const i={};for(const s in e){const r=e[s].sidx;if(r){const e=yt(r);if(!t[e])break;const s=t[e].sidxInfo;rd(s,r)&&(i[e]=t[e])}}return i};class ad extends ed{constructor(e,t,i={},s){super(),this.isPaused_=!0,this.mainPlaylistLoader_=s||this,s||(this.isMain_=!0);const{withCredentials:r=!1}=i;if(this.vhs_=t,this.withCredentials=r,this.addMetadataToTextTrack=i.addMetadataToTextTrack,!e)throw new Error("A non-empty playlist URL or object is required");this.on("minimumUpdatePeriod",()=>{this.refreshXml_()}),this.on("mediaupdatetimeout",()=>{this.refreshMedia_(this.media().id)}),this.state="HAVE_NOTHING",this.loadedPlaylists_={},this.logger_=Wo("DashPlaylistLoader"),this.isMain_?(this.mainPlaylistLoader_.srcUrl=e,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=e}get isPaused(){return this.isPaused_}requestErrored_(e,t,i){return!this.request||(this.request=null,e?(this.error="object"!=typeof e||e instanceof Error?{status:t.status,message:"DASH request error at URL: "+t.uri,response:t.response,code:2,metadata:e.metadata}:e,i&&(this.state=i),this.trigger("error"),!0):void 0)}addSidxSegments_(e,t,i){const s=e.sidx&&yt(e.sidx);if(!e.sidx||!s||this.mainPlaylistLoader_.sidxMapping_[s])return p.clearTimeout(this.mediaRequest_),void(this.mediaRequest_=p.setTimeout(()=>i(!1),0));const r=zo(e.sidx.resolvedUri),n=(r,n)=>{if(this.requestErrored_(r,n,t))return;const a=this.mainPlaylistLoader_.sidxMapping_,{requestType:o}=n;let l;try{l=Zt(Ee(n.response).subarray(8))}catch(e){return e.metadata=Al({requestType:o,request:n,parseFailure:!0}),void this.requestErrored_(e,n,t)}return a[s]={sidxInfo:e.sidx,sidx:l},ut(e,l,e.sidx.resolvedUri),i(!0)};this.request=Zl(r,this.vhs_.xhr,(t,i,s,a)=>{if(t)return n(t,i);if(!s||"mp4"!==s){const t=s||"unknown";return n({status:i.status,message:`Unsupported ${t} container type for sidx segment at URL: ${r}`,response:"",playlist:e,internal:!0,playlistExclusionDuration:1/0,code:2},i)}const{offset:o,length:l}=e.sidx.byterange;if(a.length>=l+o)return n(t,{response:a.subarray(o,o+l),status:i.status,uri:i.uri});this.request=this.vhs_.xhr({uri:r,responseType:"arraybuffer",requestType:"dash-sidx",headers:jl({byterange:e.sidx.byterange})},n)},"dash-sidx")}dispose(){this.isPaused_=!0,this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},p.clearTimeout(this.minimumUpdatePeriodTimeout_),p.clearTimeout(this.mediaRequest_),p.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){const e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e){if(!e)return this.media_;if("HAVE_NOTHING"===this.state)throw new Error("Cannot switch media playlist from "+this.state);const t=this.state;if("string"==typeof e){if(!this.mainPlaylistLoader_.main.playlists[e])throw new Error("Unknown playlist URI: "+e);e=this.mainPlaylistLoader_.main.playlists[e]}const i=!this.media_||e.id!==this.media_.id;if(i&&this.loadedPlaylists_[e.id]&&this.loadedPlaylists_[e.id].endList)return this.state="HAVE_METADATA",this.media_=e,void(i&&(this.trigger("mediachanging"),this.trigger("mediachange")));i&&(this.media_&&this.trigger("mediachanging"),this.addSidxSegments_(e,t,i=>{this.haveMetadata({startingState:t,playlist:e})}))}haveMetadata({startingState:e,playlist:t}){this.state="HAVE_METADATA",this.loadedPlaylists_[t.id]=t,p.clearTimeout(this.mediaRequest_),this.mediaRequest_=null,this.refreshMedia_(t.id),"HAVE_MAIN_MANIFEST"===e?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.isPaused_=!0,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),p.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(p.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),"HAVE_NOTHING"===this.state&&(this.started=!1)}load(e){this.isPaused_=!1,p.clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;const t=this.media();if(e){const e=t?t.targetDuration/2*1e3:5e3;return void(this.mediaUpdateTimeout=p.setTimeout(()=>this.load(),e))}this.started?t&&!t.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist"):this.start()}start(){if(this.started=!0,!this.isMain_)return p.clearTimeout(this.mediaRequest_),void(this.mediaRequest_=p.setTimeout(()=>this.haveMain_(),0));this.requestMain_((e,t)=>{this.haveMain_(),this.hasPendingRequest()||this.media_||this.media(this.mainPlaylistLoader_.main.playlists[0])})}requestMain_(e){const t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestrequeststart",metadata:t}),this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,requestType:"dash-manifest"},(i,s)=>{if(i){const{requestType:e}=s;i.metadata=Al({requestType:e,request:s,error:i})}if(this.requestErrored_(i,s))return void("HAVE_NOTHING"===this.state&&(this.started=!1));this.trigger({type:"manifestrequestcomplete",metadata:t});const r=s.responseText!==this.mainPlaylistLoader_.mainXml_;return this.mainPlaylistLoader_.mainXml_=s.responseText,s.responseHeaders&&s.responseHeaders.date?this.mainLoaded_=Date.parse(s.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=zo(this.mainPlaylistLoader_.srcUrl,s),r?(this.handleMain_(),void this.syncClientServerClock_(()=>e(s,r))):e(s,r)})}syncClientServerClock_(e){const t=Xt(this.mainPlaylistLoader_.mainXml_);return null===t?(this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()):"DIRECT"===t.method?(this.mainPlaylistLoader_.clientOffset_=t.value-Date.now(),e()):void(this.request=this.vhs_.xhr({uri:Ho(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials,requestType:"dash-clock-sync"},(i,s)=>{if(!this.request)return;if(i){const{requestType:t}=s;return this.error.metadata=Al({requestType:t,request:s,error:i}),this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()}let r;r="HEAD"===t.method?s.responseHeaders&&s.responseHeaders.date?Date.parse(s.responseHeaders.date):this.mainLoaded_:Date.parse(s.responseText),this.mainPlaylistLoader_.clientOffset_=r-Date.now(),e()}))}haveMain_(){this.state="HAVE_MAIN_MANIFEST",this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){p.clearTimeout(this.mediaRequest_),this.mediaRequest_=null;const e=this.mainPlaylistLoader_.main,t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};let i;this.trigger({type:"manifestparsestart",metadata:t});try{i=(({mainXml:e,srcUrl:t,clientOffset:i,sidxMapping:s,previousManifest:r})=>{const n=Gt(e,{manifestUri:t,clientOffset:i,sidxMapping:s,previousManifest:r});return Il(n,t,id),n})({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:e})}catch(e){this.error=e,this.error.metadata={errorType:Fo.Error.StreamingDashManifestParserError,error:e},this.trigger("error")}e&&(i=sd(e,i,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=i||e;const s=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];if(s&&s!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=s),(!e||i&&i.minimumUpdatePeriod!==e.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(i),i){const{duration:e,endList:s}=i,r=[];i.playlists.forEach(e=>{r.push({id:e.id,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS})});const n={duration:e,isLive:!s,renditions:r};t.parsedManifest=n,this.trigger({type:"manifestparsecomplete",metadata:t})}return Boolean(i)}updateMinimumUpdatePeriodTimeout_(){const e=this.mainPlaylistLoader_;e.createMupOnMedia_&&(e.off("loadedmetadata",e.createMupOnMedia_),e.createMupOnMedia_=null),e.minimumUpdatePeriodTimeout_&&(p.clearTimeout(e.minimumUpdatePeriodTimeout_),e.minimumUpdatePeriodTimeout_=null);let t=e.main&&e.main.minimumUpdatePeriod;0===t&&(e.media()?t=1e3*e.media().targetDuration:(e.createMupOnMedia_=e.updateMinimumUpdatePeriodTimeout_,e.one("loadedmetadata",e.createMupOnMedia_))),"number"!=typeof t||t<=0?t<0&&this.logger_(`found invalid minimumUpdatePeriod of ${t}, not setting a timeout`):this.createMUPTimeout_(t)}createMUPTimeout_(e){const t=this.mainPlaylistLoader_;t.minimumUpdatePeriodTimeout_=p.setTimeout(()=>{t.minimumUpdatePeriodTimeout_=null,t.trigger("minimumUpdatePeriod"),t.createMUPTimeout_(e)},e)}refreshXml_(){this.requestMain_((e,t)=>{t&&(this.media_&&(this.media_=this.mainPlaylistLoader_.main.playlists[this.media_.id]),this.mainPlaylistLoader_.sidxMapping_=((e,t)=>{let i=nd(e.playlists,t);return kl(e,(e,s,r,n)=>{if(e.playlists&&e.playlists.length){const s=e.playlists;i=Go(i,nd(s,t))}}),i})(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.sidxMapping_),this.addSidxSegments_(this.media(),this.state,e=>{this.refreshMedia_(this.media().id)}))})}refreshMedia_(e){if(!e)throw new Error("refreshMedia_ must take a media id");this.media_&&this.isMain_&&this.handleMain_();const t=this.mainPlaylistLoader_.main.playlists,i=!this.media_||this.media_!==t[e];if(i?this.media_=t[e]:this.trigger("playlistunchanged"),!this.mediaUpdateTimeout){const e=()=>{this.media().endList||(this.mediaUpdateTimeout=p.setTimeout(()=>{this.trigger("mediaupdatetimeout"),e()},Nl(this.media(),Boolean(i))))};e()}this.trigger("loadedplaylist")}addEventStreamToMetadataTrack_(e){if(e&&this.mainPlaylistLoader_.main.eventStream){const e=this.mainPlaylistLoader_.main.eventStream.map(e=>({cueTime:e.start,frames:[{data:e.messageData}]}));this.addMetadataToTextTrack("EventStream",e,this.mainPlaylistLoader_.main.duration)}}getKeyIdSet(e){if(e.contentProtection){const t=new Set;for(const i in e.contentProtection){const s=e.contentProtection[i].attributes["cenc:default_KID"];s&&t.add(s.replace(/-/g,"").toLowerCase())}return t}}}var od={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 ld=function(e){return e.on=e.addEventListener,e.off=e.removeEventListener,e},dd=function(e){return function(){const t=function(e){try{return URL.createObjectURL(new Blob([e],{type:"application/javascript"}))}catch(t){const i=new BlobBuilder;return i.append(e),URL.createObjectURL(i.getBlob())}}(e),i=ld(new Worker(t));i.objURL=t;const s=i.terminate;return i.on=i.addEventListener,i.off=i.removeEventListener,i.terminate=function(){return URL.revokeObjectURL(t),s.call(this)},i}},ud=function(e){return`var browserWorkerPolyFill = ${ld.toString()};\nbrowserWorkerPolyFill(self);\n`+e},cd=function(e){return e.toString().replace(/^function.+?{/,"").slice(0,-1)},hd=ud(cd(function(){var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=function(){this.init=function(){var e={};this.on=function(t,i){e[t]||(e[t]=[]),e[t]=e[t].concat(i)},this.off=function(t,i){var s;return!!e[t]&&(s=e[t].indexOf(i),e[t]=e[t].slice(),e[t].splice(s,1),s>-1)},this.trigger=function(t){var i,s,r,n;if(i=e[t])if(2===arguments.length)for(r=i.length,s=0;s<r;++s)i[s].call(this,arguments[1]);else{for(n=[],s=arguments.length,s=1;s<arguments.length;++s)n.push(arguments[s]);for(r=i.length,s=0;s<r;++s)i[s].apply(this,n)}},this.dispose=function(){e={}}}};t.prototype.pipe=function(e){return this.on("data",function(t){e.push(t)}),this.on("done",function(t){e.flush(t)}),this.on("partialdone",function(t){e.partialFlush(t)}),this.on("endedtimeline",function(t){e.endTimeline(t)}),this.on("reset",function(t){e.reset(t)}),e},t.prototype.push=function(e){this.trigger("data",e)},t.prototype.flush=function(e){this.trigger("done",e)},t.prototype.partialFlush=function(e){this.trigger("partialdone",e)},t.prototype.endTimeline=function(e){this.trigger("endedtimeline",e)},t.prototype.reset=function(e){this.trigger("reset",e)};var i,s,r,n,a,o,l,d,u,c,h,p,m,g,f,y,_,b,v,T,S,E,w,k,C,I,x,A,D,P,L,O,M,R,N,U,B,F,q,j,V=t,$=Math.pow(2,32),H={getUint64:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength);return i.getBigUint64?(t=i.getBigUint64(0))<Number.MAX_SAFE_INTEGER?Number(t):t:i.getUint32(0)*$+i.getUint32(4)},MAX_UINT32:$},z=H.MAX_UINT32;!function(){var e;if(E={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],pasp:[],sdtp:[],smhd:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],styp:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[]},"undefined"!=typeof Uint8Array){for(e in E)E.hasOwnProperty(e)&&(E[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);w=new Uint8Array(["i".charCodeAt(0),"s".charCodeAt(0),"o".charCodeAt(0),"m".charCodeAt(0)]),C=new Uint8Array(["a".charCodeAt(0),"v".charCodeAt(0),"c".charCodeAt(0),"1".charCodeAt(0)]),k=new Uint8Array([0,0,0,1]),I=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),x=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),A={video:I,audio:x},L=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),P=new Uint8Array([0,0,0,0,0,0,0,0]),O=new Uint8Array([0,0,0,0,0,0,0,0]),M=O,R=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),N=O,D=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])}}(),i=function(e){var t,i,s=[],r=0;for(t=1;t<arguments.length;t++)s.push(arguments[t]);for(t=s.length;t--;)r+=s[t].byteLength;for(i=new Uint8Array(r+8),new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,i.byteLength),i.set(e,4),t=0,r=8;t<s.length;t++)i.set(s[t],r),r+=s[t].byteLength;return i},s=function(){return i(E.dinf,i(E.dref,L))},r=function(e){return i(E.esds,new Uint8Array([0,0,0,0,3,25,0,0,0,4,17,64,21,0,6,0,0,0,218,192,0,0,218,192,5,2,e.audioobjecttype<<3|e.samplingfrequencyindex>>>1,e.samplingfrequencyindex<<7|e.channelcount<<3,6,1,2]))},f=function(e){return i(E.hdlr,A[e])},g=function(e){var t=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,e.duration>>>24&255,e.duration>>>16&255,e.duration>>>8&255,255&e.duration,85,196,0,0]);return e.samplerate&&(t[12]=e.samplerate>>>24&255,t[13]=e.samplerate>>>16&255,t[14]=e.samplerate>>>8&255,t[15]=255&e.samplerate),i(E.mdhd,t)},m=function(e){return i(E.mdia,g(e),f(e.type),o(e))},a=function(e){return i(E.mfhd,new Uint8Array([0,0,0,0,(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e]))},o=function(e){return i(E.minf,"video"===e.type?i(E.vmhd,D):i(E.smhd,P),s(),_(e))},l=function(e,t){for(var s=[],r=t.length;r--;)s[r]=v(t[r]);return i.apply(null,[E.moof,a(e)].concat(s))},d=function(e){for(var t=e.length,s=[];t--;)s[t]=h(e[t]);return i.apply(null,[E.moov,c(4294967295)].concat(s).concat(u(e)))},u=function(e){for(var t=e.length,s=[];t--;)s[t]=T(e[t]);return i.apply(null,[E.mvex].concat(s))},c=function(e){var t=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e,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 i(E.mvhd,t)},y=function(e){var t,s,r=e.samples||[],n=new Uint8Array(4+r.length);for(s=0;s<r.length;s++)t=r[s].flags,n[s+4]=t.dependsOn<<4|t.isDependedOn<<2|t.hasRedundancy;return i(E.sdtp,n)},_=function(e){return i(E.stbl,b(e),i(E.stts,N),i(E.stsc,M),i(E.stsz,R),i(E.stco,O))},b=function(e){return i(E.stsd,new Uint8Array([0,0,0,0,0,0,0,1]),"video"===e.type?U(e):B(e))},U=function(e){var t,s,r=e.sps||[],n=e.pps||[],a=[],o=[];for(t=0;t<r.length;t++)a.push((65280&r[t].byteLength)>>>8),a.push(255&r[t].byteLength),a=a.concat(Array.prototype.slice.call(r[t]));for(t=0;t<n.length;t++)o.push((65280&n[t].byteLength)>>>8),o.push(255&n[t].byteLength),o=o.concat(Array.prototype.slice.call(n[t]));if(s=[E.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,(65280&e.width)>>8,255&e.width,(65280&e.height)>>8,255&e.height,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]),i(E.avcC,new Uint8Array([1,e.profileIdc,e.profileCompatibility,e.levelIdc,255].concat([r.length],a,[n.length],o))),i(E.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],e.sarRatio){var l=e.sarRatio[0],d=e.sarRatio[1];s.push(i(E.pasp,new Uint8Array([(4278190080&l)>>24,(16711680&l)>>16,(65280&l)>>8,255&l,(4278190080&d)>>24,(16711680&d)>>16,(65280&d)>>8,255&d])))}return i.apply(null,s)},B=function(e){return i(E.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(65280&e.channelcount)>>8,255&e.channelcount,(65280&e.samplesize)>>8,255&e.samplesize,0,0,0,0,(65280&e.samplerate)>>8,255&e.samplerate,0,0]),r(e))},p=function(e){var t=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(4278190080&e.id)>>24,(16711680&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,0,(4278190080&e.duration)>>24,(16711680&e.duration)>>16,(65280&e.duration)>>8,255&e.duration,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,(65280&e.width)>>8,255&e.width,0,0,(65280&e.height)>>8,255&e.height,0,0]);return i(E.tkhd,t)},v=function(e){var t,s,r,n,a,o;return t=i(E.tfhd,new Uint8Array([0,0,0,58,(4278190080&e.id)>>24,(16711680&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),a=Math.floor(e.baseMediaDecodeTime/z),o=Math.floor(e.baseMediaDecodeTime%z),s=i(E.tfdt,new Uint8Array([1,0,0,0,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o>>>24&255,o>>>16&255,o>>>8&255,255&o])),"audio"===e.type?(r=S(e,92),i(E.traf,t,s,r)):(n=y(e),r=S(e,n.length+92),i(E.traf,t,s,r,n))},h=function(e){return e.duration=e.duration||4294967295,i(E.trak,p(e),m(e))},T=function(e){var t=new Uint8Array([0,0,0,0,(4278190080&e.id)>>24,(16711680&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return"video"!==e.type&&(t[t.length-1]=0),i(E.trex,t)},j=function(e,t){var i=0,s=0,r=0,n=0;return e.length&&(void 0!==e[0].duration&&(i=1),void 0!==e[0].size&&(s=2),void 0!==e[0].flags&&(r=4),void 0!==e[0].compositionTimeOffset&&(n=8)),[0,0,i|s|r|n,1,(4278190080&e.length)>>>24,(16711680&e.length)>>>16,(65280&e.length)>>>8,255&e.length,(4278190080&t)>>>24,(16711680&t)>>>16,(65280&t)>>>8,255&t]},q=function(e,t){var s,r,n,a,o,l;for(t+=20+16*(a=e.samples||[]).length,n=j(a,t),(r=new Uint8Array(n.length+16*a.length)).set(n),s=n.length,l=0;l<a.length;l++)o=a[l],r[s++]=(4278190080&o.duration)>>>24,r[s++]=(16711680&o.duration)>>>16,r[s++]=(65280&o.duration)>>>8,r[s++]=255&o.duration,r[s++]=(4278190080&o.size)>>>24,r[s++]=(16711680&o.size)>>>16,r[s++]=(65280&o.size)>>>8,r[s++]=255&o.size,r[s++]=o.flags.isLeading<<2|o.flags.dependsOn,r[s++]=o.flags.isDependedOn<<6|o.flags.hasRedundancy<<4|o.flags.paddingValue<<1|o.flags.isNonSyncSample,r[s++]=61440&o.flags.degradationPriority,r[s++]=15&o.flags.degradationPriority,r[s++]=(4278190080&o.compositionTimeOffset)>>>24,r[s++]=(16711680&o.compositionTimeOffset)>>>16,r[s++]=(65280&o.compositionTimeOffset)>>>8,r[s++]=255&o.compositionTimeOffset;return i(E.trun,r)},F=function(e,t){var s,r,n,a,o,l;for(t+=20+8*(a=e.samples||[]).length,n=j(a,t),(s=new Uint8Array(n.length+8*a.length)).set(n),r=n.length,l=0;l<a.length;l++)o=a[l],s[r++]=(4278190080&o.duration)>>>24,s[r++]=(16711680&o.duration)>>>16,s[r++]=(65280&o.duration)>>>8,s[r++]=255&o.duration,s[r++]=(4278190080&o.size)>>>24,s[r++]=(16711680&o.size)>>>16,s[r++]=(65280&o.size)>>>8,s[r++]=255&o.size;return i(E.trun,s)},S=function(e,t){return"audio"===e.type?F(e,t):q(e,t)};var W,G,X,K,Y,Q,J,Z,ee={ftyp:n=function(){return i(E.ftyp,w,k,w,C)},mdat:function(e){return i(E.mdat,e)},moof:l,moov:d,initSegment:function(e){var t,i=n(),s=d(e);return(t=new Uint8Array(i.byteLength+s.byteLength)).set(i),t.set(s,i.byteLength),t}},te=function(e,t){var i={size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}};return i.dataOffset=t,i.compositionTimeOffset=e.pts-e.dts,i.duration=e.duration,i.size=4*e.length,i.size+=e.byteLength,e.keyFrame&&(i.flags.dependsOn=2,i.flags.isNonSyncSample=0),i},ie={groupNalsIntoFrames:function(e){var t,i,s=[],r=[];for(r.byteLength=0,r.nalCount=0,r.duration=0,s.byteLength=0,t=0;t<e.length;t++)"access_unit_delimiter_rbsp"===(i=e[t]).nalUnitType?(s.length&&(s.duration=i.dts-s.dts,r.byteLength+=s.byteLength,r.nalCount+=s.length,r.duration+=s.duration,r.push(s)),(s=[i]).byteLength=i.data.byteLength,s.pts=i.pts,s.dts=i.dts):("slice_layer_without_partitioning_rbsp_idr"===i.nalUnitType&&(s.keyFrame=!0),s.duration=i.dts-s.dts,s.byteLength+=i.data.byteLength,s.push(i));return r.length&&(!s.duration||s.duration<=0)&&(s.duration=r[r.length-1].duration),r.byteLength+=s.byteLength,r.nalCount+=s.length,r.duration+=s.duration,r.push(s),r},groupFramesIntoGops:function(e){var t,i,s=[],r=[];for(s.byteLength=0,s.nalCount=0,s.duration=0,s.pts=e[0].pts,s.dts=e[0].dts,r.byteLength=0,r.nalCount=0,r.duration=0,r.pts=e[0].pts,r.dts=e[0].dts,t=0;t<e.length;t++)(i=e[t]).keyFrame?(s.length&&(r.push(s),r.byteLength+=s.byteLength,r.nalCount+=s.nalCount,r.duration+=s.duration),(s=[i]).nalCount=i.length,s.byteLength=i.byteLength,s.pts=i.pts,s.dts=i.dts,s.duration=i.duration):(s.duration+=i.duration,s.nalCount+=i.length,s.byteLength+=i.byteLength,s.push(i));return r.length&&s.duration<=0&&(s.duration=r[r.length-1].duration),r.byteLength+=s.byteLength,r.nalCount+=s.nalCount,r.duration+=s.duration,r.push(s),r},extendFirstKeyFrame:function(e){var t;return!e[0][0].keyFrame&&e.length>1&&(t=e.shift(),e.byteLength-=t.byteLength,e.nalCount-=t.nalCount,e[0][0].dts=t.dts,e[0][0].pts=t.pts,e[0][0].duration+=t.duration),e},generateSampleTable:function(e,t){var i,s,r,n,a,o=t||0,l=[];for(i=0;i<e.length;i++)for(n=e[i],s=0;s<n.length;s++)a=n[s],o+=(r=te(a,o)).size,l.push(r);return l},concatenateNalData:function(e){var t,i,s,r,n,a,o=0,l=e.byteLength,d=e.nalCount,u=new Uint8Array(l+4*d),c=new DataView(u.buffer);for(t=0;t<e.length;t++)for(r=e[t],i=0;i<r.length;i++)for(n=r[i],s=0;s<n.length;s++)a=n[s],c.setUint32(o,a.data.byteLength),o+=4,u.set(a.data,o),o+=a.data.byteLength;return u},generateSampleTableForFrame:function(e,t){var i,s=[];return i=te(e,t||0),s.push(i),s},concatenateNalDataForFrame:function(e){var t,i,s=0,r=e.byteLength,n=e.length,a=new Uint8Array(r+4*n),o=new DataView(a.buffer);for(t=0;t<e.length;t++)i=e[t],o.setUint32(s,i.data.byteLength),s+=4,a.set(i.data,s),s+=i.data.byteLength;return a}},se=[33,16,5,32,164,27],re=[33,65,108,84,1,2,4,8,168,2,4,8,17,191,252],ne=function(e){for(var t=[];e--;)t.push(0);return t},ae=9e4;Q=function(e,t){return G(Y(e,t))},J=function(e,t){return X(K(e),t)},Z=function(e,t,i){return K(i?e:e-t)};var oe={ONE_SECOND_IN_TS:ae,secondsToVideoTs:G=function(e){return e*ae},secondsToAudioTs:X=function(e,t){return e*t},videoTsToSeconds:K=function(e){return e/ae},audioTsToSeconds:Y=function(e,t){return e/t},audioTsToVideoTs:Q,videoTsToAudioTs:J,metadataTsToSeconds:Z},le=function(){if(!W){var e={96e3:[se,[227,64],ne(154),[56]],88200:[se,[231],ne(170),[56]],64e3:[se,[248,192],ne(240),[56]],48e3:[se,[255,192],ne(268),[55,148,128],ne(54),[112]],44100:[se,[255,192],ne(268),[55,163,128],ne(84),[112]],32e3:[se,[255,192],ne(268),[55,234],ne(226),[112]],24e3:[se,[255,192],ne(268),[55,255,128],ne(268),[111,112],ne(126),[224]],16e3:[se,[255,192],ne(268),[55,255,128],ne(268),[111,255],ne(269),[223,108],ne(195),[1,192]],12e3:[re,ne(268),[3,127,248],ne(268),[6,255,240],ne(268),[13,255,224],ne(268),[27,253,128],ne(259),[56]],11025:[re,ne(268),[3,127,248],ne(268),[6,255,240],ne(268),[13,255,224],ne(268),[27,255,192],ne(268),[55,175,128],ne(108),[112]],8e3:[re,ne(268),[3,121,16],ne(47),[7]]};t=e,W=Object.keys(t).reduce(function(e,i){return e[i]=new Uint8Array(t[i].reduce(function(e,t){return e.concat(t)},[])),e},{})}var t;return W},de=oe,ue={prefixWithSilence:function(e,t,i,s){var r,n,a,o,l,d=0,u=0,c=0;if(t.length&&(r=de.audioTsToVideoTs(e.baseMediaDecodeTime,e.samplerate),n=Math.ceil(de.ONE_SECOND_IN_TS/(e.samplerate/1024)),i&&s&&(d=r-Math.max(i,s),c=(u=Math.floor(d/n))*n),!(u<1||c>de.ONE_SECOND_IN_TS/2))){for((a=le()[e.samplerate])||(a=t[0].data),o=0;o<u;o++)l=t[0],t.splice(0,0,{data:a,dts:l.dts-n,pts:l.pts-n});return e.baseMediaDecodeTime-=Math.floor(de.videoTsToAudioTs(c,e.samplerate)),c}},trimAdtsFramesByEarliestDts:function(e,t,i){return t.minSegmentDts>=i?e:(t.minSegmentDts=1/0,e.filter(function(e){return e.dts>=i&&(t.minSegmentDts=Math.min(t.minSegmentDts,e.dts),t.minSegmentPts=t.minSegmentDts,!0)}))},generateSampleTable:function(e){var t,i,s=[];for(t=0;t<e.length;t++)i=e[t],s.push({size:i.data.byteLength,duration:1024});return s},concatenateFrameData:function(e){var t,i,s=0,r=new Uint8Array(function(e){var t,i=0;for(t=0;t<e.length;t++)i+=e[t].data.byteLength;return i}(e));for(t=0;t<e.length;t++)i=e[t],r.set(i.data,s),s+=i.data.byteLength;return r}},ce=oe.ONE_SECOND_IN_TS,he={clearDtsInfo:function(e){delete e.minSegmentDts,delete e.maxSegmentDts,delete e.minSegmentPts,delete e.maxSegmentPts},calculateTrackBaseMediaDecodeTime:function(e,t){var i,s=e.minSegmentDts;return t||(s-=e.timelineStartInfo.dts),i=e.timelineStartInfo.baseMediaDecodeTime,i+=s,i=Math.max(0,i),"audio"===e.type&&(i*=e.samplerate/ce,i=Math.floor(i)),i},collectDtsInfo:function(e,t){"number"==typeof t.pts&&(void 0===e.timelineStartInfo.pts&&(e.timelineStartInfo.pts=t.pts),void 0===e.minSegmentPts?e.minSegmentPts=t.pts:e.minSegmentPts=Math.min(e.minSegmentPts,t.pts),void 0===e.maxSegmentPts?e.maxSegmentPts=t.pts:e.maxSegmentPts=Math.max(e.maxSegmentPts,t.pts)),"number"==typeof t.dts&&(void 0===e.timelineStartInfo.dts&&(e.timelineStartInfo.dts=t.dts),void 0===e.minSegmentDts?e.minSegmentDts=t.dts:e.minSegmentDts=Math.min(e.minSegmentDts,t.dts),void 0===e.maxSegmentDts?e.maxSegmentDts=t.dts:e.maxSegmentDts=Math.max(e.maxSegmentDts,t.dts))}},pe={parseSei:function(e){for(var t=0,i={payloadType:-1,payloadSize:0},s=0,r=0;t<e.byteLength&&128!==e[t];){for(;255===e[t];)s+=255,t++;for(s+=e[t++];255===e[t];)r+=255,t++;if(r+=e[t++],!i.payload&&4===s){if("GA94"===String.fromCharCode(e[t+3],e[t+4],e[t+5],e[t+6])){i.payloadType=s,i.payloadSize=r,i.payload=e.subarray(t,t+r);break}i.payload=void 0}t+=r,s=0,r=0}return i},parseUserData:function(e){return 181!==e.payload[0]||49!=(e.payload[1]<<8|e.payload[2])||"GA94"!==String.fromCharCode(e.payload[3],e.payload[4],e.payload[5],e.payload[6])||3!==e.payload[7]?null:e.payload.subarray(8,e.payload.length-1)},parseCaptionPackets:function(e,t){var i,s,r,n,a=[];if(!(64&t[0]))return a;for(s=31&t[0],i=0;i<s;i++)n={type:3&t[(r=3*i)+2],pts:e},4&t[r+2]&&(n.ccData=t[r+3]<<8|t[r+4],a.push(n));return a},discardEmulationPreventionBytes:function(e){for(var t,i,s=e.byteLength,r=[],n=1;n<s-2;)0===e[n]&&0===e[n+1]&&3===e[n+2]?(r.push(n+2),n+=2):n++;if(0===r.length)return e;t=s-r.length,i=new Uint8Array(t);var a=0;for(n=0;n<t;a++,n++)a===r[0]&&(a++,r.shift()),i[n]=e[a];return i},USER_DATA_REGISTERED_ITU_T_T35:4},me=V,ge=pe,fe=function(e){e=e||{},fe.prototype.init.call(this),this.parse708captions_="boolean"!=typeof e.parse708captions||e.parse708captions,this.captionPackets_=[],this.ccStreams_=[new Ce(0,0),new Ce(0,1),new Ce(1,0),new Ce(1,1)],this.parse708captions_&&(this.cc708Stream_=new Te({captionServices:e.captionServices})),this.reset(),this.ccStreams_.forEach(function(e){e.on("data",this.trigger.bind(this,"data")),e.on("partialdone",this.trigger.bind(this,"partialdone")),e.on("done",this.trigger.bind(this,"done"))},this),this.parse708captions_&&(this.cc708Stream_.on("data",this.trigger.bind(this,"data")),this.cc708Stream_.on("partialdone",this.trigger.bind(this,"partialdone")),this.cc708Stream_.on("done",this.trigger.bind(this,"done")))};fe.prototype=new me,fe.prototype.push=function(e){var t,i,s;if("sei_rbsp"===e.nalUnitType&&(t=ge.parseSei(e.escapedRBSP)).payload&&t.payloadType===ge.USER_DATA_REGISTERED_ITU_T_T35&&(i=ge.parseUserData(t)))if(e.dts<this.latestDts_)this.ignoreNextEqualDts_=!0;else{if(e.dts===this.latestDts_&&this.ignoreNextEqualDts_)return this.numSameDts_--,void(this.numSameDts_||(this.ignoreNextEqualDts_=!1));s=ge.parseCaptionPackets(e.pts,i),this.captionPackets_=this.captionPackets_.concat(s),this.latestDts_!==e.dts&&(this.numSameDts_=0),this.numSameDts_++,this.latestDts_=e.dts}},fe.prototype.flushCCStreams=function(e){this.ccStreams_.forEach(function(t){return"flush"===e?t.flush():t.partialFlush()},this)},fe.prototype.flushStream=function(e){this.captionPackets_.length?(this.captionPackets_.forEach(function(e,t){e.presortIndex=t}),this.captionPackets_.sort(function(e,t){return e.pts===t.pts?e.presortIndex-t.presortIndex:e.pts-t.pts}),this.captionPackets_.forEach(function(e){e.type<2?this.dispatchCea608Packet(e):this.dispatchCea708Packet(e)},this),this.captionPackets_.length=0,this.flushCCStreams(e)):this.flushCCStreams(e)},fe.prototype.flush=function(){return this.flushStream("flush")},fe.prototype.partialFlush=function(){return this.flushStream("partialFlush")},fe.prototype.reset=function(){this.latestDts_=null,this.ignoreNextEqualDts_=!1,this.numSameDts_=0,this.activeCea608Channel_=[null,null],this.ccStreams_.forEach(function(e){e.reset()})},fe.prototype.dispatchCea608Packet=function(e){this.setsTextOrXDSActive(e)?this.activeCea608Channel_[e.type]=null:this.setsChannel1Active(e)?this.activeCea608Channel_[e.type]=0:this.setsChannel2Active(e)&&(this.activeCea608Channel_[e.type]=1),null!==this.activeCea608Channel_[e.type]&&this.ccStreams_[(e.type<<1)+this.activeCea608Channel_[e.type]].push(e)},fe.prototype.setsChannel1Active=function(e){return 4096==(30720&e.ccData)},fe.prototype.setsChannel2Active=function(e){return 6144==(30720&e.ccData)},fe.prototype.setsTextOrXDSActive=function(e){return 256==(28928&e.ccData)||4138==(30974&e.ccData)||6186==(30974&e.ccData)},fe.prototype.dispatchCea708Packet=function(e){this.parse708captions_&&this.cc708Stream_.push(e)};var ye={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},_e=function(e){return 32<=e&&e<=127||160<=e&&e<=255},be=function(e){this.windowNum=e,this.reset()};be.prototype.reset=function(){this.clearText(),this.pendingNewLine=!1,this.winAttr={},this.penAttr={},this.penLoc={},this.penColor={},this.visible=0,this.rowLock=0,this.columnLock=0,this.priority=0,this.relativePositioning=0,this.anchorVertical=0,this.anchorHorizontal=0,this.anchorPoint=0,this.rowCount=1,this.virtualRowCount=this.rowCount+1,this.columnCount=41,this.windowStyle=0,this.penStyle=0},be.prototype.getText=function(){return this.rows.join("\n")},be.prototype.clearText=function(){this.rows=[""],this.rowIdx=0},be.prototype.newLine=function(e){for(this.rows.length>=this.virtualRowCount&&"function"==typeof this.beforeRowOverflow&&this.beforeRowOverflow(e),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},be.prototype.isEmpty=function(){return 0===this.rows.length||1===this.rows.length&&""===this.rows[0]},be.prototype.addText=function(e){this.rows[this.rowIdx]+=e},be.prototype.backspace=function(){if(!this.isEmpty()){var e=this.rows[this.rowIdx];this.rows[this.rowIdx]=e.substr(0,e.length-1)}};var ve=function(e,t,i){this.serviceNum=e,this.text="",this.currentWindow=new be(-1),this.windows=[],this.stream=i,"string"==typeof t&&this.createTextDecoder(t)};ve.prototype.init=function(e,t){this.startPts=e;for(var i=0;i<8;i++)this.windows[i]=new be(i),"function"==typeof t&&(this.windows[i].beforeRowOverflow=t)},ve.prototype.setCurrentWindow=function(e){this.currentWindow=this.windows[e]},ve.prototype.createTextDecoder=function(e){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(e)}catch(t){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+e+" encoding. "+t})}};var Te=function(e){e=e||{},Te.prototype.init.call(this);var t,i=this,s=e.captionServices||{},r={};Object.keys(s).forEach(e=>{t=s[e],/^SERVICE/.test(e)&&(r[e]=t.encoding)}),this.serviceEncodings=r,this.current708Packet=null,this.services={},this.push=function(e){3===e.type?(i.new708Packet(),i.add708Bytes(e)):(null===i.current708Packet&&i.new708Packet(),i.add708Bytes(e))}};Te.prototype=new me,Te.prototype.new708Packet=function(){null!==this.current708Packet&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},Te.prototype.add708Bytes=function(e){var t=e.ccData,i=t>>>8,s=255&t;this.current708Packet.ptsVals.push(e.pts),this.current708Packet.data.push(i),this.current708Packet.data.push(s)},Te.prototype.push708Packet=function(){var e=this.current708Packet,t=e.data,i=null,s=null,r=0,n=t[r++];for(e.seq=n>>6,e.sizeCode=63&n;r<t.length;r++)s=31&(n=t[r++]),7===(i=n>>5)&&s>0&&(i=n=t[r++]),this.pushServiceBlock(i,r,s),s>0&&(r+=s-1)},Te.prototype.pushServiceBlock=function(e,t,i){var s,r=t,n=this.current708Packet.data,a=this.services[e];for(a||(a=this.initService(e,r));r<t+i&&r<n.length;r++)s=n[r],_e(s)?r=this.handleText(r,a):24===s?r=this.multiByteCharacter(r,a):16===s?r=this.extendedCommands(r,a):128<=s&&s<=135?r=this.setCurrentWindow(r,a):152<=s&&s<=159?r=this.defineWindow(r,a):136===s?r=this.clearWindows(r,a):140===s?r=this.deleteWindows(r,a):137===s?r=this.displayWindows(r,a):138===s?r=this.hideWindows(r,a):139===s?r=this.toggleWindows(r,a):151===s?r=this.setWindowAttributes(r,a):144===s?r=this.setPenAttributes(r,a):145===s?r=this.setPenColor(r,a):146===s?r=this.setPenLocation(r,a):143===s?a=this.reset(r,a):8===s?a.currentWindow.backspace():12===s?a.currentWindow.clearText():13===s?a.currentWindow.pendingNewLine=!0:14===s?a.currentWindow.clearText():141===s&&r++},Te.prototype.extendedCommands=function(e,t){var i=this.current708Packet.data[++e];return _e(i)&&(e=this.handleText(e,t,{isExtended:!0})),e},Te.prototype.getPts=function(e){return this.current708Packet.ptsVals[Math.floor(e/2)]},Te.prototype.initService=function(e,t){var i,s,r=this;return(i="SERVICE"+e)in this.serviceEncodings&&(s=this.serviceEncodings[i]),this.services[e]=new ve(e,s,r),this.services[e].init(this.getPts(t),function(t){r.flushDisplayed(t,r.services[e])}),this.services[e]},Te.prototype.handleText=function(e,t,i){var s,r,n,a,o=i&&i.isExtended,l=i&&i.isMultiByte,d=this.current708Packet.data,u=o?4096:0,c=d[e],h=d[e+1],p=t.currentWindow;if(l?(r=[c,h],e++):r=[c],t.textDecoder_&&!o)s=t.textDecoder_.decode(new Uint8Array(r));else if(l){const e=r.map(e=>("0"+(255&e).toString(16)).slice(-2)).join("");s=String.fromCharCode(parseInt(e,16))}else a=ye[n=u|c]||n,s=4096&n&&n===a?"":String.fromCharCode(a);return p.pendingNewLine&&!p.isEmpty()&&p.newLine(this.getPts(e)),p.pendingNewLine=!1,p.addText(s),e},Te.prototype.multiByteCharacter=function(e,t){var i=this.current708Packet.data,s=i[e+1],r=i[e+2];return _e(s)&&_e(r)&&(e=this.handleText(++e,t,{isMultiByte:!0})),e},Te.prototype.setCurrentWindow=function(e,t){var i=7&this.current708Packet.data[e];return t.setCurrentWindow(i),e},Te.prototype.defineWindow=function(e,t){var i=this.current708Packet.data,s=i[e],r=7&s;t.setCurrentWindow(r);var n=t.currentWindow;return s=i[++e],n.visible=(32&s)>>5,n.rowLock=(16&s)>>4,n.columnLock=(8&s)>>3,n.priority=7&s,s=i[++e],n.relativePositioning=(128&s)>>7,n.anchorVertical=127&s,s=i[++e],n.anchorHorizontal=s,s=i[++e],n.anchorPoint=(240&s)>>4,n.rowCount=15&s,s=i[++e],n.columnCount=63&s,s=i[++e],n.windowStyle=(56&s)>>3,n.penStyle=7&s,n.virtualRowCount=n.rowCount+1,e},Te.prototype.setWindowAttributes=function(e,t){var i=this.current708Packet.data,s=i[e],r=t.currentWindow.winAttr;return s=i[++e],r.fillOpacity=(192&s)>>6,r.fillRed=(48&s)>>4,r.fillGreen=(12&s)>>2,r.fillBlue=3&s,s=i[++e],r.borderType=(192&s)>>6,r.borderRed=(48&s)>>4,r.borderGreen=(12&s)>>2,r.borderBlue=3&s,s=i[++e],r.borderType+=(128&s)>>5,r.wordWrap=(64&s)>>6,r.printDirection=(48&s)>>4,r.scrollDirection=(12&s)>>2,r.justify=3&s,s=i[++e],r.effectSpeed=(240&s)>>4,r.effectDirection=(12&s)>>2,r.displayEffect=3&s,e},Te.prototype.flushDisplayed=function(e,t){for(var i=[],s=0;s<8;s++)t.windows[s].visible&&!t.windows[s].isEmpty()&&i.push(t.windows[s].getText());t.endPts=e,t.text=i.join("\n\n"),this.pushCaption(t),t.startPts=e},Te.prototype.pushCaption=function(e){""!==e.text&&(this.trigger("data",{startPts:e.startPts,endPts:e.endPts,text:e.text,stream:"cc708_"+e.serviceNum}),e.text="",e.startPts=e.endPts)},Te.prototype.displayWindows=function(e,t){var i=this.current708Packet.data[++e],s=this.getPts(e);this.flushDisplayed(s,t);for(var r=0;r<8;r++)i&1<<r&&(t.windows[r].visible=1);return e},Te.prototype.hideWindows=function(e,t){var i=this.current708Packet.data[++e],s=this.getPts(e);this.flushDisplayed(s,t);for(var r=0;r<8;r++)i&1<<r&&(t.windows[r].visible=0);return e},Te.prototype.toggleWindows=function(e,t){var i=this.current708Packet.data[++e],s=this.getPts(e);this.flushDisplayed(s,t);for(var r=0;r<8;r++)i&1<<r&&(t.windows[r].visible^=1);return e},Te.prototype.clearWindows=function(e,t){var i=this.current708Packet.data[++e],s=this.getPts(e);this.flushDisplayed(s,t);for(var r=0;r<8;r++)i&1<<r&&t.windows[r].clearText();return e},Te.prototype.deleteWindows=function(e,t){var i=this.current708Packet.data[++e],s=this.getPts(e);this.flushDisplayed(s,t);for(var r=0;r<8;r++)i&1<<r&&t.windows[r].reset();return e},Te.prototype.setPenAttributes=function(e,t){var i=this.current708Packet.data,s=i[e],r=t.currentWindow.penAttr;return s=i[++e],r.textTag=(240&s)>>4,r.offset=(12&s)>>2,r.penSize=3&s,s=i[++e],r.italics=(128&s)>>7,r.underline=(64&s)>>6,r.edgeType=(56&s)>>3,r.fontStyle=7&s,e},Te.prototype.setPenColor=function(e,t){var i=this.current708Packet.data,s=i[e],r=t.currentWindow.penColor;return s=i[++e],r.fgOpacity=(192&s)>>6,r.fgRed=(48&s)>>4,r.fgGreen=(12&s)>>2,r.fgBlue=3&s,s=i[++e],r.bgOpacity=(192&s)>>6,r.bgRed=(48&s)>>4,r.bgGreen=(12&s)>>2,r.bgBlue=3&s,s=i[++e],r.edgeRed=(48&s)>>4,r.edgeGreen=(12&s)>>2,r.edgeBlue=3&s,e},Te.prototype.setPenLocation=function(e,t){var i=this.current708Packet.data,s=i[e],r=t.currentWindow.penLoc;return t.currentWindow.pendingNewLine=!0,s=i[++e],r.row=15&s,s=i[++e],r.column=63&s,e},Te.prototype.reset=function(e,t){var i=this.getPts(e);return this.flushDisplayed(i,t),this.initService(t.serviceNum,e)};var Se={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},Ee=function(e){return null===e?"":(e=Se[e]||e,String.fromCharCode(e))},we=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],ke=function(){for(var e=[],t=15;t--;)e.push({text:"",indent:0,offset:0});return e},Ce=function(e,t){Ce.prototype.init.call(this),this.field_=e||0,this.dataChannel_=t||0,this.name_="CC"+(1+(this.field_<<1|this.dataChannel_)),this.setConstants(),this.reset(),this.push=function(e){var t,i,s,r,n;if((t=32639&e.ccData)!==this.lastControlCode_){if(4096==(61440&t)?this.lastControlCode_=t:t!==this.PADDING_&&(this.lastControlCode_=null),s=t>>>8,r=255&t,t!==this.PADDING_)if(t===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(t===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(e.pts),this.flushDisplayed(e.pts),i=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=i,this.startPts_=e.pts;else if(t===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(e.pts);else if(t===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(e.pts);else if(t===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(e.pts);else if(t===this.CARRIAGE_RETURN_)this.clearFormatting(e.pts),this.flushDisplayed(e.pts),this.shiftRowsUp_(),this.startPts_=e.pts;else if(t===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);else if(t===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(e.pts),this.displayed_=ke();else if(t===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=ke();else if(t===this.RESUME_DIRECT_CAPTIONING_)"paintOn"!==this.mode_&&(this.flushDisplayed(e.pts),this.displayed_=ke()),this.mode_="paintOn",this.startPts_=e.pts;else if(this.isSpecialCharacter(s,r))n=Ee((s=(3&s)<<8)|r),this[this.mode_](e.pts,n),this.column_++;else if(this.isExtCharacter(s,r))"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),n=Ee((s=(3&s)<<8)|r),this[this.mode_](e.pts,n),this.column_++;else if(this.isMidRowCode(s,r))this.clearFormatting(e.pts),this[this.mode_](e.pts," "),this.column_++,14&~r||this.addFormatting(e.pts,["i"]),1&~r||this.addFormatting(e.pts,["u"]);else if(this.isOffsetControlCode(s,r)){const e=3&r;this.nonDisplayed_[this.row_].offset=e,this.column_+=e}else if(this.isPAC(s,r)){var a=we.indexOf(7968&t);if("rollUp"===this.mode_&&(a-this.rollUpRows_+1<0&&(a=this.rollUpRows_-1),this.setRollUp(e.pts,a)),a!==this.row_&&a>=0&&a<=14&&(this.clearFormatting(e.pts),this.row_=a),1&r&&-1===this.formatting_.indexOf("u")&&this.addFormatting(e.pts,["u"]),!(16&~t)){const e=(14&t)>>1;this.column_=4*e,this.nonDisplayed_[this.row_].indent+=e}this.isColorPAC(r)&&(14&~r||this.addFormatting(e.pts,["i"]))}else this.isNormalChar(s)&&(0===r&&(r=null),n=Ee(s),n+=Ee(r),this[this.mode_](e.pts,n),this.column_+=n.length)}else this.lastControlCode_=null}};Ce.prototype=new me,Ce.prototype.flushDisplayed=function(e){const t=e=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+e+"."})},i=[];this.displayed_.forEach((e,s)=>{if(e&&e.text&&e.text.length){try{e.text=e.text.trim()}catch(e){t(s)}e.text.length&&i.push({text:e.text,line:s+1,position:10+Math.min(70,10*e.indent)+2.5*e.offset})}else null==e&&t(s)}),i.length&&this.trigger("data",{startPts:this.startPts_,endPts:e,content:i,stream:this.name_})},Ce.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=ke(),this.nonDisplayed_=ke(),this.lastControlCode_=null,this.column_=0,this.row_=14,this.rollUpRows_=2,this.formatting_=[]},Ce.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_=32|this.CONTROL_,this.END_OF_CAPTION_=47|this.CONTROL_,this.ROLL_UP_2_ROWS_=37|this.CONTROL_,this.ROLL_UP_3_ROWS_=38|this.CONTROL_,this.ROLL_UP_4_ROWS_=39|this.CONTROL_,this.CARRIAGE_RETURN_=45|this.CONTROL_,this.RESUME_DIRECT_CAPTIONING_=41|this.CONTROL_,this.BACKSPACE_=33|this.CONTROL_,this.ERASE_DISPLAYED_MEMORY_=44|this.CONTROL_,this.ERASE_NON_DISPLAYED_MEMORY_=46|this.CONTROL_},Ce.prototype.isSpecialCharacter=function(e,t){return e===this.EXT_&&t>=48&&t<=63},Ce.prototype.isExtCharacter=function(e,t){return(e===this.EXT_+1||e===this.EXT_+2)&&t>=32&&t<=63},Ce.prototype.isMidRowCode=function(e,t){return e===this.EXT_&&t>=32&&t<=47},Ce.prototype.isOffsetControlCode=function(e,t){return e===this.OFFSET_&&t>=33&&t<=35},Ce.prototype.isPAC=function(e,t){return e>=this.BASE_&&e<this.BASE_+8&&t>=64&&t<=127},Ce.prototype.isColorPAC=function(e){return e>=64&&e<=79||e>=96&&e<=127},Ce.prototype.isNormalChar=function(e){return e>=32&&e<=127},Ce.prototype.setRollUp=function(e,t){if("rollUp"!==this.mode_&&(this.row_=14,this.mode_="rollUp",this.flushDisplayed(e),this.nonDisplayed_=ke(),this.displayed_=ke()),void 0!==t&&t!==this.row_)for(var i=0;i<this.rollUpRows_;i++)this.displayed_[t-i]=this.displayed_[this.row_-i],this.displayed_[this.row_-i]={text:"",indent:0,offset:0};void 0===t&&(t=this.row_),this.topRow_=t-this.rollUpRows_+1},Ce.prototype.addFormatting=function(e,t){this.formatting_=this.formatting_.concat(t);var i=t.reduce(function(e,t){return e+"<"+t+">"},"");this[this.mode_](e,i)},Ce.prototype.clearFormatting=function(e){if(this.formatting_.length){var t=this.formatting_.reverse().reduce(function(e,t){return e+"</"+t+">"},"");this.formatting_=[],this[this.mode_](e,t)}},Ce.prototype.popOn=function(e,t){var i=this.nonDisplayed_[this.row_].text;i+=t,this.nonDisplayed_[this.row_].text=i},Ce.prototype.rollUp=function(e,t){var i=this.displayed_[this.row_].text;i+=t,this.displayed_[this.row_].text=i},Ce.prototype.shiftRowsUp_=function(){var e;for(e=0;e<this.topRow_;e++)this.displayed_[e]={text:"",indent:0,offset:0};for(e=this.row_+1;e<15;e++)this.displayed_[e]={text:"",indent:0,offset:0};for(e=this.topRow_;e<this.row_;e++)this.displayed_[e]=this.displayed_[e+1];this.displayed_[this.row_]={text:"",indent:0,offset:0}},Ce.prototype.paintOn=function(e,t){var i=this.displayed_[this.row_].text;i+=t,this.displayed_[this.row_].text=i};var Ie={CaptionStream:fe,Cea608Stream:Ce,Cea708Stream:Te},xe={H264_STREAM_TYPE:27,ADTS_STREAM_TYPE:15,METADATA_STREAM_TYPE:21},Ae=V,De="shared",Pe=function(e,t){var i=1;for(e>t&&(i=-1);Math.abs(t-e)>4294967296;)e+=8589934592*i;return e},Le=function(e){var t,i;Le.prototype.init.call(this),this.type_=e||De,this.push=function(e){"metadata"!==e.type?this.type_!==De&&e.type!==this.type_||(void 0===i&&(i=e.dts),e.dts=Pe(e.dts,i),e.pts=Pe(e.pts,i),t=e.dts,this.trigger("data",e)):this.trigger("data",e)},this.flush=function(){i=t,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){i=void 0,t=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};Le.prototype=new Ae;var Oe,Me={TimestampRolloverStream:Le,handleRollover:Pe},Re=(e,t,i)=>{if(!e)return-1;for(var s=i;s<e.length;s++)if(e[s]===t)return s;return-1},Ne=Re,Ue=3,Be=function(e,t,i){var s,r="";for(s=t;s<i;s++)r+="%"+("00"+e[s].toString(16)).slice(-2);return r},Fe=function(e,t,i){return decodeURIComponent(Be(e,t,i))},qe=function(e,t,i){return unescape(Be(e,t,i))},je=function(e){return e[0]<<21|e[1]<<14|e[2]<<7|e[3]},Ve={APIC:function(e){var t,i,s=1;e.data[0]===Ue&&((t=Ne(e.data,0,s))<0||(e.mimeType=qe(e.data,s,t),s=t+1,e.pictureType=e.data[s],s++,(i=Ne(e.data,0,s))<0||(e.description=Fe(e.data,s,i),s=i+1,"--\x3e"===e.mimeType?e.url=qe(e.data,s,e.data.length):e.pictureData=e.data.subarray(s,e.data.length))))},"T*":function(e){e.data[0]===Ue&&(e.value=Fe(e.data,1,e.data.length).replace(/\0*$/,""),e.values=e.value.split("\0"))},TXXX:function(e){var t;e.data[0]===Ue&&-1!==(t=Ne(e.data,0,1))&&(e.description=Fe(e.data,1,t),e.value=Fe(e.data,t+1,e.data.length).replace(/\0*$/,""),e.data=e.value)},"W*":function(e){e.url=qe(e.data,0,e.data.length).replace(/\0.*$/,"")},WXXX:function(e){var t;e.data[0]===Ue&&-1!==(t=Ne(e.data,0,1))&&(e.description=Fe(e.data,1,t),e.url=qe(e.data,t+1,e.data.length).replace(/\0.*$/,""))},PRIV:function(e){var t;for(t=0;t<e.data.length;t++)if(0===e.data[t]){e.owner=qe(e.data,0,t);break}e.privateData=e.data.subarray(t+1),e.data=e.privateData}},$e={parseId3Frames:function(e){var t,i=10,s=0,r=[];if(!(e.length<10||e[0]!=="I".charCodeAt(0)||e[1]!=="D".charCodeAt(0)||e[2]!=="3".charCodeAt(0))){s=je(e.subarray(6,10)),s+=10,64&e[5]&&(i+=4,i+=je(e.subarray(10,14)),s-=je(e.subarray(16,20)));do{if((t=je(e.subarray(i+4,i+8)))<1)break;var n={id:String.fromCharCode(e[i],e[i+1],e[i+2],e[i+3]),data:e.subarray(i+10,i+t+10)};n.key=n.id,Ve[n.id]?Ve[n.id](n):"T"===n.id[0]?Ve["T*"](n):"W"===n.id[0]&&Ve["W*"](n),r.push(n),i+=10,i+=t}while(i<s);return r}},parseSyncSafeInteger:je,frameParsers:Ve},He=xe,ze=$e;(Oe=function(e){var t,i={descriptor:e&&e.descriptor},s=0,r=[],n=0;if(Oe.prototype.init.call(this),this.dispatchType=He.METADATA_STREAM_TYPE.toString(16),i.descriptor)for(t=0;t<i.descriptor.length;t++)this.dispatchType+=("00"+i.descriptor[t].toString(16)).slice(-2);this.push=function(e){var t,i,a,o,l;if("timed-metadata"===e.type)if(e.dataAlignmentIndicator&&(n=0,r.length=0),0===r.length&&(e.data.length<10||e.data[0]!=="I".charCodeAt(0)||e.data[1]!=="D".charCodeAt(0)||e.data[2]!=="3".charCodeAt(0)))this.trigger("log",{level:"warn",message:"Skipping unrecognized metadata packet"});else if(r.push(e),n+=e.data.byteLength,1===r.length&&(s=ze.parseSyncSafeInteger(e.data.subarray(6,10)),s+=10),!(n<s)){for(t={data:new Uint8Array(s),frames:[],pts:r[0].pts,dts:r[0].dts},l=0;l<s;)t.data.set(r[0].data.subarray(0,s-l),l),l+=r[0].data.byteLength,n-=r[0].data.byteLength,r.shift();i=10,64&t.data[5]&&(i+=4,i+=ze.parseSyncSafeInteger(t.data.subarray(10,14)),s-=ze.parseSyncSafeInteger(t.data.subarray(16,20)));do{if((a=ze.parseSyncSafeInteger(t.data.subarray(i+4,i+8)))<1){this.trigger("log",{level:"warn",message:"Malformed ID3 frame encountered. Skipping remaining metadata parsing."});break}if((o={id:String.fromCharCode(t.data[i],t.data[i+1],t.data[i+2],t.data[i+3]),data:t.data.subarray(i+10,i+a+10)}).key=o.id,ze.frameParsers[o.id]?ze.frameParsers[o.id](o):"T"===o.id[0]?ze.frameParsers["T*"](o):"W"===o.id[0]&&ze.frameParsers["W*"](o),"com.apple.streaming.transportStreamTimestamp"===o.owner){var d=o.data,u=(1&d[3])<<30|d[4]<<22|d[5]<<14|d[6]<<6|d[7]>>>2;u*=4,u+=3&d[7],o.timeStamp=u,void 0===t.pts&&void 0===t.dts&&(t.pts=o.timeStamp,t.dts=o.timeStamp),this.trigger("timestamp",o)}t.frames.push(o),i+=10,i+=a}while(i<s);this.trigger("data",t)}}}).prototype=new V;var We,Ge,Xe,Ke=Oe,Ye=V,Qe=Ie,Je=xe,Ze=Me.TimestampRolloverStream,et=188;(We=function(){var e=new Uint8Array(et),t=0;We.prototype.init.call(this),this.push=function(i){var s,r=0,n=et;for(t?((s=new Uint8Array(i.byteLength+t)).set(e.subarray(0,t)),s.set(i,t),t=0):s=i;n<s.byteLength;)71!==s[r]||71!==s[n]?(r++,n++):(this.trigger("data",s.subarray(r,n)),r+=et,n+=et);r<s.byteLength&&(e.set(s.subarray(r),0),t=s.byteLength-r)},this.flush=function(){t===et&&71===e[0]&&(this.trigger("data",e),t=0),this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.reset=function(){t=0,this.trigger("reset")}}).prototype=new Ye,Ge=function(){var e,t,i,s;Ge.prototype.init.call(this),s=this,this.packetsWaitingForPmt=[],this.programMapTable=void 0,e=function(e,s){var r=0;s.payloadUnitStartIndicator&&(r+=e[r]+1),"pat"===s.type?t(e.subarray(r),s):i(e.subarray(r),s)},t=function(e,t){t.section_number=e[7],t.last_section_number=e[8],s.pmtPid=(31&e[10])<<8|e[11],t.pmtPid=s.pmtPid},i=function(e,t){var i,r;if(1&e[5]){for(s.programMapTable={video:null,audio:null,"timed-metadata":{}},i=3+((15&e[1])<<8|e[2])-4,r=12+((15&e[10])<<8|e[11]);r<i;){var n=e[r],a=(31&e[r+1])<<8|e[r+2];n===Je.H264_STREAM_TYPE&&null===s.programMapTable.video?s.programMapTable.video=a:n===Je.ADTS_STREAM_TYPE&&null===s.programMapTable.audio?s.programMapTable.audio=a:n===Je.METADATA_STREAM_TYPE&&(s.programMapTable["timed-metadata"][a]=n),r+=5+((15&e[r+3])<<8|e[r+4])}t.programMapTable=s.programMapTable}},this.push=function(t){var i={},s=4;if(i.payloadUnitStartIndicator=!!(64&t[1]),i.pid=31&t[1],i.pid<<=8,i.pid|=t[2],(48&t[3])>>>4>1&&(s+=t[s]+1),0===i.pid)i.type="pat",e(t.subarray(s),i),this.trigger("data",i);else if(i.pid===this.pmtPid)for(i.type="pmt",e(t.subarray(s),i),this.trigger("data",i);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else void 0===this.programMapTable?this.packetsWaitingForPmt.push([t,s,i]):this.processPes_(t,s,i)},this.processPes_=function(e,t,i){i.pid===this.programMapTable.video?i.streamType=Je.H264_STREAM_TYPE:i.pid===this.programMapTable.audio?i.streamType=Je.ADTS_STREAM_TYPE:i.streamType=this.programMapTable["timed-metadata"][i.pid],i.type="pes",i.data=e.subarray(t),this.trigger("data",i)}},Ge.prototype=new Ye,Ge.STREAM_TYPES={h264:27,adts:15},Xe=function(){var e,t=this,i=!1,s={data:[],size:0},r={data:[],size:0},n={data:[],size:0},a=function(e,i,s){var r,n,a=new Uint8Array(e.size),o={type:i},l=0,d=0;if(e.data.length&&!(e.size<9)){for(o.trackId=e.data[0].pid,l=0;l<e.data.length;l++)n=e.data[l],a.set(n.data,d),d+=n.data.byteLength;!function(e,t){var i;const s=e[0]<<16|e[1]<<8|e[2];t.data=new Uint8Array,1===s&&(t.packetLength=6+(e[4]<<8|e[5]),t.dataAlignmentIndicator=!!(4&e[6]),192&(i=e[7])&&(t.pts=(14&e[9])<<27|(255&e[10])<<20|(254&e[11])<<12|(255&e[12])<<5|(254&e[13])>>>3,t.pts*=4,t.pts+=(6&e[13])>>>1,t.dts=t.pts,64&i&&(t.dts=(14&e[14])<<27|(255&e[15])<<20|(254&e[16])<<12|(255&e[17])<<5|(254&e[18])>>>3,t.dts*=4,t.dts+=(6&e[18])>>>1)),t.data=e.subarray(9+e[8]))}(a,o),r="video"===i||o.packetLength<=e.size,(s||r)&&(e.size=0,e.data.length=0),r&&t.trigger("data",o)}};Xe.prototype.init.call(this),this.push=function(o){({pat:function(){},pes:function(){var e,t;switch(o.streamType){case Je.H264_STREAM_TYPE:e=s,t="video";break;case Je.ADTS_STREAM_TYPE:e=r,t="audio";break;case Je.METADATA_STREAM_TYPE:e=n,t="timed-metadata";break;default:return}o.payloadUnitStartIndicator&&a(e,t,!0),e.data.push(o),e.size+=o.data.byteLength},pmt:function(){var s={type:"metadata",tracks:[]};null!==(e=o.programMapTable).video&&s.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.video,codec:"avc",type:"video"}),null!==e.audio&&s.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.audio,codec:"adts",type:"audio"}),i=!0,t.trigger("data",s)}})[o.type]()},this.reset=function(){s.size=0,s.data.length=0,r.size=0,r.data.length=0,this.trigger("reset")},this.flushStreams_=function(){a(s,"video"),a(r,"audio"),a(n,"timed-metadata")},this.flush=function(){if(!i&&e){var s={type:"metadata",tracks:[]};null!==e.video&&s.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.video,codec:"avc",type:"video"}),null!==e.audio&&s.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+e.audio,codec:"adts",type:"audio"}),t.trigger("data",s)}i=!1,this.flushStreams_(),this.trigger("done")}},Xe.prototype=new Ye;var tt={PAT_PID:0,MP2T_PACKET_LENGTH:et,TransportPacketStream:We,TransportParseStream:Ge,ElementaryStream:Xe,TimestampRolloverStream:Ze,CaptionStream:Qe.CaptionStream,Cea608Stream:Qe.Cea608Stream,Cea708Stream:Qe.Cea708Stream,MetadataStream:Ke};for(var it in Je)Je.hasOwnProperty(it)&&(tt[it]=Je[it]);var st,rt=tt,nt=oe.ONE_SECOND_IN_TS,at=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];(st=function(e){var t,i=0;st.prototype.init.call(this),this.skipWarn_=function(e,t){this.trigger("log",{level:"warn",message:`adts skiping bytes ${e} to ${t} in frame ${i} outside syncword`})},this.push=function(s){var r,n,a,o,l,d=0;if(e||(i=0),"audio"===s.type){var u;for(t&&t.length?(a=t,(t=new Uint8Array(a.byteLength+s.data.byteLength)).set(a),t.set(s.data,a.byteLength)):t=s.data;d+7<t.length;)if(255===t[d]&&240==(246&t[d+1])){if("number"==typeof u&&(this.skipWarn_(u,d),u=null),n=2*(1&~t[d+1]),r=(3&t[d+3])<<11|t[d+4]<<3|(224&t[d+5])>>5,l=(o=1024*(1+(3&t[d+6])))*nt/at[(60&t[d+2])>>>2],t.byteLength-d<r)break;this.trigger("data",{pts:s.pts+i*l,dts:s.dts+i*l,sampleCount:o,audioobjecttype:1+(t[d+2]>>>6&3),channelcount:(1&t[d+2])<<2|(192&t[d+3])>>>6,samplerate:at[(60&t[d+2])>>>2],samplingfrequencyindex:(60&t[d+2])>>>2,samplesize:16,data:t.subarray(d+7+n,d+r)}),i++,d+=r}else"number"!=typeof u&&(u=d),d++;"number"==typeof u&&(this.skipWarn_(u,d),u=null),t=t.subarray(d)}},this.flush=function(){i=0,this.trigger("done")},this.reset=function(){t=void 0,this.trigger("reset")},this.endTimeline=function(){t=void 0,this.trigger("endedtimeline")}}).prototype=new V;var ot,lt,dt,ut=st,ct=V,ht=function(e){var t=e.byteLength,i=0,s=0;this.length=function(){return 8*t},this.bitsAvailable=function(){return 8*t+s},this.loadWord=function(){var r=e.byteLength-t,n=new Uint8Array(4),a=Math.min(4,t);if(0===a)throw new Error("no bytes available");n.set(e.subarray(r,r+a)),i=new DataView(n.buffer).getUint32(0),s=8*a,t-=a},this.skipBits=function(e){var r;s>e?(i<<=e,s-=e):(e-=s,e-=8*(r=Math.floor(e/8)),t-=r,this.loadWord(),i<<=e,s-=e)},this.readBits=function(e){var r=Math.min(s,e),n=i>>>32-r;return(s-=r)>0?i<<=r:t>0&&this.loadWord(),(r=e-r)>0?n<<r|this.readBits(r):n},this.skipLeadingZeros=function(){var e;for(e=0;e<s;++e)if(i&2147483648>>>e)return i<<=e,s-=e,e;return this.loadWord(),e+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var e=this.skipLeadingZeros();return this.readBits(e+1)-1},this.readExpGolomb=function(){var e=this.readUnsignedExpGolomb();return 1&e?1+e>>>1:-1*(e>>>1)},this.readBoolean=function(){return 1===this.readBits(1)},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};(lt=function(){var e,t,i=0;lt.prototype.init.call(this),this.push=function(s){var r;t?((r=new Uint8Array(t.byteLength+s.data.byteLength)).set(t),r.set(s.data,t.byteLength),t=r):t=s.data;for(var n=t.byteLength;i<n-3;i++)if(1===t[i+2]){e=i+5;break}for(;e<n;)switch(t[e]){case 0:if(0!==t[e-1]){e+=2;break}if(0!==t[e-2]){e++;break}i+3!==e-2&&this.trigger("data",t.subarray(i+3,e-2));do{e++}while(1!==t[e]&&e<n);i=e-2,e+=3;break;case 1:if(0!==t[e-1]||0!==t[e-2]){e+=3;break}this.trigger("data",t.subarray(i+3,e-2)),i=e-2,e+=3;break;default:e+=3}t=t.subarray(i),e-=i,i=0},this.reset=function(){t=null,i=0,this.trigger("reset")},this.flush=function(){t&&t.byteLength>3&&this.trigger("data",t.subarray(i+3)),t=null,i=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}}).prototype=new ct,dt={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},ot=function(){var e,t,i,s,r,n,a,o=new lt;ot.prototype.init.call(this),e=this,this.push=function(e){"video"===e.type&&(t=e.trackId,i=e.pts,s=e.dts,o.push(e))},o.on("data",function(a){var o={trackId:t,pts:i,dts:s,data:a,nalUnitTypeCode:31&a[0]};switch(o.nalUnitTypeCode){case 5:o.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:o.nalUnitType="sei_rbsp",o.escapedRBSP=r(a.subarray(1));break;case 7:o.nalUnitType="seq_parameter_set_rbsp",o.escapedRBSP=r(a.subarray(1)),o.config=n(o.escapedRBSP);break;case 8:o.nalUnitType="pic_parameter_set_rbsp";break;case 9:o.nalUnitType="access_unit_delimiter_rbsp"}e.trigger("data",o)}),o.on("done",function(){e.trigger("done")}),o.on("partialdone",function(){e.trigger("partialdone")}),o.on("reset",function(){e.trigger("reset")}),o.on("endedtimeline",function(){e.trigger("endedtimeline")}),this.flush=function(){o.flush()},this.partialFlush=function(){o.partialFlush()},this.reset=function(){o.reset()},this.endTimeline=function(){o.endTimeline()},a=function(e,t){var i,s=8,r=8;for(i=0;i<e;i++)0!==r&&(r=(s+t.readExpGolomb()+256)%256),s=0===r?s:r},r=function(e){for(var t,i,s=e.byteLength,r=[],n=1;n<s-2;)0===e[n]&&0===e[n+1]&&3===e[n+2]?(r.push(n+2),n+=2):n++;if(0===r.length)return e;t=s-r.length,i=new Uint8Array(t);var a=0;for(n=0;n<t;a++,n++)a===r[0]&&(a++,r.shift()),i[n]=e[a];return i},n=function(e){var t,i,s,r,n,o,l,d,u,c,h,p,m=0,g=0,f=0,y=0,_=[1,1];if(i=(t=new ht(e)).readUnsignedByte(),r=t.readUnsignedByte(),s=t.readUnsignedByte(),t.skipUnsignedExpGolomb(),dt[i]&&(3===(n=t.readUnsignedExpGolomb())&&t.skipBits(1),t.skipUnsignedExpGolomb(),t.skipUnsignedExpGolomb(),t.skipBits(1),t.readBoolean()))for(h=3!==n?8:12,p=0;p<h;p++)t.readBoolean()&&a(p<6?16:64,t);if(t.skipUnsignedExpGolomb(),0===(o=t.readUnsignedExpGolomb()))t.readUnsignedExpGolomb();else if(1===o)for(t.skipBits(1),t.skipExpGolomb(),t.skipExpGolomb(),l=t.readUnsignedExpGolomb(),p=0;p<l;p++)t.skipExpGolomb();if(t.skipUnsignedExpGolomb(),t.skipBits(1),d=t.readUnsignedExpGolomb(),u=t.readUnsignedExpGolomb(),0===(c=t.readBits(1))&&t.skipBits(1),t.skipBits(1),t.readBoolean()&&(m=t.readUnsignedExpGolomb(),g=t.readUnsignedExpGolomb(),f=t.readUnsignedExpGolomb(),y=t.readUnsignedExpGolomb()),t.readBoolean()&&t.readBoolean()){switch(t.readUnsignedByte()){case 1:_=[1,1];break;case 2:_=[12,11];break;case 3:_=[10,11];break;case 4:_=[16,11];break;case 5:_=[40,33];break;case 6:_=[24,11];break;case 7:_=[20,11];break;case 8:_=[32,11];break;case 9:_=[80,33];break;case 10:_=[18,11];break;case 11:_=[15,11];break;case 12:_=[64,33];break;case 13:_=[160,99];break;case 14:_=[4,3];break;case 15:_=[3,2];break;case 16:_=[2,1];break;case 255:_=[t.readUnsignedByte()<<8|t.readUnsignedByte(),t.readUnsignedByte()<<8|t.readUnsignedByte()]}_&&(_[0],_[1])}return{profileIdc:i,levelIdc:s,profileCompatibility:r,width:16*(d+1)-2*m-2*g,height:(2-c)*(u+1)*16-2*f-2*y,sarRatio:_}}},ot.prototype=new ct;var pt,mt={H264Stream:ot},gt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ft=function(e,t){var i=e[t+6]<<21|e[t+7]<<14|e[t+8]<<7|e[t+9];return i=i>=0?i:0,(16&e[t+5])>>4?i+20:i+10},yt=function(e,t){return e.length-t<10||e[t]!=="I".charCodeAt(0)||e[t+1]!=="D".charCodeAt(0)||e[t+2]!=="3".charCodeAt(0)?t:(t+=ft(e,t),yt(e,t))},_t=function(e){return e[0]<<21|e[1]<<14|e[2]<<7|e[3]},bt=function(e,t,i){return unescape(function(e,t,i){var s,r="";for(s=t;s<i;s++)r+="%"+("00"+e[s].toString(16)).slice(-2);return r}(e,t,i))},vt={isLikelyAacData:function(e){var t=yt(e,0);return e.length>=t+2&&!(255&~e[t])&&!(240&~e[t+1])&&16==(22&e[t+1])},parseId3TagSize:ft,parseAdtsSize:function(e,t){var i=(224&e[t+5])>>5,s=e[t+4]<<3;return 6144&e[t+3]|s|i},parseType:function(e,t){return e[t]==="I".charCodeAt(0)&&e[t+1]==="D".charCodeAt(0)&&e[t+2]==="3".charCodeAt(0)?"timed-metadata":!0&e[t]&&!(240&~e[t+1])?"audio":null},parseSampleRate:function(e){for(var t=0;t+5<e.length;){if(255===e[t]&&240==(246&e[t+1]))return gt[(60&e[t+2])>>>2];t++}return null},parseAacTimestamp:function(e){var t,i,s;t=10,64&e[5]&&(t+=4,t+=_t(e.subarray(10,14)));do{if((i=_t(e.subarray(t+4,t+8)))<1)return null;if("PRIV"===String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3])){s=e.subarray(t+10,t+i+10);for(var r=0;r<s.byteLength;r++)if(0===s[r]){if("com.apple.streaming.transportStreamTimestamp"===bt(s,0,r)){var n=s.subarray(r+1),a=(1&n[3])<<30|n[4]<<22|n[5]<<14|n[6]<<6|n[7]>>>2;return a*=4,a+=3&n[7]}break}}t+=10,t+=i}while(t<e.byteLength);return null}},Tt=vt;(pt=function(){var e=new Uint8Array,t=0;pt.prototype.init.call(this),this.setTimestamp=function(e){t=e},this.push=function(i){var s,r,n,a,o=0,l=0;for(e.length?(a=e.length,(e=new Uint8Array(i.byteLength+a)).set(e.subarray(0,a)),e.set(i,a)):e=i;e.length-l>=3;)if(e[l]!=="I".charCodeAt(0)||e[l+1]!=="D".charCodeAt(0)||e[l+2]!=="3".charCodeAt(0))if(255&~e[l]||240&~e[l+1])l++;else{if(e.length-l<7)break;if(l+(o=Tt.parseAdtsSize(e,l))>e.length)break;n={type:"audio",data:e.subarray(l,l+o),pts:t,dts:t},this.trigger("data",n),l+=o}else{if(e.length-l<10)break;if(l+(o=Tt.parseId3TagSize(e,l))>e.length)break;r={type:"timed-metadata",data:e.subarray(l,l+o)},this.trigger("data",r),l+=o}s=e.length-l,e=s>0?e.subarray(l):new Uint8Array},this.reset=function(){e=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){e=new Uint8Array,this.trigger("endedtimeline")}}).prototype=new V;var St,Et,wt,kt,Ct=V,It=ee,xt=ie,At=ue,Dt=he,Pt=rt,Lt=oe,Ot=ut,Mt=mt.H264Stream,Rt=pt,Nt=vt.isLikelyAacData,Ut=oe.ONE_SECOND_IN_TS,Bt=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],Ft=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],qt=function(e,t){t.stream=e,this.trigger("log",t)},jt=function(e,t){for(var i=Object.keys(t),s=0;s<i.length;s++){var r=i[s];"headOfPipeline"!==r&&t[r].on&&t[r].on("log",qt.bind(e,r))}},Vt=function(e,t){var i;if(e.length!==t.length)return!1;for(i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0},$t=function(e,t,i,s,r,n){return{start:{dts:e,pts:e+(i-t)},end:{dts:e+(s-t),pts:e+(r-i)},prependedContentDuration:n,baseMediaDecodeTime:e}};Et=function(e,t){var i,s=[],r=0,n=0,a=1/0;i=(t=t||{}).firstSequenceNumber||0,Et.prototype.init.call(this),this.push=function(t){Dt.collectDtsInfo(e,t),e&&Bt.forEach(function(i){e[i]=t[i]}),s.push(t)},this.setEarliestDts=function(e){r=e},this.setVideoBaseMediaDecodeTime=function(e){a=e},this.setAudioAppendStart=function(e){n=e},this.flush=function(){var o,l,d,u,c,h,p;0!==s.length?(o=At.trimAdtsFramesByEarliestDts(s,e,r),e.baseMediaDecodeTime=Dt.calculateTrackBaseMediaDecodeTime(e,t.keepOriginalTimestamps),p=At.prefixWithSilence(e,o,n,a),e.samples=At.generateSampleTable(o),d=It.mdat(At.concatenateFrameData(o)),s=[],l=It.moof(i,[e]),u=new Uint8Array(l.byteLength+d.byteLength),i++,u.set(l),u.set(d,l.byteLength),Dt.clearDtsInfo(e),c=Math.ceil(1024*Ut/e.samplerate),o.length&&(h=o.length*c,this.trigger("segmentTimingInfo",$t(Lt.audioTsToVideoTs(e.baseMediaDecodeTime,e.samplerate),o[0].dts,o[0].pts,o[0].dts+h,o[0].pts+h,p||0)),this.trigger("timingInfo",{start:o[0].pts,end:o[0].pts+h})),this.trigger("data",{track:e,boxes:u}),this.trigger("done","AudioSegmentStream")):this.trigger("done","AudioSegmentStream")},this.reset=function(){Dt.clearDtsInfo(e),s=[],this.trigger("reset")}},Et.prototype=new Ct,St=function(e,t){var i,s,r,n=[],a=[];i=(t=t||{}).firstSequenceNumber||0,St.prototype.init.call(this),delete e.minPTS,this.gopCache_=[],this.push=function(t){Dt.collectDtsInfo(e,t),"seq_parameter_set_rbsp"!==t.nalUnitType||s||(s=t.config,e.sps=[t.data],Ft.forEach(function(t){e[t]=s[t]},this)),"pic_parameter_set_rbsp"!==t.nalUnitType||r||(r=t.data,e.pps=[t.data]),n.push(t)},this.flush=function(){for(var s,r,o,l,d,u,c,h,p=0;n.length&&"access_unit_delimiter_rbsp"!==n[0].nalUnitType;)n.shift();if(0===n.length)return this.resetStream_(),void this.trigger("done","VideoSegmentStream");if(s=xt.groupNalsIntoFrames(n),(o=xt.groupFramesIntoGops(s))[0][0].keyFrame||((r=this.getGopForFusion_(n[0],e))?(p=r.duration,o.unshift(r),o.byteLength+=r.byteLength,o.nalCount+=r.nalCount,o.pts=r.pts,o.dts=r.dts,o.duration+=r.duration):o=xt.extendFirstKeyFrame(o)),a.length){var m;if(!(m=t.alignGopsAtEnd?this.alignGopsAtEnd_(o):this.alignGopsAtStart_(o)))return this.gopCache_.unshift({gop:o.pop(),pps:e.pps,sps:e.sps}),this.gopCache_.length=Math.min(6,this.gopCache_.length),n=[],this.resetStream_(),void this.trigger("done","VideoSegmentStream");Dt.clearDtsInfo(e),o=m}Dt.collectDtsInfo(e,o),e.samples=xt.generateSampleTable(o),d=It.mdat(xt.concatenateNalData(o)),e.baseMediaDecodeTime=Dt.calculateTrackBaseMediaDecodeTime(e,t.keepOriginalTimestamps),this.trigger("processedGopsInfo",o.map(function(e){return{pts:e.pts,dts:e.dts,byteLength:e.byteLength}})),c=o[0],h=o[o.length-1],this.trigger("segmentTimingInfo",$t(e.baseMediaDecodeTime,c.dts,c.pts,h.dts+h.duration,h.pts+h.duration,p)),this.trigger("timingInfo",{start:o[0].pts,end:o[o.length-1].pts+o[o.length-1].duration}),this.gopCache_.unshift({gop:o.pop(),pps:e.pps,sps:e.sps}),this.gopCache_.length=Math.min(6,this.gopCache_.length),n=[],this.trigger("baseMediaDecodeTime",e.baseMediaDecodeTime),this.trigger("timelineStartInfo",e.timelineStartInfo),l=It.moof(i,[e]),u=new Uint8Array(l.byteLength+d.byteLength),i++,u.set(l),u.set(d,l.byteLength),this.trigger("data",{track:e,boxes:u}),this.resetStream_(),this.trigger("done","VideoSegmentStream")},this.reset=function(){this.resetStream_(),n=[],this.gopCache_.length=0,a.length=0,this.trigger("reset")},this.resetStream_=function(){Dt.clearDtsInfo(e),s=void 0,r=void 0},this.getGopForFusion_=function(t){var i,s,r,n,a,o=1/0;for(a=0;a<this.gopCache_.length;a++)r=(n=this.gopCache_[a]).gop,e.pps&&Vt(e.pps[0],n.pps[0])&&e.sps&&Vt(e.sps[0],n.sps[0])&&(r.dts<e.timelineStartInfo.dts||(i=t.dts-r.dts-r.duration)>=-1e4&&i<=45e3&&(!s||o>i)&&(s=n,o=i));return s?s.gop:null},this.alignGopsAtStart_=function(e){var t,i,s,r,n,o,l,d;for(n=e.byteLength,o=e.nalCount,l=e.duration,t=i=0;t<a.length&&i<e.length&&(s=a[t],r=e[i],s.pts!==r.pts);)r.pts>s.pts?t++:(i++,n-=r.byteLength,o-=r.nalCount,l-=r.duration);return 0===i?e:i===e.length?null:((d=e.slice(i)).byteLength=n,d.duration=l,d.nalCount=o,d.pts=d[0].pts,d.dts=d[0].dts,d)},this.alignGopsAtEnd_=function(e){var t,i,s,r,n,o,l;for(t=a.length-1,i=e.length-1,n=null,o=!1;t>=0&&i>=0;){if(s=a[t],r=e[i],s.pts===r.pts){o=!0;break}s.pts>r.pts?t--:(t===a.length-1&&(n=i),i--)}if(!o&&null===n)return null;if(0===(l=o?i:n))return e;var d=e.slice(l),u=d.reduce(function(e,t){return e.byteLength+=t.byteLength,e.duration+=t.duration,e.nalCount+=t.nalCount,e},{byteLength:0,duration:0,nalCount:0});return d.byteLength=u.byteLength,d.duration=u.duration,d.nalCount=u.nalCount,d.pts=d[0].pts,d.dts=d[0].dts,d},this.alignGopsWith=function(e){a=e}},St.prototype=new Ct,kt=function(e,t){this.numberOfTracks=0,this.metadataStream=t,void 0!==(e=e||{}).remux?this.remuxTracks=!!e.remux:this.remuxTracks=!0,"boolean"==typeof e.keepOriginalTimestamps?this.keepOriginalTimestamps=e.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,kt.prototype.init.call(this),this.push=function(e){return e.content||e.text?this.pendingCaptions.push(e):e.frames?this.pendingMetadata.push(e):(this.pendingTracks.push(e.track),this.pendingBytes+=e.boxes.byteLength,"video"===e.track.type&&(this.videoTrack=e.track,this.pendingBoxes.push(e.boxes)),void("audio"===e.track.type&&(this.audioTrack=e.track,this.pendingBoxes.unshift(e.boxes))))}},kt.prototype=new Ct,kt.prototype.flush=function(e){var t,i,s,r,n=0,a={captions:[],captionStreams:{},metadata:[],info:{}},o=0;if(this.pendingTracks.length<this.numberOfTracks){if("VideoSegmentStream"!==e&&"AudioSegmentStream"!==e)return;if(this.remuxTracks)return;if(0===this.pendingTracks.length)return this.emittedTracks++,void(this.emittedTracks>=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0))}if(this.videoTrack?(o=this.videoTrack.timelineStartInfo.pts,Ft.forEach(function(e){a.info[e]=this.videoTrack[e]},this)):this.audioTrack&&(o=this.audioTrack.timelineStartInfo.pts,Bt.forEach(function(e){a.info[e]=this.audioTrack[e]},this)),this.videoTrack||this.audioTrack){for(1===this.pendingTracks.length?a.type=this.pendingTracks[0].type:a.type="combined",this.emittedTracks+=this.pendingTracks.length,s=It.initSegment(this.pendingTracks),a.initSegment=new Uint8Array(s.byteLength),a.initSegment.set(s),a.data=new Uint8Array(this.pendingBytes),r=0;r<this.pendingBoxes.length;r++)a.data.set(this.pendingBoxes[r],n),n+=this.pendingBoxes[r].byteLength;for(r=0;r<this.pendingCaptions.length;r++)(t=this.pendingCaptions[r]).startTime=Lt.metadataTsToSeconds(t.startPts,o,this.keepOriginalTimestamps),t.endTime=Lt.metadataTsToSeconds(t.endPts,o,this.keepOriginalTimestamps),a.captionStreams[t.stream]=!0,a.captions.push(t);for(r=0;r<this.pendingMetadata.length;r++)(i=this.pendingMetadata[r]).cueTime=Lt.metadataTsToSeconds(i.pts,o,this.keepOriginalTimestamps),a.metadata.push(i);for(a.metadata.dispatchType=this.metadataStream.dispatchType,this.pendingTracks.length=0,this.videoTrack=null,this.pendingBoxes.length=0,this.pendingCaptions.length=0,this.pendingBytes=0,this.pendingMetadata.length=0,this.trigger("data",a),r=0;r<a.captions.length;r++)t=a.captions[r],this.trigger("caption",t);for(r=0;r<a.metadata.length;r++)i=a.metadata[r],this.trigger("id3Frame",i)}this.emittedTracks>=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},kt.prototype.setRemux=function(e){this.remuxTracks=e},(wt=function(e){var t,i,s=this,r=!0;wt.prototype.init.call(this),e=e||{},this.baseMediaDecodeTime=e.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var r={};this.transmuxPipeline_=r,r.type="aac",r.metadataStream=new Pt.MetadataStream,r.aacStream=new Rt,r.audioTimestampRolloverStream=new Pt.TimestampRolloverStream("audio"),r.timedMetadataTimestampRolloverStream=new Pt.TimestampRolloverStream("timed-metadata"),r.adtsStream=new Ot,r.coalesceStream=new kt(e,r.metadataStream),r.headOfPipeline=r.aacStream,r.aacStream.pipe(r.audioTimestampRolloverStream).pipe(r.adtsStream),r.aacStream.pipe(r.timedMetadataTimestampRolloverStream).pipe(r.metadataStream).pipe(r.coalesceStream),r.metadataStream.on("timestamp",function(e){r.aacStream.setTimestamp(e.timeStamp)}),r.aacStream.on("data",function(n){"timed-metadata"!==n.type&&"audio"!==n.type||r.audioSegmentStream||(i=i||{timelineStartInfo:{baseMediaDecodeTime:s.baseMediaDecodeTime},codec:"adts",type:"audio"},r.coalesceStream.numberOfTracks++,r.audioSegmentStream=new Et(i,e),r.audioSegmentStream.on("log",s.getLogTrigger_("audioSegmentStream")),r.audioSegmentStream.on("timingInfo",s.trigger.bind(s,"audioTimingInfo")),r.adtsStream.pipe(r.audioSegmentStream).pipe(r.coalesceStream),s.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!t}))}),r.coalesceStream.on("data",this.trigger.bind(this,"data")),r.coalesceStream.on("done",this.trigger.bind(this,"done")),jt(this,r)},this.setupTsPipeline=function(){var r={};this.transmuxPipeline_=r,r.type="ts",r.metadataStream=new Pt.MetadataStream,r.packetStream=new Pt.TransportPacketStream,r.parseStream=new Pt.TransportParseStream,r.elementaryStream=new Pt.ElementaryStream,r.timestampRolloverStream=new Pt.TimestampRolloverStream,r.adtsStream=new Ot,r.h264Stream=new Mt,r.captionStream=new Pt.CaptionStream(e),r.coalesceStream=new kt(e,r.metadataStream),r.headOfPipeline=r.packetStream,r.packetStream.pipe(r.parseStream).pipe(r.elementaryStream).pipe(r.timestampRolloverStream),r.timestampRolloverStream.pipe(r.h264Stream),r.timestampRolloverStream.pipe(r.adtsStream),r.timestampRolloverStream.pipe(r.metadataStream).pipe(r.coalesceStream),r.h264Stream.pipe(r.captionStream).pipe(r.coalesceStream),r.elementaryStream.on("data",function(n){var a;if("metadata"===n.type){for(a=n.tracks.length;a--;)t||"video"!==n.tracks[a].type?i||"audio"!==n.tracks[a].type||((i=n.tracks[a]).timelineStartInfo.baseMediaDecodeTime=s.baseMediaDecodeTime):(t=n.tracks[a]).timelineStartInfo.baseMediaDecodeTime=s.baseMediaDecodeTime;t&&!r.videoSegmentStream&&(r.coalesceStream.numberOfTracks++,r.videoSegmentStream=new St(t,e),r.videoSegmentStream.on("log",s.getLogTrigger_("videoSegmentStream")),r.videoSegmentStream.on("timelineStartInfo",function(t){i&&!e.keepOriginalTimestamps&&(i.timelineStartInfo=t,r.audioSegmentStream.setEarliestDts(t.dts-s.baseMediaDecodeTime))}),r.videoSegmentStream.on("processedGopsInfo",s.trigger.bind(s,"gopInfo")),r.videoSegmentStream.on("segmentTimingInfo",s.trigger.bind(s,"videoSegmentTimingInfo")),r.videoSegmentStream.on("baseMediaDecodeTime",function(e){i&&r.audioSegmentStream.setVideoBaseMediaDecodeTime(e)}),r.videoSegmentStream.on("timingInfo",s.trigger.bind(s,"videoTimingInfo")),r.h264Stream.pipe(r.videoSegmentStream).pipe(r.coalesceStream)),i&&!r.audioSegmentStream&&(r.coalesceStream.numberOfTracks++,r.audioSegmentStream=new Et(i,e),r.audioSegmentStream.on("log",s.getLogTrigger_("audioSegmentStream")),r.audioSegmentStream.on("timingInfo",s.trigger.bind(s,"audioTimingInfo")),r.audioSegmentStream.on("segmentTimingInfo",s.trigger.bind(s,"audioSegmentTimingInfo")),r.adtsStream.pipe(r.audioSegmentStream).pipe(r.coalesceStream)),s.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!t})}}),r.coalesceStream.on("data",this.trigger.bind(this,"data")),r.coalesceStream.on("id3Frame",function(e){e.dispatchType=r.metadataStream.dispatchType,s.trigger("id3Frame",e)}),r.coalesceStream.on("caption",this.trigger.bind(this,"caption")),r.coalesceStream.on("done",this.trigger.bind(this,"done")),jt(this,r)},this.setBaseMediaDecodeTime=function(s){var r=this.transmuxPipeline_;e.keepOriginalTimestamps||(this.baseMediaDecodeTime=s),i&&(i.timelineStartInfo.dts=void 0,i.timelineStartInfo.pts=void 0,Dt.clearDtsInfo(i),r.audioTimestampRolloverStream&&r.audioTimestampRolloverStream.discontinuity()),t&&(r.videoSegmentStream&&(r.videoSegmentStream.gopCache_=[]),t.timelineStartInfo.dts=void 0,t.timelineStartInfo.pts=void 0,Dt.clearDtsInfo(t),r.captionStream.reset()),r.timestampRolloverStream&&r.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(e){i&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(e)},this.setRemux=function(t){var i=this.transmuxPipeline_;e.remux=t,i&&i.coalesceStream&&i.coalesceStream.setRemux(t)},this.alignGopsWith=function(e){t&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(e)},this.getLogTrigger_=function(e){var t=this;return function(i){i.stream=e,t.trigger("log",i)}},this.push=function(e){if(r){var t=Nt(e);t&&"aac"!==this.transmuxPipeline_.type?this.setupAacPipeline():t||"ts"===this.transmuxPipeline_.type||this.setupTsPipeline(),r=!1}this.transmuxPipeline_.headOfPipeline.push(e)},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()}}).prototype=new Ct;var Ht,zt,Wt,Gt,Xt,Kt,Yt,Qt={Transmuxer:wt},Jt=function(e){return e>>>0},Zt=function(e){var t="";return t+=String.fromCharCode(e[0]),t+=String.fromCharCode(e[1]),t+=String.fromCharCode(e[2]),t+=String.fromCharCode(e[3])},ei=Jt,ti=Zt,ii=function(e,t){var i,s,r,n,a,o=[];if(!t.length)return null;for(i=0;i<e.byteLength;)s=ei(e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]),r=ti(e.subarray(i+4,i+8)),n=s>1?i+s:e.byteLength,r===t[0]&&(1===t.length?o.push(e.subarray(i+8,n)):(a=ii(e.subarray(i+8,n),t.slice(1))).length&&(o=o.concat(a))),i=n;return o},si=ii,ri=Jt,ni=H.getUint64,ai=function(e){var t={version:e[0],flags:new Uint8Array(e.subarray(1,4))};return 1===t.version?t.baseMediaDecodeTime=ni(e.subarray(4)):t.baseMediaDecodeTime=ri(e[4]<<24|e[5]<<16|e[6]<<8|e[7]),t},oi=function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),s={version:e[0],flags:new Uint8Array(e.subarray(1,4)),trackId:i.getUint32(4)},r=1&s.flags[2],n=2&s.flags[2],a=8&s.flags[2],o=16&s.flags[2],l=32&s.flags[2],d=65536&s.flags[0],u=131072&s.flags[0];return t=8,r&&(t+=4,s.baseDataOffset=i.getUint32(12),t+=4),n&&(s.sampleDescriptionIndex=i.getUint32(t),t+=4),a&&(s.defaultSampleDuration=i.getUint32(t),t+=4),o&&(s.defaultSampleSize=i.getUint32(t),t+=4),l&&(s.defaultSampleFlags=i.getUint32(t)),d&&(s.durationIsEmpty=!0),!r&&u&&(s.baseDataOffsetIsMoof=!0),s},li=function(e){return{isLeading:(12&e[0])>>>2,dependsOn:3&e[0],isDependedOn:(192&e[1])>>>6,hasRedundancy:(48&e[1])>>>4,paddingValue:(14&e[1])>>>1,isNonSyncSample:1&e[1],degradationPriority:e[2]<<8|e[3]}},di=function(e){var t,i={version:e[0],flags:new Uint8Array(e.subarray(1,4)),samples:[]},s=new DataView(e.buffer,e.byteOffset,e.byteLength),r=1&i.flags[2],n=4&i.flags[2],a=1&i.flags[1],o=2&i.flags[1],l=4&i.flags[1],d=8&i.flags[1],u=s.getUint32(4),c=8;for(r&&(i.dataOffset=s.getInt32(c),c+=4),n&&u&&(t={flags:li(e.subarray(c,c+4))},c+=4,a&&(t.duration=s.getUint32(c),c+=4),o&&(t.size=s.getUint32(c),c+=4),d&&(1===i.version?t.compositionTimeOffset=s.getInt32(c):t.compositionTimeOffset=s.getUint32(c),c+=4),i.samples.push(t),u--);u--;)t={},a&&(t.duration=s.getUint32(c),c+=4),o&&(t.size=s.getUint32(c),c+=4),l&&(t.flags=li(e.subarray(c,c+4)),c+=4),d&&(1===i.version?t.compositionTimeOffset=s.getInt32(c):t.compositionTimeOffset=s.getUint32(c),c+=4),i.samples.push(t);return i},ui={tfdt:ai,trun:di},ci={parseTfdt:ui.tfdt,parseTrun:ui.trun},hi=function(e){for(var t=0,i=String.fromCharCode(e[t]),s="";"\0"!==i;)s+=i,t++,i=String.fromCharCode(e[t]);return s+=i},pi=H.getUint64,mi=function(e,t){var i="\0"!==t.scheme_id_uri,s=0===e&&gi(t.presentation_time_delta)&&i,r=1===e&&gi(t.presentation_time)&&i;return!(e>1)&&s||r},gi=function(e){return void 0!==e||null!==e},fi={parseEmsgBox:function(e){var t,i,s,r,n,a,o,l=4,d=e[0];if(0===d)l+=(t=hi(e.subarray(l))).length,l+=(i=hi(e.subarray(l))).length,s=(u=new DataView(e.buffer)).getUint32(l),l+=4,n=u.getUint32(l),l+=4,a=u.getUint32(l),l+=4,o=u.getUint32(l),l+=4;else if(1===d){var u;s=(u=new DataView(e.buffer)).getUint32(l),l+=4,r=pi(e.subarray(l)),l+=8,a=u.getUint32(l),l+=4,o=u.getUint32(l),l+=4,l+=(t=hi(e.subarray(l))).length,l+=(i=hi(e.subarray(l))).length}var c={scheme_id_uri:t,value:i,timescale:s||1,presentation_time:r,presentation_time_delta:n,event_duration:a,id:o,message_data:new Uint8Array(e.subarray(l,e.byteLength))};return mi(d,c)?c:void 0},scaleTime:function(e,t,i,s){return e||0===e?e/t:s+i/t}},yi="undefined"!=typeof window?window:void 0!==e?e:"undefined"!=typeof self?self:{},_i=Jt,bi=function(e){return("00"+e.toString(16)).slice(-2)},vi=si,Ti=Zt,Si=fi,Ei=oi,wi=di,ki=ai,Ci=H.getUint64,Ii=yi,xi=$e.parseId3Frames;Ht=function(e){return vi(e,["moov","trak"]).reduce(function(e,t){var i,s,r,n,a;return(i=vi(t,["tkhd"])[0])?(s=i[0],n=_i(i[r=0===s?12:20]<<24|i[r+1]<<16|i[r+2]<<8|i[r+3]),(a=vi(t,["mdia","mdhd"])[0])?(r=0===(s=a[0])?12:20,e[n]=_i(a[r]<<24|a[r+1]<<16|a[r+2]<<8|a[r+3]),e):null):null},{})},zt=function(e,t){var i=vi(t,["moof","traf"]).reduce(function(t,i){var s,r=vi(i,["tfhd"])[0],n=_i(r[4]<<24|r[5]<<16|r[6]<<8|r[7]),a=e[n]||9e4,o=vi(i,["tfdt"])[0],l=new DataView(o.buffer,o.byteOffset,o.byteLength);let d;return"bigint"==typeof(s=1===o[0]?Ci(o.subarray(4,12)):l.getUint32(4))?d=s/Ii.BigInt(a):"number"!=typeof s||isNaN(s)||(d=s/a),d<Number.MAX_SAFE_INTEGER&&(d=Number(d)),d<t&&(t=d),t},1/0);return"bigint"==typeof i||isFinite(i)?i:0},Wt=function(e,t){var i,s=vi(t,["moof","traf"]),r=0,n=0;if(s&&s.length){var a=vi(s[0],["tfhd"])[0],o=vi(s[0],["trun"])[0],l=vi(s[0],["tfdt"])[0];if(a)i=Ei(a).trackId;if(l)r=ki(l).baseMediaDecodeTime;if(o){var d=wi(o);d.samples&&d.samples.length&&(n=d.samples[0].compositionTimeOffset||0)}}var u=e[i]||9e4;"bigint"==typeof r&&(n=Ii.BigInt(n),u=Ii.BigInt(u));var c=(r+n)/u;return"bigint"==typeof c&&c<Number.MAX_SAFE_INTEGER&&(c=Number(c)),c},Gt=function(e){var t=vi(e,["moov","trak"]),i=[];return t.forEach(function(e){var t=vi(e,["mdia","hdlr"]),s=vi(e,["tkhd"]);t.forEach(function(e,t){var r,n,a=Ti(e.subarray(8,12)),o=s[t];"vide"===a&&(n=0===(r=new DataView(o.buffer,o.byteOffset,o.byteLength)).getUint8(0)?r.getUint32(12):r.getUint32(20),i.push(n))})}),i},Kt=function(e){var t=0===e[0]?12:20;return _i(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])},Xt=function(e){var t=vi(e,["moov","trak"]),i=[];return t.forEach(function(e){var t,s,r={},n=vi(e,["tkhd"])[0];n&&(s=(t=new DataView(n.buffer,n.byteOffset,n.byteLength)).getUint8(0),r.id=0===s?t.getUint32(12):t.getUint32(20));var a=vi(e,["mdia","hdlr"])[0];if(a){var o=Ti(a.subarray(8,12));r.type="vide"===o?"video":"soun"===o?"audio":o}var l=vi(e,["mdia","minf","stbl","stsd"])[0];if(l){var d=l.subarray(8);r.codec=Ti(d.subarray(4,8));var u,c=vi(d,[r.codec])[0];c&&(/^[asm]vc[1-9]$/i.test(r.codec)?(u=c.subarray(78),"avcC"===Ti(u.subarray(4,8))&&u.length>11?(r.codec+=".",r.codec+=bi(u[9]),r.codec+=bi(u[10]),r.codec+=bi(u[11])):r.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(r.codec)?(u=c.subarray(28),"esds"===Ti(u.subarray(4,8))&&u.length>20&&0!==u[19]?(r.codec+="."+bi(u[19]),r.codec+="."+bi(u[20]>>>2&63).replace(/^0/,"")):r.codec="mp4a.40.2"):r.codec=r.codec.toLowerCase())}var h=vi(e,["mdia","mdhd"])[0];h&&(r.timescale=Kt(h)),i.push(r)}),i},Yt=function(e,t=0){return vi(e,["emsg"]).map(e=>{var i=Si.parseEmsgBox(new Uint8Array(e)),s=xi(i.message_data);return{cueTime:Si.scaleTime(i.presentation_time,i.timescale,i.presentation_time_delta,t),duration:Si.scaleTime(i.event_duration,i.timescale),frames:s}})};var Ai={findBox:vi,parseType:Ti,timescale:Ht,startTime:zt,compositionStartTime:Wt,videoTrackIds:Gt,tracks:Xt,getTimescaleFromMediaHeader:Kt,getEmsgID3:Yt};const{parseTrun:Di}=ci,{findBox:Pi}=Ai;var Li=yi,Oi={getMdatTrafPairs:function(e){var t=Pi(e,["moof","traf"]),i=Pi(e,["mdat"]),s=[];return i.forEach(function(e,i){var r=t[i];s.push({mdat:e,traf:r})}),s},parseSamples:function(e,t,i){var s=t,r=i.defaultSampleDuration||0,n=i.defaultSampleSize||0,a=i.trackId,o=[];return e.forEach(function(e){var t=Di(e).samples;t.forEach(function(e){void 0===e.duration&&(e.duration=r),void 0===e.size&&(e.size=n),e.trackId=a,e.dts=s,void 0===e.compositionTimeOffset&&(e.compositionTimeOffset=0),"bigint"==typeof s?(e.pts=s+Li.BigInt(e.compositionTimeOffset),s+=Li.BigInt(e.duration)):(e.pts=s+e.compositionTimeOffset,s+=e.duration)}),o=o.concat(t)}),o}},Mi=pe.discardEmulationPreventionBytes,Ri=Ie.CaptionStream,Ni=si,Ui=ai,Bi=oi,{getMdatTrafPairs:Fi,parseSamples:qi}=Oi,ji=function(e,t){for(var i=e,s=0;s<t.length;s++){var r=t[s];if(i<r.size)return r;i-=r.size}return null},Vi=function(e,t){var i={};return Fi(e).forEach(function(e){var s,r=e.mdat,n=e.traf,a=Ni(n,["tfhd"]),o=Bi(a[0]),l=o.trackId,d=Ni(n,["tfdt"]),u=d.length>0?Ui(d[0]).baseMediaDecodeTime:0,c=Ni(n,["trun"]);t===l&&c.length>0&&(s=function(e,t,i){var s,r,n,a,o=new DataView(e.buffer,e.byteOffset,e.byteLength),l={logs:[],seiNals:[]};for(r=0;r+4<e.length;r+=n)if(n=o.getUint32(r),r+=4,!(n<=0))switch(31&e[r]){case 6:var d=e.subarray(r+1,r+1+n),u=ji(r,t);if(s={nalUnitType:"sei_rbsp",size:n,data:d,escapedRBSP:Mi(d),trackId:i},u)s.pts=u.pts,s.dts=u.dts,a=u;else{if(!a){l.logs.push({level:"warn",message:"We've encountered a nal unit without data at "+r+" for trackId "+i+". See mux.js#223."});break}s.pts=a.pts,s.dts=a.dts}l.seiNals.push(s)}return l}(r,qi(c,u,o),l),i[l]||(i[l]={seiNals:[],logs:[]}),i[l].seiNals=i[l].seiNals.concat(s.seiNals),i[l].logs=i[l].logs.concat(s.logs))}),i},$i=function(){var e,t,i,s,r,n,a=!1;this.isInitialized=function(){return a},this.init=function(t){e=new Ri,a=!0,n=!!t&&t.isPartial,e.on("data",function(e){e.startTime=e.startPts/s,e.endTime=e.endPts/s,r.captions.push(e),r.captionStreams[e.stream]=!0}),e.on("log",function(e){r.logs.push(e)})},this.isNewInit=function(e,t){return!(e&&0===e.length||t&&"object"==typeof t&&0===Object.keys(t).length)&&(i!==e[0]||s!==t[i])},this.parse=function(e,n,a){var o;if(!this.isInitialized())return null;if(!n||!a)return null;if(this.isNewInit(n,a))i=n[0],s=a[i];else if(null===i||!s)return t.push(e),null;for(;t.length>0;){var l=t.shift();this.parse(l,n,a)}return o=function(e,t,i){if(null===t)return null;var s=Vi(e,t)[t]||{};return{seiNals:s.seiNals,logs:s.logs,timescale:i}}(e,i,s),o&&o.logs&&(r.logs=r.logs.concat(o.logs)),null!==o&&o.seiNals?(this.pushNals(o.seiNals),this.flushStream(),r):r.logs.length?{logs:r.logs,captions:[],captionStreams:[]}:null},this.pushNals=function(t){if(!this.isInitialized()||!t||0===t.length)return null;t.forEach(function(t){e.push(t)})},this.flushStream=function(){if(!this.isInitialized())return null;n?e.partialFlush():e.flush()},this.clearParsedCaptions=function(){r.captions=[],r.captionStreams={},r.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;e.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){t=[],i=null,s=null,r?this.clearParsedCaptions():r={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()};const{parseTfdt:Hi}=ci,zi=si,{getTimescaleFromMediaHeader:Wi}=Ai,{parseSamples:Gi,getMdatTrafPairs:Xi}=Oi;var Ki=function(){let e=9e4;this.init=function(t){const i=zi(t,["moov","trak","mdia","mdhd"])[0];i&&(e=Wi(i))},this.parseSegment=function(t){const i=[],s=Xi(t);let r=0;return s.forEach(function(t){const s=t.mdat,n=t.traf,a=zi(n,["tfdt"])[0],o=zi(n,["tfhd"])[0],l=zi(n,["trun"]);if(a){const e=Hi(a);r=e.baseMediaDecodeTime}if(l.length&&o){const t=Gi(l,r,o);let n=0;t.forEach(function(t){const r=new TextDecoder("utf-8"),a=s.slice(n,n+t.size);if(zi(a,["vtte"])[0])return void(n+=t.size);zi(a,["vttc"]).forEach(function(s){const n=zi(s,["payl"])[0],a=zi(s,["sttg"])[0],o=t.pts/e,l=(t.pts+t.duration)/e;let d,u;if(n)try{d=r.decode(n)}catch(e){console.error(e)}if(a)try{u=r.decode(a)}catch(e){console.error(e)}t.duration&&d&&i.push({cueText:d,start:o,end:l,settings:u})}),n+=t.size})}}),i}},Yi=xe,Qi=function(e){var t=31&e[1];return t<<=8,t|=e[2]},Ji=function(e){return!!(64&e[1])},Zi=function(e){var t=0;return(48&e[3])>>>4>1&&(t+=e[4]+1),t},es=function(e){switch(e){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}},ts={parseType:function(e,t){var i=Qi(e);return 0===i?"pat":i===t?"pmt":t?"pes":null},parsePat:function(e){var t=Ji(e),i=4+Zi(e);return t&&(i+=e[i]+1),(31&e[i+10])<<8|e[i+11]},parsePmt:function(e){var t={},i=Ji(e),s=4+Zi(e);if(i&&(s+=e[s]+1),1&e[s+5]){var r;r=3+((15&e[s+1])<<8|e[s+2])-4;for(var n=12+((15&e[s+10])<<8|e[s+11]);n<r;){var a=s+n;t[(31&e[a+1])<<8|e[a+2]]=e[a],n+=5+((15&e[a+3])<<8|e[a+4])}return t}},parsePayloadUnitStartIndicator:Ji,parsePesType:function(e,t){switch(t[Qi(e)]){case Yi.H264_STREAM_TYPE:return"video";case Yi.ADTS_STREAM_TYPE:return"audio";case Yi.METADATA_STREAM_TYPE:return"timed-metadata";default:return null}},parsePesTime:function(e){if(!Ji(e))return null;var t=4+Zi(e);if(t>=e.byteLength)return null;var i,s=null;return 192&(i=e[t+7])&&((s={}).pts=(14&e[t+9])<<27|(255&e[t+10])<<20|(254&e[t+11])<<12|(255&e[t+12])<<5|(254&e[t+13])>>>3,s.pts*=4,s.pts+=(6&e[t+13])>>>1,s.dts=s.pts,64&i&&(s.dts=(14&e[t+14])<<27|(255&e[t+15])<<20|(254&e[t+16])<<12|(255&e[t+17])<<5|(254&e[t+18])>>>3,s.dts*=4,s.dts+=(6&e[t+18])>>>1)),s},videoPacketContainsKeyFrame:function(e){for(var t=4+Zi(e),i=e.subarray(t),s=0,r=0,n=!1;r<i.byteLength-3;r++)if(1===i[r+2]){s=r+5;break}for(;s<i.byteLength;)switch(i[s]){case 0:if(0!==i[s-1]){s+=2;break}if(0!==i[s-2]){s++;break}r+3!==s-2&&"slice_layer_without_partitioning_rbsp_idr"===es(31&i[r+3])&&(n=!0);do{s++}while(1!==i[s]&&s<i.length);r=s-2,s+=3;break;case 1:if(0!==i[s-1]||0!==i[s-2]){s+=3;break}"slice_layer_without_partitioning_rbsp_idr"===es(31&i[r+3])&&(n=!0),r=s-2,s+=3;break;default:s+=3}return i=i.subarray(r),s-=r,r=0,i&&i.byteLength>3&&"slice_layer_without_partitioning_rbsp_idr"===es(31&i[r+3])&&(n=!0),n}},is=xe,ss=Me.handleRollover,rs={};rs.ts=ts,rs.aac=vt;var ns=oe.ONE_SECOND_IN_TS,as=188,os=71,ls=function(e,t,i){for(var s,r,n,a,o=0,l=as,d=!1;l<=e.byteLength;)if(e[o]!==os||e[l]!==os&&l!==e.byteLength)o++,l++;else{if(s=e.subarray(o,l),"pes"===rs.ts.parseType(s,t.pid))r=rs.ts.parsePesType(s,t.table),n=rs.ts.parsePayloadUnitStartIndicator(s),"audio"===r&&n&&(a=rs.ts.parsePesTime(s))&&(a.type="audio",i.audio.push(a),d=!0);if(d)break;o+=as,l+=as}for(o=(l=e.byteLength)-as,d=!1;o>=0;)if(e[o]!==os||e[l]!==os&&l!==e.byteLength)o--,l--;else{if(s=e.subarray(o,l),"pes"===rs.ts.parseType(s,t.pid))r=rs.ts.parsePesType(s,t.table),n=rs.ts.parsePayloadUnitStartIndicator(s),"audio"===r&&n&&(a=rs.ts.parsePesTime(s))&&(a.type="audio",i.audio.push(a),d=!0);if(d)break;o-=as,l-=as}},ds=function(e,t,i){for(var s,r,n,a,o,l,d,u=0,c=as,h=!1,p={data:[],size:0};c<e.byteLength;)if(e[u]!==os||e[c]!==os)u++,c++;else{if(s=e.subarray(u,c),"pes"===rs.ts.parseType(s,t.pid))if(r=rs.ts.parsePesType(s,t.table),n=rs.ts.parsePayloadUnitStartIndicator(s),"video"===r&&(n&&!h&&(a=rs.ts.parsePesTime(s))&&(a.type="video",i.video.push(a),h=!0),!i.firstKeyFrame)){if(n&&0!==p.size){for(o=new Uint8Array(p.size),l=0;p.data.length;)d=p.data.shift(),o.set(d,l),l+=d.byteLength;if(rs.ts.videoPacketContainsKeyFrame(o)){var m=rs.ts.parsePesTime(o);m?(i.firstKeyFrame=m,i.firstKeyFrame.type="video"):console.warn("Failed to extract PTS/DTS from PES at first keyframe. This could be an unusual TS segment, or else mux.js did not parse your TS segment correctly. If you know your TS segments do contain PTS/DTS on keyframes please file a bug report! You can try ffprobe to double check for yourself.")}p.size=0}p.data.push(s),p.size+=s.byteLength}if(h&&i.firstKeyFrame)break;u+=as,c+=as}for(u=(c=e.byteLength)-as,h=!1;u>=0;)if(e[u]!==os||e[c]!==os)u--,c--;else{if(s=e.subarray(u,c),"pes"===rs.ts.parseType(s,t.pid))r=rs.ts.parsePesType(s,t.table),n=rs.ts.parsePayloadUnitStartIndicator(s),"video"===r&&n&&(a=rs.ts.parsePesTime(s))&&(a.type="video",i.video.push(a),h=!0);if(h)break;u-=as,c-=as}},us=function(e){var t={pid:null,table:null},i={};for(var s in function(e,t){for(var i,s=0,r=as;r<e.byteLength;)if(e[s]!==os||e[r]!==os)s++,r++;else{switch(i=e.subarray(s,r),rs.ts.parseType(i,t.pid)){case"pat":t.pid=rs.ts.parsePat(i);break;case"pmt":var n=rs.ts.parsePmt(i);t.table=t.table||{},Object.keys(n).forEach(function(e){t.table[e]=n[e]})}s+=as,r+=as}}(e,t),t.table){if(t.table.hasOwnProperty(s))switch(t.table[s]){case is.H264_STREAM_TYPE:i.video=[],ds(e,t,i),0===i.video.length&&delete i.video;break;case is.ADTS_STREAM_TYPE:i.audio=[],ls(e,t,i),0===i.audio.length&&delete i.audio}}return i},cs=function(e,t){var i;return i=rs.aac.isLikelyAacData(e)?function(e){for(var t,i=!1,s=0,r=null,n=null,a=0,o=0;e.length-o>=3;){switch(rs.aac.parseType(e,o)){case"timed-metadata":if(e.length-o<10){i=!0;break}if((a=rs.aac.parseId3TagSize(e,o))>e.length){i=!0;break}null===n&&(t=e.subarray(o,o+a),n=rs.aac.parseAacTimestamp(t)),o+=a;break;case"audio":if(e.length-o<7){i=!0;break}if((a=rs.aac.parseAdtsSize(e,o))>e.length){i=!0;break}null===r&&(t=e.subarray(o,o+a),r=rs.aac.parseSampleRate(t)),s++,o+=a;break;default:o++}if(i)return null}if(null===r||null===n)return null;var l=ns/r;return{audio:[{type:"audio",dts:n,pts:n},{type:"audio",dts:n+1024*s*l,pts:n+1024*s*l}]}}(e):us(e),i&&(i.audio||i.video)?(function(e,t){if(e.audio&&e.audio.length){var i=t;(void 0===i||isNaN(i))&&(i=e.audio[0].dts),e.audio.forEach(function(e){e.dts=ss(e.dts,i),e.pts=ss(e.pts,i),e.dtsTime=e.dts/ns,e.ptsTime=e.pts/ns})}if(e.video&&e.video.length){var s=t;if((void 0===s||isNaN(s))&&(s=e.video[0].dts),e.video.forEach(function(e){e.dts=ss(e.dts,s),e.pts=ss(e.pts,s),e.dtsTime=e.dts/ns,e.ptsTime=e.pts/ns}),e.firstKeyFrame){var r=e.firstKeyFrame;r.dts=ss(r.dts,s),r.pts=ss(r.pts,s),r.dtsTime=r.dts/ns,r.ptsTime=r.pts/ns}}}(i,t),i):null};class hs{constructor(e,t){this.options=t||{},this.self=e,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new Qt.Transmuxer(this.options),function(e,t){t.on("data",function(t){const i=t.initSegment;t.initSegment={data:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength};const s=t.data;t.data=s.buffer,e.postMessage({action:"data",segment:t,byteOffset:s.byteOffset,byteLength:s.byteLength},[t.data])}),t.on("done",function(t){e.postMessage({action:"done"})}),t.on("gopInfo",function(t){e.postMessage({action:"gopInfo",gopInfo:t})}),t.on("videoSegmentTimingInfo",function(t){const i={start:{decode:oe.videoTsToSeconds(t.start.dts),presentation:oe.videoTsToSeconds(t.start.pts)},end:{decode:oe.videoTsToSeconds(t.end.dts),presentation:oe.videoTsToSeconds(t.end.pts)},baseMediaDecodeTime:oe.videoTsToSeconds(t.baseMediaDecodeTime)};t.prependedContentDuration&&(i.prependedContentDuration=oe.videoTsToSeconds(t.prependedContentDuration)),e.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:i})}),t.on("audioSegmentTimingInfo",function(t){const i={start:{decode:oe.videoTsToSeconds(t.start.dts),presentation:oe.videoTsToSeconds(t.start.pts)},end:{decode:oe.videoTsToSeconds(t.end.dts),presentation:oe.videoTsToSeconds(t.end.pts)},baseMediaDecodeTime:oe.videoTsToSeconds(t.baseMediaDecodeTime)};t.prependedContentDuration&&(i.prependedContentDuration=oe.videoTsToSeconds(t.prependedContentDuration)),e.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:i})}),t.on("id3Frame",function(t){e.postMessage({action:"id3Frame",id3Frame:t})}),t.on("caption",function(t){e.postMessage({action:"caption",caption:t})}),t.on("trackinfo",function(t){e.postMessage({action:"trackinfo",trackInfo:t})}),t.on("audioTimingInfo",function(t){e.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:oe.videoTsToSeconds(t.start),end:oe.videoTsToSeconds(t.end)}})}),t.on("videoTimingInfo",function(t){e.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:oe.videoTsToSeconds(t.start),end:oe.videoTsToSeconds(t.end)}})}),t.on("log",function(t){e.postMessage({action:"log",log:t})})}(this.self,this.transmuxer)}pushMp4Captions(e){this.captionParser||(this.captionParser=new $i,this.captionParser.init());const t=new Uint8Array(e.data,e.byteOffset,e.byteLength),i=this.captionParser.parse(t,e.trackIds,e.timescales);this.self.postMessage({action:"mp4Captions",captions:i&&i.captions||[],logs:i&&i.logs||[],data:t.buffer},[t.buffer])}initMp4WebVttParser(e){this.webVttParser||(this.webVttParser=new Ki);const t=new Uint8Array(e.data,e.byteOffset,e.byteLength);this.webVttParser.init(t)}getMp4WebVttText(e){this.webVttParser||(this.webVttParser=new Ki);const t=new Uint8Array(e.data,e.byteOffset,e.byteLength),i=this.webVttParser.parseSegment(t);this.self.postMessage({action:"getMp4WebVttText",mp4VttCues:i||[],data:t.buffer},[t.buffer])}probeMp4StartTime({timescales:e,data:t}){const i=Ai.startTime(e,t);this.self.postMessage({action:"probeMp4StartTime",startTime:i,data:t},[t.buffer])}probeMp4Tracks({data:e}){const t=Ai.tracks(e);this.self.postMessage({action:"probeMp4Tracks",tracks:t,data:e},[e.buffer])}probeEmsgID3({data:e,offset:t}){const i=Ai.getEmsgID3(e,t);this.self.postMessage({action:"probeEmsgID3",id3Frames:i,emsgData:e},[e.buffer])}probeTs({data:e,baseStartTime:t}){const i="number"!=typeof t||isNaN(t)?void 0:t*oe.ONE_SECOND_IN_TS,s=cs(e,i);let r=null;s&&(r={hasVideo:s.video&&2===s.video.length||!1,hasAudio:s.audio&&2===s.audio.length||!1},r.hasVideo&&(r.videoStart=s.video[0].ptsTime),r.hasAudio&&(r.audioStart=s.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:r,data:e},[e.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(e){const t=new Uint8Array(e.data,e.byteOffset,e.byteLength);this.transmuxer.push(t)}reset(){this.transmuxer.reset()}setTimestampOffset(e){const t=e.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(oe.secondsToVideoTs(t)))}setAudioAppendStart(e){this.transmuxer.setAudioAppendStart(Math.ceil(oe.secondsToVideoTs(e.appendStart)))}setRemux(e){this.transmuxer.setRemux(e.remux)}flush(e){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(e){this.transmuxer.alignGopsWith(e.gopsToAlignWith.slice())}}self.onmessage=function(e){"init"===e.data.action&&e.data.options?this.messageHandlers=new hs(self,e.data.options):(this.messageHandlers||(this.messageHandlers=new hs(self)),e.data&&e.data.action&&"init"!==e.data.action&&this.messageHandlers[e.data.action]&&this.messageHandlers[e.data.action](e.data))}}));var pd=dd(hd);const md=e=>{const{transmuxer:t,bytes:i,audioAppendStart:s,gopsToAlignWith:r,remux:n,onData:a,onTrackInfo:o,onAudioTimingInfo:l,onVideoTimingInfo:d,onVideoSegmentTimingInfo:u,onAudioSegmentTimingInfo:c,onId3:h,onCaptions:p,onDone:m,onEndedTimeline:g,onTransmuxerLog:f,isEndOfTimeline:y,segment:_,triggerSegmentEventFn:b}=e,v={buffer:[]};let T=y;if(t.onmessage=i=>{t.currentTransmux===e&&("data"===i.data.action&&((e,t,i)=>{const{type:s,initSegment:r,captions:n,captionStreams:a,metadata:o,videoFrameDtsTime:l,videoFramePtsTime:d}=e.data.segment;t.buffer.push({captions:n,captionStreams:a,metadata:o});const u=e.data.segment.boxes||{data:e.data.segment.data},c={type:s,data:new Uint8Array(u.data,u.data.byteOffset,u.data.byteLength),initSegment:new Uint8Array(r.data,r.byteOffset,r.byteLength)};void 0!==l&&(c.videoFrameDtsTime=l),void 0!==d&&(c.videoFramePtsTime=d),i(c)})(i,v,a),"trackinfo"===i.data.action&&o(i.data.trackInfo),"gopInfo"===i.data.action&&((e,t)=>{t.gopInfo=e.data.gopInfo})(i,v),"audioTimingInfo"===i.data.action&&l(i.data.audioTimingInfo),"videoTimingInfo"===i.data.action&&d(i.data.videoTimingInfo),"videoSegmentTimingInfo"===i.data.action&&u(i.data.videoSegmentTimingInfo),"audioSegmentTimingInfo"===i.data.action&&c(i.data.audioSegmentTimingInfo),"id3Frame"===i.data.action&&h([i.data.id3Frame],i.data.id3Frame.dispatchType),"caption"===i.data.action&&p(i.data.caption),"endedtimeline"===i.data.action&&(T=!1,g()),"log"===i.data.action&&f(i.data.log),"transmuxed"===i.data.type&&(T||(t.onmessage=null,(({transmuxedData:e,callback:t})=>{e.buffer=[],t(e)})({transmuxedData:v,callback:m}),gd(t))))},t.onerror=()=>{const e={message:"Received an error message from the transmuxer worker",metadata:{errorType:Fo.Error.StreamingFailedToTransmuxSegment,segmentInfo:du({segment:_})}};m(null,e)},s&&t.postMessage({action:"setAudioAppendStart",appendStart:s}),Array.isArray(r)&&t.postMessage({action:"alignGopsWith",gopsToAlignWith:r}),void 0!==n&&t.postMessage({action:"setRemux",remux:n}),i.byteLength){const e=i instanceof ArrayBuffer?i:i.buffer,s=i instanceof ArrayBuffer?0:i.byteOffset;b({type:"segmenttransmuxingstart",segment:_}),t.postMessage({action:"push",data:e,byteOffset:s,byteLength:i.byteLength},[e])}y&&t.postMessage({action:"endTimeline"}),t.postMessage({action:"flush"})},gd=e=>{e.currentTransmux=null,e.transmuxQueue.length&&(e.currentTransmux=e.transmuxQueue.shift(),"function"==typeof e.currentTransmux?e.currentTransmux():md(e.currentTransmux))},fd=(e,t)=>{e.postMessage({action:t}),gd(e)},yd=(e,t)=>{if(!t.currentTransmux)return t.currentTransmux=e,void fd(t,e);t.transmuxQueue.push(fd.bind(null,t,e))},_d=e=>{if(!e.transmuxer.currentTransmux)return e.transmuxer.currentTransmux=e,void md(e);e.transmuxer.transmuxQueue.push(e)};var bd=e=>{yd("reset",e)},vd=e=>{const t=new pd;t.currentTransmux=null,t.transmuxQueue=[];const i=t.terminate;return t.terminate=()=>(t.currentTransmux=null,t.transmuxQueue.length=0,i.call(t)),t.postMessage({action:"init",options:e}),t};const Td=function(e){const t=e.transmuxer,i=e.endAction||e.action,s=e.callback,r=G({},e,{endAction:null,transmuxer:null,callback:null}),n=r=>{r.data.action===i&&(t.removeEventListener("message",n),r.data.data&&(r.data.data=new Uint8Array(r.data.data,e.byteOffset||0,e.byteLength||r.data.data.byteLength),e.data&&(e.data=r.data.data)),s(r.data))};if(t.addEventListener("message",n),e.data){const i=e.data instanceof ArrayBuffer;r.byteOffset=i?0:e.data.byteOffset,r.byteLength=e.data.byteLength;const s=[i?e.data:e.data.buffer];t.postMessage(r,s)}else t.postMessage(r)},Sd=2,Ed=-101,wd=-102,kd="wvtt",Cd=e=>{e.forEach(e=>{e.abort()})},Id=(e,t)=>{const{requestType:i}=t,s=Al({requestType:i,request:t,error:e});return t.timedout?{status:t.status,message:"HLS request timed-out at URL: "+t.uri,code:Ed,xhr:t,metadata:s}:t.aborted?{status:t.status,message:"HLS request aborted at URL: "+t.uri,code:wd,xhr:t,metadata:s}:e?{status:t.status,message:"HLS request errored at URL: "+t.uri,code:Sd,xhr:t,metadata:s}:"arraybuffer"===t.responseType&&0===t.response.byteLength?{status:t.status,message:"Empty HLS response at URL: "+t.uri,code:Sd,xhr:t,metadata:s}:null},xd=(e,t,i,s)=>(r,n)=>{const a=n.response,o=Id(r,n);if(o)return i(o,e);if(16!==a.byteLength)return i({status:n.status,message:"Invalid HLS key at URL: "+n.uri,code:Sd,xhr:n},e);const l=new DataView(a),d=new Uint32Array([l.getUint32(0),l.getUint32(4),l.getUint32(8),l.getUint32(12)]);for(let e=0;e<t.length;e++)t[e].bytes=d;const u={uri:n.uri};return s({type:"segmentkeyloadcomplete",segment:e,keyInfo:u}),i(null,e)},Ad=(e,t)=>{const i=Ti(e.map.bytes);if("mp4"!==i){const s=e.map.resolvedUri||e.map.uri,r=i||"unknown";return t({internal:!0,message:`Found unsupported ${r} container for initialization segment at URL: ${s}`,code:Sd,metadata:{mediaType:r}})}Td({action:"probeMp4Tracks",data:e.map.bytes,transmuxer:e.transmuxer,callback:({tracks:i,data:s})=>(e.map.bytes=s,i.forEach(function(t){e.map.tracks=e.map.tracks||{},e.map.tracks[t.type]||(e.map.tracks[t.type]=t,"number"==typeof t.id&&t.timescale&&(e.map.timescales=e.map.timescales||{},e.map.timescales[t.id]=t.timescale),"text"===t.type&&((e,t)=>{t===kd&&e.transmuxer.postMessage({action:"initMp4WebVttParser",data:e.map.bytes})})(e,t.codec))}),t(null))})},Dd=({segment:e,finishProcessingFn:t,responseType:i,triggerSegmentEventFn:s})=>(r,n)=>{const a=Id(r,n);if(a)return t(a,e);s({type:"segmentloaded",segment:e});const o="arraybuffer"!==i&&n.responseText?(e=>{const t=new Uint8Array(new ArrayBuffer(e.length));for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t.buffer})(n.responseText.substring(e.lastReachedChar||0)):n.response;return e.stats=(e=>({bandwidth:e.bandwidth,bytesReceived:e.bytesReceived||0,roundTripTime:e.roundTripTime||0}))(n),e.key?e.encryptedBytes=new Uint8Array(o):e.bytes=new Uint8Array(o),t(null,e)},Pd=({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:u,doneFn:c,onTransmuxerLog:h,triggerSegmentEventFn:p})=>{const m=e.map&&e.map.tracks||{},g=Boolean(m.audio&&m.video);let f=s.bind(null,e,"audio","start");const y=s.bind(null,e,"audio","end");let _=s.bind(null,e,"video","start");const b=s.bind(null,e,"video","end");Td({action:"probeTs",transmuxer:e.transmuxer,data:t,baseStartTime:e.baseStartTime,callback:s=>{e.bytes=t=s.data;const m=s.result;m&&(i(e,{hasAudio:m.hasAudio,hasVideo:m.hasVideo,isMuxed:g}),i=null),_d({bytes:t,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,remux:g,onData:t=>{t.type="combined"===t.type?"video":t.type,u(e,t)},onTrackInfo:t=>{i&&(g&&(t.isMuxed=!0),i(e,t))},onAudioTimingInfo:e=>{f&&void 0!==e.start&&(f(e.start),f=null),y&&void 0!==e.end&&y(e.end)},onVideoTimingInfo:e=>{_&&void 0!==e.start&&(_(e.start),_=null),b&&void 0!==e.end&&b(e.end)},onVideoSegmentTimingInfo:t=>{const i={pts:{start:t.start.presentation,end:t.end.presentation},dts:{start:t.start.decode,end:t.end.decode}};p({type:"segmenttransmuxingtiminginfoavailable",segment:e,timingInfo:i}),r(t)},onAudioSegmentTimingInfo:t=>{const i={pts:{start:t.start.pts,end:t.end.pts},dts:{start:t.start.dts,end:t.end.dts}};p({type:"segmenttransmuxingtiminginfoavailable",segment:e,timingInfo:i}),n(t)},onId3:(t,i)=>{a(e,t,i)},onCaptions:t=>{o(e,[t])},isEndOfTimeline:l,onEndedTimeline:()=>{d()},onTransmuxerLog:h,onDone:(t,i)=>{c&&(t.type="combined"===t.type?"video":t.type,p({type:"segmenttransmuxingcomplete",segment:e}),c(i,e,t))},segment:e,triggerSegmentEventFn:p})}})},Ld=({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:u,doneFn:c,onTransmuxerLog:h,triggerSegmentEventFn:p})=>{let m=new Uint8Array(t);if(function(e){return si(e,["moof"]).length>0}(m)){e.isFmp4=!0;const{tracks:r}=e.map;if(r.text&&(!r.audio||!r.video))return u(e,{data:m,type:"text"}),void((e,t,i)=>{t===kd&&Td({action:"getMp4WebVttText",data:e.bytes,transmuxer:e.transmuxer,callback:({data:t,mp4VttCues:s})=>{e.bytes=t,i(null,e,{mp4VttCues:s})}})})(e,r.text.codec,c);const n={isFmp4:!0,hasVideo:!!r.video,hasAudio:!!r.audio};r.audio&&r.audio.codec&&"enca"!==r.audio.codec&&(n.audioCodec=r.audio.codec),r.video&&r.video.codec&&"encv"!==r.video.codec&&(n.videoCodec=r.video.codec),r.video&&r.audio&&(n.isMuxed=!0),i(e,n);const l=(t,i)=>{u(e,{data:m,type:n.hasAudio&&!n.isMuxed?"audio":"video"}),i&&i.length&&a(e,i),t&&t.length&&o(e,t),c(null,e,{})};return void Td({action:"probeMp4StartTime",timescales:e.map.timescales,data:m,transmuxer:e.transmuxer,callback:({data:i,startTime:a})=>{t=i.buffer,e.bytes=m=i,n.hasAudio&&!n.isMuxed&&s(e,"audio","start",a),n.hasVideo&&s(e,"video","start",a),Td({action:"probeEmsgID3",data:m,transmuxer:e.transmuxer,offset:a,callback:({emsgData:i,id3Frames:s})=>{t=i.buffer,e.bytes=m=i,r.video&&i.byteLength&&e.transmuxer?Td({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:e.transmuxer,data:m,timescales:e.map.timescales,trackIds:[r.video.id],callback:i=>{t=i.data.buffer,e.bytes=m=i.data,i.logs.forEach(function(e){h(Go(e,{stream:"mp4CaptionParser"}))}),l(i.captions,s)}}):l(void 0,s)}})}})}if(e.transmuxer){if(void 0===e.container&&(e.container=Ti(m)),"ts"!==e.container&&"aac"!==e.container)return i(e,{hasAudio:!1,hasVideo:!1}),void c(null,e,{});Pd({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:u,doneFn:c,onTransmuxerLog:h,triggerSegmentEventFn:p})}else c(null,e,{})},Od=function({id:e,key:t,encryptedBytes:i,decryptionWorker:s,segment:r,doneFn:n},a){const o=t=>{if(t.data.source===e){s.removeEventListener("message",o);const e=t.data.decrypted;a(new Uint8Array(e.bytes,e.byteOffset,e.byteLength))}};let l;s.onerror=()=>{const e="An error occurred in the decryption worker",t=du({segment:r}),i={message:e,metadata:{error:new Error(e),errorType:Fo.Error.StreamingFailedToDecryptSegment,segmentInfo:t,keyInfo:{uri:r.key.resolvedUri||r.map.key.resolvedUri}}};n(i,r)},s.addEventListener("message",o),l=t.bytes.slice?t.bytes.slice():new Uint32Array(Array.prototype.slice.call(t.bytes)),s.postMessage(zl({source:e,encrypted:i,key:l,iv:t.iv}),[i.buffer,l.buffer])},Md=({activeXhrs:e,decryptionWorker:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:u,doneFn:c,onTransmuxerLog:h,triggerSegmentEventFn:p})=>{let m=0,g=!1;return(f,y)=>{if(!g){if(f)return g=!0,Cd(e),c(f,y);if(m+=1,m===e.length){const m=function(){if(y.encryptedBytes)return(({decryptionWorker:e,segment:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:u,doneFn:c,onTransmuxerLog:h,triggerSegmentEventFn:p})=>{p({type:"segmentdecryptionstart"}),Od({id:t.requestId,key:t.key,encryptedBytes:t.encryptedBytes,decryptionWorker:e,segment:t,doneFn:c},e=>{t.bytes=e,p({type:"segmentdecryptioncomplete",segment:t}),Ld({segment:t,bytes:t.bytes,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:u,doneFn:c,onTransmuxerLog:h,triggerSegmentEventFn:p})})})({decryptionWorker:t,segment:y,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:u,doneFn:c,onTransmuxerLog:h,triggerSegmentEventFn:p});Ld({segment:y,bytes:y.bytes,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:u,doneFn:c,onTransmuxerLog:h,triggerSegmentEventFn:p})};if(y.endOfAllRequests=Date.now(),y.map&&y.map.encryptedBytes&&!y.map.bytes)return p({type:"segmentdecryptionstart",segment:y}),Od({decryptionWorker:t,id:y.requestId+"-init",encryptedBytes:y.map.encryptedBytes,key:y.map.key,segment:y,doneFn:c},t=>{y.map.bytes=t,p({type:"segmentdecryptioncomplete",segment:y}),Ad(y,t=>{if(t)return Cd(e),c(t,y);m()})});m()}}}},Rd=({segment:e,progressFn:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:d,dataFn:u})=>i=>{if(!i.target.aborted)return e.stats=Go(e.stats,(e=>{const t=e.target,i={bandwidth:1/0,bytesReceived:0,roundTripTime:Date.now()-t.requestTime||0};return i.bytesReceived=e.loaded,i.bandwidth=Math.floor(i.bytesReceived/i.roundTripTime*8*1e3),i})(i)),!e.stats.firstBytesReceivedAt&&e.stats.bytesReceived&&(e.stats.firstBytesReceivedAt=Date.now()),t(i,e)},Nd=({xhr:e,xhrOptions:t,decryptionWorker:i,segment:s,abortFn:r,progressFn:n,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:l,audioSegmentTimingInfoFn:d,id3Fn:u,captionsFn:c,isEndOfTimeline:h,endedTimelineFn:p,dataFn:m,doneFn:g,onTransmuxerLog:f,triggerSegmentEventFn:y})=>{const _=[],b=Md({activeXhrs:_,decryptionWorker:i,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:l,audioSegmentTimingInfoFn:d,id3Fn:u,captionsFn:c,isEndOfTimeline:h,endedTimelineFn:p,dataFn:m,doneFn:g,onTransmuxerLog:f,triggerSegmentEventFn:y});if(s.key&&!s.key.bytes){const i=[s.key];s.map&&!s.map.bytes&&s.map.key&&s.map.key.resolvedUri===s.key.resolvedUri&&i.push(s.map.key);const r=Go(t,{uri:s.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),n=xd(s,i,b,y);y({type:"segmentkeyloadstart",segment:s,keyInfo:{uri:s.key.resolvedUri}});const a=e(r,n);_.push(a)}if(s.map&&!s.map.bytes){if(s.map.key&&(!s.key||s.key.resolvedUri!==s.map.key.resolvedUri)){const i=Go(t,{uri:s.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),r=xd(s,[s.map.key],b,y);y({type:"segmentkeyloadstart",segment:s,keyInfo:{uri:s.map.key.resolvedUri}});const n=e(i,r);_.push(n)}const i=Go(t,{uri:s.map.resolvedUri,responseType:"arraybuffer",headers:jl(s.map),requestType:"segment-media-initialization"}),r=(({segment:e,finishProcessingFn:t,triggerSegmentEventFn:i})=>(s,r)=>{const n=Id(s,r);if(n)return t(n,e);const a=new Uint8Array(r.response);if(i({type:"segmentloaded",segment:e}),e.map.key)return e.map.encryptedBytes=a,t(null,e);e.map.bytes=a,Ad(e,function(i){if(i)return i.xhr=r,i.status=r.status,t(i,e);t(null,e)})})({segment:s,finishProcessingFn:b,triggerSegmentEventFn:y});y({type:"segmentloadstart",segment:s});const n=e(i,r);_.push(n)}const v=Go(t,{uri:s.part&&s.part.resolvedUri||s.resolvedUri,responseType:"arraybuffer",headers:jl(s),requestType:"segment"}),T=Dd({segment:s,finishProcessingFn:b,responseType:v.responseType,triggerSegmentEventFn:y});y({type:"segmentloadstart",segment:s});const S=e(v,T);S.addEventListener("progress",Rd({segment:s,progressFn:n,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:l,audioSegmentTimingInfoFn:d,id3Fn:u,captionsFn:c,isEndOfTimeline:h,endedTimelineFn:p,dataFn:m})),_.push(S);const E={};return _.forEach(e=>{e.addEventListener("loadend",(({loadendState:e,abortFn:t})=>i=>{i.target.aborted&&t&&!e.calledAbortFn&&(t(),e.calledAbortFn=!0)})({loadendState:E,abortFn:r}))}),()=>Cd(_)},Ud=Wo("CodecUtils"),Bd=(e,t)=>{const i=t.attributes||{};return e&&e.mediaGroups&&e.mediaGroups.AUDIO&&i.AUDIO&&e.mediaGroups.AUDIO[i.AUDIO]},Fd=function(e){const t={};return e.forEach(({mediaType:e,type:i,details:s})=>{t[e]=t[e]||[],t[e].push(he(`${i}${s}`))}),Object.keys(t).forEach(function(e){if(t[e].length>1)return Ud(`multiple ${e} codecs found as attributes: ${t[e].join(", ")}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`),void(t[e]=null);t[e]=t[e][0]}),t},qd=function(e){let t=0;return e.audio&&t++,e.video&&t++,t},jd=function(e,t){const i=t.attributes||{},s=Fd(function(e){const t=e.attributes||{};if(t.CODECS)return pe(t.CODECS)}(t)||[]);if(Bd(e,t)&&!s.audio&&!((e,t)=>{if(!Bd(e,t))return!0;const i=t.attributes||{},s=e.mediaGroups.AUDIO[i.AUDIO];for(const e in s)if(!s[e].uri&&!s[e].playlists)return!0;return!1})(e,t)){const t=Fd(function(e,t){if(!e.mediaGroups.AUDIO||!t)return null;var i=e.mediaGroups.AUDIO[t];if(!i)return null;for(var s in i){var r=i[s];if(r.default&&r.playlists)return pe(r.playlists[0].attributes.CODECS)}return null}(e,i.AUDIO)||[]);t.audio&&(s.audio=t.audio)}return s},Vd=Wo("PlaylistSelector"),$d=function(e){if(!e||!e.playlist)return;const t=e.playlist;return JSON.stringify({id:t.id,bandwidth:e.bandwidth,width:e.width,height:e.height,codecs:t.attributes&&t.attributes.CODECS||""})},Hd=function(e,t){if(!e)return"";const i=p.getComputedStyle(e);return i?i[t]:""},zd=function(e,t){const i=e.slice();e.sort(function(e,s){const r=t(e,s);return 0===r?i.indexOf(e)-i.indexOf(s):r})},Wd=function(e,t){let i,s;return e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||p.Number.MAX_VALUE,t.attributes.BANDWIDTH&&(s=t.attributes.BANDWIDTH),s=s||p.Number.MAX_VALUE,i-s};let Gd=function(e,t,i,s,r,n){if(!e)return;const a={bandwidth:t,width:i,height:s,limitRenditionByPlayerDimensions:r};let o=e.playlists;Tl.isAudioOnly(e)&&(o=n.getAudioTrackPlaylists_(),a.audioOnly=!0);let l=o.map(e=>{let t;const i=e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width,s=e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.height;return t=e.attributes&&e.attributes.BANDWIDTH,t=t||p.Number.MAX_VALUE,{bandwidth:t,width:i,height:s,playlist:e}});zd(l,(e,t)=>e.bandwidth-t.bandwidth),l=l.filter(e=>!Tl.isIncompatible(e.playlist));let d=l.filter(e=>Tl.isEnabled(e.playlist));d.length||(d=l.filter(e=>!Tl.isDisabled(e.playlist)));const u=d.filter(e=>e.bandwidth*od.BANDWIDTH_VARIANCE<t);let c=u[u.length-1];const h=u.filter(e=>e.bandwidth===c.bandwidth)[0];if(!1===r){const e=h||d[0]||l[0];if(e&&e.playlist){let t="sortedPlaylistReps";return h&&(t="bandwidthBestRep"),d[0]&&(t="enabledPlaylistReps"),Vd(`choosing ${$d(e)} using ${t} with options`,a),e.playlist}return Vd("could not choose a playlist with options",a),null}const m=u.filter(e=>e.width&&e.height);zd(m,(e,t)=>e.width-t.width);const g=m.filter(e=>e.width===i&&e.height===s);c=g[g.length-1];const f=g.filter(e=>e.bandwidth===c.bandwidth)[0];let y,_,b,v;if(f||(y=m.filter(e=>e.width>i||e.height>s),_=y.filter(e=>e.width===y[0].width&&e.height===y[0].height),c=_[_.length-1],b=_.filter(e=>e.bandwidth===c.bandwidth)[0]),n.leastPixelDiffSelector){const e=m.map(e=>(e.pixelDiff=Math.abs(e.width-i)+Math.abs(e.height-s),e));zd(e,(e,t)=>e.pixelDiff===t.pixelDiff?t.bandwidth-e.bandwidth:e.pixelDiff-t.pixelDiff),v=e[0]}const T=v||b||f||h||d[0]||l[0];if(T&&T.playlist){let e="sortedPlaylistReps";return v?e="leastPixelDiffRep":b?e="resolutionPlusOneRep":f?e="resolutionBestRep":h?e="bandwidthBestRep":d[0]&&(e="enabledPlaylistReps"),Vd(`choosing ${$d(T)} using ${e} with options`,a),T.playlist}return Vd("could not choose a playlist with options",a),null};const Xd=function(){let e=this.useDevicePixelRatio&&p.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(e=this.customPixelRatio),Gd(this.playlists.main,this.systemBandwidth,parseInt(Hd(this.tech_.el(),"width"),10)*e,parseInt(Hd(this.tech_.el(),"height"),10)*e,this.limitRenditionByPlayerDimensions,this.playlistController_)};function Kd(e){try{return new URL(e).pathname.split("/").slice(-2).join("/")}catch(e){return""}}const Yd=({inbandTextTracks:e,metadataArray:t,timestampOffset:i,videoDuration:s})=>{if(!t)return;const r=p.WebKitDataCue||p.VTTCue,n=e.metadataTrack_;if(!n)return;if(t.forEach(e=>{const t=e.cueTime+i;!("number"!=typeof t||p.isNaN(t)||t<0)&&t<1/0&&e.frames&&e.frames.length&&e.frames.forEach(e=>{const i=new r(t,t,e.value||e.url||e.data||"");i.frame=e,i.value=e,function(e){Object.defineProperties(e.frame,{id:{get:()=>(Fo.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),e.value.key)},value:{get:()=>(Fo.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),e.value.data)},privateData:{get:()=>(Fo.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),e.value.data)}})}(i),n.addCue(i)})}),!n.cues||!n.cues.length)return;const a=n.cues,o=[];for(let e=0;e<a.length;e++)a[e]&&o.push(a[e]);const l=o.reduce((e,t)=>{const i=e[t.startTime]||[];return i.push(t),e[t.startTime]=i,e},{}),d=Object.keys(l).sort((e,t)=>Number(e)-Number(t));d.forEach((e,t)=>{const i=l[e],r=isFinite(s)?s:e,n=Number(d[t+1])||r;i.forEach(e=>{e.endTime=n})})},Qd={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"},Jd=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),Zd=(e,t,i)=>{e.metadataTrack_||(e.metadataTrack_=i.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,Fo.browser.IS_ANY_SAFARI||(e.metadataTrack_.inBandMetadataTrackDispatchType=t))},eu=function(e,t,i){let s,r;if(i&&i.cues)for(s=i.cues.length;s--;)r=i.cues[s],r.startTime>=e&&r.endTime<=t&&i.removeCue(r)},tu=e=>"number"==typeof e&&isFinite(e),iu=1/60,su=e=>{const{startOfSegment:t,duration:i,segment:s,part:r,playlist:{mediaSequence:n,id:a,segments:o=[]},mediaIndex:l,partIndex:d,timeline:u}=e,c=o.length-1;let h="mediaIndex/partIndex increment";e.getMediaInfoForTime?h=`getMediaInfoForTime (${e.getMediaInfoForTime})`:e.isSyncRequest&&(h="getSyncSegmentCandidate (isSyncRequest)"),e.independent&&(h+=` with independent ${e.independent}`);const p="number"==typeof d,m=e.segment.uri?"segment":"pre-segment",g=p?ol({preloadSegment:s})-1:0;return`${m} [${n+l}/${n+c}]`+(p?` part [${d}/${g}]`:"")+` segment start/end [${s.start} => ${s.end}]`+(p?` part start/end [${r.start} => ${r.end}]`:"")+` startOfSegment [${t}]`+` duration [${i}]`+` timeline [${u}]`+` selected by [${h}]`+` playlist [${a}]`},ru=e=>`${e}TimingInfo`,nu=({timelineChangeController:e,currentTimeline:t,segmentTimeline:i,loaderType:s,audioDisabled:r})=>{if(t===i)return!1;if("audio"===s){const t=e.lastTimelineChange({type:"main"});return!t||t.to!==i}if("main"===s&&r){const t=e.pendingTimelineChange({type:"audio"});return!t||t.to!==i}return!1},au=e=>{const t=e.pendingSegment_;if(!t)return;if(nu({timelineChangeController:e.timelineChangeController_,currentTimeline:e.currentTimeline_,segmentTimeline:t.timeline,loaderType:e.loaderType_,audioDisabled:e.audioDisabled_})&&(e=>{if(!e)return!1;const t=e.pendingTimelineChange({type:"audio"}),i=e.pendingTimelineChange({type:"main"}),s=t&&i,r=s&&t.to!==i.to;return!(!s||-1===t.from||-1===i.from||!r)})(e.timelineChangeController_)){if((e=>{const t=e.timelineChangeController_.pendingTimelineChange({type:"audio"}),i=e.timelineChangeController_.pendingTimelineChange({type:"main"});return t&&i&&t.to<i.to})(e))return void e.timelineChangeController_.trigger("audioTimelineBehind");e.timelineChangeController_.trigger("fixBadTimelineChange")}},ou=({segmentDuration:e,maxDuration:t})=>!!e&&Math.round(e)>t+Ko,lu=(e,t)=>{if("hls"!==t)return null;const i=(e=>{let t=0;return["video","audio"].forEach(function(i){const s=e[`${i}TimingInfo`];if(!s)return;const{start:r,end:n}=s;let a;"bigint"==typeof r||"bigint"==typeof n?a=p.BigInt(n)-p.BigInt(r):"number"==typeof r&&"number"==typeof n&&(a=n-r),void 0!==a&&a>t&&(t=a)}),"bigint"==typeof t&&t<Number.MAX_SAFE_INTEGER&&(t=Number(t)),t})({audioTimingInfo:e.audioTimingInfo,videoTimingInfo:e.videoTimingInfo});if(!i)return null;const s=e.playlist.targetDuration,r=ou({segmentDuration:i,maxDuration:2*s}),n=ou({segmentDuration:i,maxDuration:s}),a=`Segment with index ${e.mediaIndex} from playlist ${e.playlist.id} has a duration of ${i} when the reported duration is ${e.duration} and the target duration is ${s}. For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1`;return r||n?{severity:r?"warn":"info",message:a}:null},du=({type:e,segment:t})=>{if(!t)return;const i=Boolean(t.key||t.map&&t.map.ke),s=Boolean(t.map&&!t.map.bytes),r=void 0===t.startOfSegment?t.start:t.startOfSegment;return{type:e||t.type,uri:t.resolvedUri||t.uri,start:r,duration:t.duration,isEncrypted:i,isMediaInitialization:s}};class uu extends Fo.EventTarget{constructor(e,t={}){if(super(),!e)throw new TypeError("Initialization settings are required");if("function"!=typeof e.currentTime)throw new TypeError("No currentTime getter specified");if(!e.mediaSource)throw new TypeError("No MediaSource specified");this.bandwidth=e.bandwidth,this.throughput={rate:0,count:0},this.roundTrip=NaN,this.resetStats_(),this.mediaIndex=null,this.partIndex=null,this.hasPlayed_=e.hasPlayed,this.currentTime_=e.currentTime,this.seekable_=e.seekable,this.seeking_=e.seeking,this.duration_=e.duration,this.mediaSource_=e.mediaSource,this.vhs_=e.vhs,this.loaderType_=e.loaderType,this.currentMediaInfo_=void 0,this.startingMediaInfo_=void 0,this.segmentMetadataTrack_=e.segmentMetadataTrack,this.goalBufferLength_=e.goalBufferLength,this.sourceType_=e.sourceType,this.sourceUpdater_=e.sourceUpdater,this.inbandTextTracks_=e.inbandTextTracks,this.state_="INIT",this.timelineChangeController_=e.timelineChangeController,this.shouldSaveSegmentTimingInfo_=!0,this.parse708captions_=e.parse708captions,this.useDtsForTimestampOffset_=e.useDtsForTimestampOffset,this.captionServices_=e.captionServices,this.exactManifestTimings=e.exactManifestTimings,this.addMetadataToTextTrack=e.addMetadataToTextTrack,this.checkBufferTimeout_=null,this.error_=void 0,this.currentTimeline_=-1,this.shouldForceTimestampOffsetAfterResync_=!1,this.pendingSegment_=null,this.xhrOptions_=null,this.pendingSegments_=[],this.audioDisabled_=!1,this.isPendingTimestampOffset_=!1,this.gopBuffer_=[],this.timeMapping_=0,this.safeAppend_=!1,this.appendInitSegment_={audio:!0,video:!0},this.playlistOfLastInitSegment_={audio:null,video:null},this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_={id3:[],caption:[]},this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=null,this.activeInitSegmentId_=null,this.initSegments_={},this.cacheEncryptionKeys_=e.cacheEncryptionKeys,this.keyCache_={},this.decrypter_=e.decrypter,this.syncController_=e.syncController,this.syncPoint_={segmentIndex:0,time:0},this.transmuxer_=this.createTransmuxer_(),this.triggerSyncInfoUpdate_=()=>this.trigger("syncinfoupdate"),this.syncController_.on("syncinfoupdate",this.triggerSyncInfoUpdate_),this.mediaSource_.addEventListener("sourceopen",()=>{this.isEndOfStream_()||(this.ended_=!1)}),this.fetchAtBuffer_=!1,this.logger_=Wo(`SegmentLoader[${this.loaderType_}]`),Object.defineProperty(this,"state",{get(){return this.state_},set(e){e!==this.state_&&(this.logger_(`${this.state_} -> ${e}`),this.state_=e,this.trigger("statechange"))}}),this.sourceUpdater_.on("ready",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():au(this)}),this.sourceUpdater_.on("codecschange",e=>{this.trigger(G({type:"codecschange"},e))}),"main"===this.loaderType_&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():au(this)}),"audio"===this.loaderType_&&this.timelineChangeController_.on("timelinechange",e=>{this.trigger(G({type:"timelinechange"},e)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():au(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():au(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return vd({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,captionServices:this.captionServices_})}resetStats_(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0}dispose(){this.trigger("dispose"),this.state="DISPOSED",this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&p.clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_),this.off()}setAudio(e){this.audioDisabled_=!e,e?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){if("WAITING"!==this.state)return this.pendingSegment_&&(this.pendingSegment_=null),void this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);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,p.clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(e){return"APPENDING"!==this.state||this.pendingSegment_?!this.pendingSegment_||this.pendingSegment_.requestId!==e:(this.state="READY",!0)}error(e){return void 0!==e&&(this.logger_("error occurred:",e),this.error_=e),this.pendingSegment_=null,this.error_}endOfStream(){this.ended_=!0,this.transmuxer_&&bd(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){const e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return Xo();if("main"===this.loaderType_){const{hasAudio:t,hasVideo:i,isMuxed:s}=e;if(i&&t&&!this.audioDisabled_&&!s)return this.sourceUpdater_.buffered();if(i)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(e,t=!1){if(!e)return null;const i=Wl(e);let s=this.initSegments_[i];return t&&!s&&e.bytes&&(this.initSegments_[i]=s={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),s||e}segmentKey(e,t=!1){if(!e)return null;const i=Gl(e);let s=this.keyCache_[i];this.cacheEncryptionKeys_&&t&&!s&&e.bytes&&(this.keyCache_[i]=s={resolvedUri:e.resolvedUri,bytes:e.bytes});const r={resolvedUri:(s||e).resolvedUri};return s&&(r.bytes=s.bytes),r}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),this.playlist_)return"INIT"===this.state&&this.couldBeginLoading_()?this.init_():void(!this.couldBeginLoading_()||"READY"!==this.state&&"INIT"!==this.state||(this.state="READY"))}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}playlist(e,t={}){if(!e)return;if(this.playlist_&&this.playlist_.endList&&e.endList&&this.playlist_.uri===e.uri)return;const i=this.playlist_,s=this.pendingSegment_;this.playlist_=e,this.xhrOptions_=t,"INIT"===this.state&&(e.syncInfo={mediaSequence:e.mediaSequence,time:0},"main"===this.loaderType_&&this.syncController_.setDateTimeMappingForStart(e));let r=null;if(i&&(i.id?r=i.id:i.uri&&(r=i.uri)),this.logger_(`playlist update [${r} => ${e.id||e.uri}]`),this.mediaSequenceSync_&&(this.mediaSequenceSync_.update(e,this.currentTime_()),this.logger_(`Playlist update:\ncurrentTime: ${this.currentTime_()}\nbufferedEnd: ${il(this.buffered_())}\n`,this.mediaSequenceSync_.diagnostics)),this.trigger("syncinfoupdate"),"INIT"===this.state&&this.couldBeginLoading_())return this.init_();if(!i||i.uri!==e.uri){if(null!==this.mediaIndex){!e.endList&&"number"==typeof e.partTargetDuration?this.resetLoader():this.resyncLoader()}return this.currentMediaInfo_=void 0,void this.trigger("playlistupdate")}const n=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${n}]`),null!==this.mediaIndex)if(this.mediaIndex-=n,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{const e=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!e.parts||!e.parts.length||!e.parts[this.partIndex])){const e=this.mediaIndex;this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=e}}s&&(s.mediaIndex-=n,s.mediaIndex<0?(s.mediaIndex=null,s.partIndex=null):(s.mediaIndex>=0&&(s.segment=e.segments[s.mediaIndex]),s.partIndex>=0&&s.segment.parts&&(s.part=s.segment.parts[s.partIndex]))),this.syncController_.saveExpiredSegmentInfo(i,e)}pause(){this.checkBufferTimeout_&&(p.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=null)}paused(){return null===this.checkBufferTimeout_}resetEverything(e){this.ended_=!1,this.activeInitSegmentId_=null,this.appendInitSegment_={audio:!0,video:!0},this.resetLoader(),this.remove(0,1/0,e),this.transmuxer_&&(this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.transmuxer_.postMessage({action:"reset"}))}resetLoader(){this.fetchAtBuffer_=!1,this.mediaSequenceSync_&&this.mediaSequenceSync_.resetAppendedStatus(),this.resyncLoader()}resyncLoader(){this.transmuxer_&&bd(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1;const e=this.currentMediaInfo_&&this.currentMediaInfo_.isFmp4;"hls"===this.sourceType_&&!e&&(this.shouldForceTimestampOffsetAfterResync_=!0),this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}remove(e,t,i=()=>{},s=!1){if(t===1/0&&(t=this.duration_()),t<=e)return void this.logger_("skipping remove because end ${end} is <= start ${start}");if(!this.sourceUpdater_||!this.getMediaInfo_())return void this.logger_("skipping remove because no source updater or starting media info");let r=1;const n=()=>{r--,0===r&&i()};!s&&this.audioDisabled_||(r++,this.sourceUpdater_.removeAudio(e,t,n)),(s||"main"===this.loaderType_)&&(this.gopBuffer_=((e,t,i,s)=>{const r=Math.ceil((t-s)*Si.ONE_SECOND_IN_TS),n=Math.ceil((i-s)*Si.ONE_SECOND_IN_TS),a=e.slice();let o=e.length;for(;o--&&!(e[o].pts<=n););if(-1===o)return a;let l=o+1;for(;l--&&!(e[l].pts<=r););return l=Math.max(l,0),a.splice(l,o-l+1),a})(this.gopBuffer_,e,t,this.timeMapping_),r++,this.sourceUpdater_.removeVideo(e,t,n));for(const i in this.inbandTextTracks_)eu(e,t,this.inbandTextTracks_[i]);eu(e,t,this.segmentMetadataTrack_),n()}monitorBuffer_(){this.checkBufferTimeout_&&p.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=p.setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){"READY"===this.state&&this.fillBuffer_(),this.checkBufferTimeout_&&p.clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=p.setTimeout(this.monitorBufferTick_.bind(this),500)}fillBuffer_(){if(this.sourceUpdater_.updating())return;const e=this.chooseNextRequest_();if(!e)return;const t={segmentInfo:du({type:this.loaderType_,segment:e})};this.trigger({type:"segmentselected",metadata:t}),"number"==typeof e.timestampOffset&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e)}isEndOfStream_(e=this.mediaIndex,t=this.playlist_,i=this.partIndex){if(!t||!this.mediaSource_)return!1;const s="number"==typeof e&&t.segments[e],r=e+1===t.segments.length,n=!s||!s.parts||i+1===s.parts.length;return t.endList&&"open"===this.mediaSource_.readyState&&r&&n}chooseNextRequest_(){const e=this.buffered_(),t=il(e)||0,i=sl(e,this.currentTime_()),s=!this.hasPlayed_()&&i>=1,r=i>=this.goalBufferLength_(),n=this.playlist_.segments;if(!n.length||s||r)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);const a={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:Boolean(!this.syncPoint_)};if(a.isSyncRequest)a.mediaIndex=function(e,t,i){t=t||[];const s=[];let r=0;for(let n=0;n<t.length;n++){const a=t[n];if(e===a.timeline&&(s.push(n),r+=a.duration,r>i))return n}return 0===s.length?0:s[s.length-1]}(this.currentTimeline_,n,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${a.mediaIndex}`);else if(null!==this.mediaIndex){const e=n[this.mediaIndex],i="number"==typeof this.partIndex?this.partIndex:-1;a.startOfSegment=e.end?e.end:t,e.parts&&e.parts[i+1]?(a.mediaIndex=this.mediaIndex,a.partIndex=i+1):a.mediaIndex=this.mediaIndex+1}else{let e,i,s;const r=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch:\nFor TargetTime: ${r}.\nCurrentTime: ${this.currentTime_()}\nBufferedEnd: ${t}\nFetch At Buffer: ${this.fetchAtBuffer_}\n`,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){const t=this.getSyncInfoFromMediaSequenceSync_(r);if(!t){const e="No sync info found while using media sequence sync";return this.error({message:e,metadata:{errorType:Fo.Error.StreamingFailedToSelectNextSegment,error:new Error(e)}}),this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${t.start} --\x3e ${t.end})`),e=t.segmentIndex,i=t.partIndex,s=t.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");const t=Tl.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:r,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});e=t.segmentIndex,i=t.partIndex,s=t.startTime}a.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${r}`:`currentTime ${r}`,a.mediaIndex=e,a.startOfSegment=s,a.partIndex=i,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${a.mediaIndex} `)}const o=n[a.mediaIndex];let l=o&&"number"==typeof a.partIndex&&o.parts&&o.parts[a.partIndex];if(!o||"number"==typeof a.partIndex&&!l)return null;"number"!=typeof a.partIndex&&o.parts&&(a.partIndex=0,l=o.parts[0]);const d=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!i&&l&&!d&&!l.independent)if(0===a.partIndex){const e=n[a.mediaIndex-1],t=e.parts&&e.parts.length&&e.parts[e.parts.length-1];t&&t.independent&&(a.mediaIndex-=1,a.partIndex=e.parts.length-1,a.independent="previous segment")}else o.parts[a.partIndex-1].independent&&(a.partIndex-=1,a.independent="previous part");const u=this.mediaSource_&&"ended"===this.mediaSource_.readyState;return a.mediaIndex>=n.length-1&&u&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,a.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync")),this.generateSegmentInfo_(a))}getSyncInfoFromMediaSequenceSync_(e){if(!this.mediaSequenceSync_)return null;const t=Math.max(e,this.mediaSequenceSync_.start);e!==t&&this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${e} to ${t}`);const i=this.mediaSequenceSync_.getSyncInfoForTime(t);if(!i)return null;if(!i.isAppended)return i;const s=this.mediaSequenceSync_.getSyncInfoForTime(i.end);return s?(s.isAppended&&this.logger_("getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!"),s):null}generateSegmentInfo_(e){const{independent:t,playlist:i,mediaIndex:s,startOfSegment:r,isSyncRequest:n,partIndex:a,forceTimestampOffset:o,getMediaInfoForTime:l}=e,d=i.segments[s],u="number"==typeof a&&d.parts[a],c={requestId:"segment-loader-"+Math.random(),uri:u&&u.resolvedUri||d.resolvedUri,mediaIndex:s,partIndex:u?a:null,isSyncRequest:n,startOfSegment:r,playlist:i,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:d.timeline,duration:u&&u.duration||d.duration,segment:d,part:u,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:l,independent:t},h=void 0!==o?o:this.isPendingTimestampOffset_;c.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:d.timeline,currentTimeline:this.currentTimeline_,startOfSegment:r,buffered:this.buffered_(),overrideCheck:h});const p=il(this.sourceUpdater_.audioBuffered());return"number"==typeof p&&(c.audioAppendStart=p-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(c.gopsToAlignWith=((e,t,i)=>{if(null==t||!e.length)return[];const s=Math.ceil((t-i+3)*Si.ONE_SECOND_IN_TS);let r;for(r=0;r<e.length&&!(e[r].pts>s);r++);return e.slice(r)})(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),c}timestampOffsetForSegment_(e){return(({segmentTimeline:e,currentTimeline:t,startOfSegment:i,buffered:s,overrideCheck:r})=>r||e!==t?e<t?i:s.length?s.end(s.length-1):i:null)(e)}earlyAbortWhenNeeded_(e){if(this.vhs_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH)return;if(Date.now()-(e.firstBytesReceivedAt||Date.now())<1e3)return;const t=this.currentTime_(),i=e.bandwidth,s=this.pendingSegment_.duration,r=Tl.estimateSegmentRequestTime(s,i,this.playlist_,e.bytesReceived),n=function(e,t,i=1){return((e.length?e.end(e.length-1):0)-t)/i}(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(r<=n)return;const a=function(e){const{main:t,currentTime:i,bandwidth:s,duration:r,segmentDuration:n,timeUntilRebuffer:a,currentTimeline:o,syncController:l}=e,d=t.playlists.filter(e=>!Tl.isIncompatible(e));let u=d.filter(Tl.isEnabled);u.length||(u=d.filter(e=>!Tl.isDisabled(e)));const c=u.filter(Tl.hasAttribute.bind(null,"BANDWIDTH")).map(e=>{const t=l.getSyncPoint(e,r,o,i)?1:2;return{playlist:e,rebufferingImpact:Tl.estimateSegmentRequestTime(n,s,e)*t-a}}),h=c.filter(e=>e.rebufferingImpact<=0);return zd(h,(e,t)=>Wd(t.playlist,e.playlist)),h.length?h[0]:(zd(c,(e,t)=>e.rebufferingImpact-t.rebufferingImpact),c[0]||null)}({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:s,timeUntilRebuffer:n,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!a)return;const o=r-n-a.rebufferingImpact;let l=.5;n<=Ko&&(l=1),!a.playlist||a.playlist.uri===this.playlist_.uri||o<l||(this.bandwidth=a.playlist.attributes.BANDWIDTH*od.BANDWIDTH_VARIANCE+1,this.trigger("earlyabort"))}handleAbort_(e){this.logger_(`Aborting ${su(e)}`),this.mediaRequestsAborted+=1}handleProgress_(e,t){this.earlyAbortWhenNeeded_(t.stats),this.checkForAbort_(t.requestId)||this.trigger("progress")}handleTrackInfo_(e,t){const{hasAudio:i,hasVideo:s}=t,r={segmentInfo:du({type:this.loaderType_,segment:e}),trackInfo:{hasAudio:i,hasVideo:s}};this.trigger({type:"segmenttransmuxingtrackinfoavailable",metadata:r}),this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId)||this.checkForIllegalMediaSwitch(t)||(t=t||{},function(e,t){if(!e&&!t||!e&&t||e&&!t)return!1;if(e===t)return!0;const i=Object.keys(e).sort(),s=Object.keys(t).sort();if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++){const n=i[r];if(n!==s[r])return!1;if(e[n]!==t[n])return!1}return!0}(this.currentMediaInfo_,t)||(this.appendInitSegment_={audio:!0,video:!0},this.startingMediaInfo_=t,this.currentMediaInfo_=t,this.logger_("trackinfo update",t),this.trigger("trackinfo")),this.checkForAbort_(e.requestId)||(this.pendingSegment_.trackInfo=t,this.hasEnoughInfoToAppend_()?this.processCallQueue_():au(this)))}handleTimingInfo_(e,t,i,s){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;const r=this.pendingSegment_,n=ru(t);r[n]=r[n]||{},r[n][i]=s,this.logger_(`timinginfo: ${t} - ${i} - ${s}`),this.hasEnoughInfoToAppend_()?this.processCallQueue_():au(this)}handleCaptions_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(0===t.length)return void this.logger_("SegmentLoader received no captions from a caption event");if(!this.pendingSegment_.hasAppendedData_)return void this.metadataQueue_.caption.push(this.handleCaptions_.bind(this,e,t));const i=null===this.sourceUpdater_.videoTimestampOffset()?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset(),s={};t.forEach(e=>{s[e.stream]=s[e.stream]||{startTime:1/0,captions:[],endTime:0};const t=s[e.stream];t.startTime=Math.min(t.startTime,e.startTime+i),t.endTime=Math.max(t.endTime,e.endTime+i),t.captions.push(e)}),Object.keys(s).forEach(e=>{const{startTime:t,endTime:r,captions:n}=s[e],a=this.inbandTextTracks_;this.logger_(`adding cues from ${t} -> ${r} for ${e}`),function(e,t,i){if(!e[i]){t.trigger({type:"usage",name:"vhs-608"});let s=i;/^cc708_/.test(i)&&(s="SERVICE"+i.split("_")[1]);const r=t.textTracks().getTrackById(s);if(r)e[i]=r;else{let r=i,n=i,a=!1;const o=(t.options_.vhs&&t.options_.vhs.captionServices||{})[s];o&&(r=o.label,n=o.language,a=o.default),e[i]=t.addRemoteTextTrack({kind:"captions",id:s,default:a,label:r,language:n},!1).track}}}(a,this.vhs_.tech_,e),eu(t,r,a[e]),function({inbandTextTracks:e,captionArray:t,timestampOffset:i}){if(!t)return;const s=p.WebKitDataCue||p.VTTCue;t.forEach(t=>{const r=t.stream;t.content?t.content.forEach(n=>{const a=new s(t.startTime+i,t.endTime+i,n.text);a.line=n.line,a.align="left",a.position=n.position,a.positionAlign="line-left",e[r].addCue(a)}):e[r].addCue(new s(t.startTime+i,t.endTime+i,t.text))})}({captionArray:n,inbandTextTracks:a,timestampOffset:i})}),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}handleId3_(e,t,i){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;this.pendingSegment_.hasAppendedData_?this.addMetadataToTextTrack(i,t,this.duration_()):this.metadataQueue_.id3.push(this.handleId3_.bind(this,e,t,i))}processMetadataQueue_(){this.metadataQueue_.id3.forEach(e=>e()),this.metadataQueue_.caption.forEach(e=>e()),this.metadataQueue_.id3=[],this.metadataQueue_.caption=[]}processCallQueue_(){const e=this.callQueue_;this.callQueue_=[],e.forEach(e=>e())}processLoadQueue_(){const e=this.loadQueue_;this.loadQueue_=[],e.forEach(e=>e())}hasEnoughInfoToLoad_(){if("audio"!==this.loaderType_)return!0;const e=this.pendingSegment_;return!!e&&(!this.getCurrentMediaInfo_()||!nu({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}getCurrentMediaInfo_(e=this.pendingSegment_){return e&&e.trackInfo||this.currentMediaInfo_}getMediaInfo_(e=this.pendingSegment_){return this.getCurrentMediaInfo_(e)||this.startingMediaInfo_}getPendingSegmentPlaylist(){return this.pendingSegment_?this.pendingSegment_.playlist:null}hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready())return!1;if(this.waitingOnRemove_||this.quotaExceededErrorRetryTimeout_)return!1;const e=this.pendingSegment_,t=this.getCurrentMediaInfo_();if(!e||!t)return!1;const{hasAudio:i,hasVideo:s,isMuxed:r}=t;return!(s&&!e.videoTimingInfo)&&(!(i&&!this.audioDisabled_&&!r&&!e.audioTimingInfo)&&!nu({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}handleData_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(this.callQueue_.length||!this.hasEnoughInfoToAppend_())return au(this),void this.callQueue_.push(this.handleData_.bind(this,e,t));const i=this.pendingSegment_;if(this.setTimeMapping_(i.timeline),this.updateMediaSecondsLoaded_(i.part||i.segment),"closed"!==this.mediaSource_.readyState){if(e.map&&(e.map=this.initSegmentForMap(e.map,!0),i.segment.map=e.map),e.key&&this.segmentKey(e.key,!0),i.isFmp4=e.isFmp4,i.timingInfo=i.timingInfo||{},i.isFmp4)this.trigger("fmp4"),i.timingInfo.start=i[ru(t.type)].start;else{const e=this.getCurrentMediaInfo_(),t="main"===this.loaderType_&&e&&e.hasVideo;let s;t&&(s=i.videoTimingInfo.start),i.timingInfo.start=this.trueSegmentStart_({currentStart:i.timingInfo.start,playlist:i.playlist,mediaIndex:i.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:t,firstVideoFrameTimeForData:s,videoTimingInfo:i.videoTimingInfo,audioTimingInfo:i.audioTimingInfo})}if(this.updateAppendInitSegmentStatus(i,t.type),this.updateSourceBufferTimestampOffset_(i),i.isSyncRequest){this.updateTimingInfoEnd_(i),this.syncController_.saveSegmentTimingInfo({segmentInfo:i,shouldSaveTimelineMapping:"main"===this.loaderType_});const e=this.chooseNextRequest_();if(e.mediaIndex!==i.mediaIndex||e.partIndex!==i.partIndex)return void this.logger_("sync segment was incorrect, not appending");this.logger_("sync segment was correct, appending")}i.hasAppendedData_=!0,this.processMetadataQueue_(),this.appendData_(i,t)}}updateAppendInitSegmentStatus(e,t){"main"!==this.loaderType_||"number"!=typeof e.timestampOffset||e.changedTimestampOffset||(this.appendInitSegment_={audio:!0,video:!0}),this.playlistOfLastInitSegment_[t]!==e.playlist&&(this.appendInitSegment_[t]=!0)}getInitSegmentAndUpdateState_({type:e,initSegment:t,map:i,playlist:s}){if(i){const e=Wl(i);if(this.activeInitSegmentId_===e)return null;t=this.initSegmentForMap(i,!0).bytes,this.activeInitSegmentId_=e}return t&&this.appendInitSegment_[e]?(this.playlistOfLastInitSegment_[e]=s,this.appendInitSegment_[e]=!1,this.activeInitSegmentId_=null,t):null}handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i},s){const r=this.sourceUpdater_.audioBuffered(),n=this.sourceUpdater_.videoBuffered();r.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+tl(r).join(", ")),n.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+tl(n).join(", "));const a=r.length?r.start(0):0,o=r.length?r.end(r.length-1):0,l=n.length?n.start(0):0,d=n.length?n.end(n.length-1):0;if(o-a<=1&&d-l<=1)return this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${tl(r).join(", ")}, video buffer: ${tl(n).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),void this.trigger("error");this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:i}));const u=this.currentTime_()-1;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${u}`),this.remove(0,u,()=>{this.logger_("On QUOTA_EXCEEDED_ERR, retrying append in 1s"),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=p.setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},s){s&&(22!==s.code?(this.logger_("Received non QUOTA_EXCEEDED_ERR on append",s),this.error({message:`${t} append of ${i.length}b failed for segment #${e.mediaIndex} in playlist ${e.playlist.id}`,metadata:{errorType:Fo.Error.StreamingFailedToAppendSegment}}),this.trigger("appenderror")):this.handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i}))}appendToSourceBuffer_({segmentInfo:e,type:t,initSegment:i,data:s,bytes:r}){if(!r){const e=[s];let t=s.byteLength;i&&(e.unshift(i),t+=i.byteLength),r=(e=>{let t,i=0;return e.bytes&&(t=new Uint8Array(e.bytes),e.segments.forEach(e=>{t.set(e,i),i+=e.byteLength})),t})({bytes:t,segments:e})}const n={segmentInfo:du({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:n}),this.sourceUpdater_.appendBuffer({segmentInfo:e,type:t,bytes:r},this.handleAppendError_.bind(this,{segmentInfo:e,type:t,bytes:r}))}handleSegmentTimingInfo_(e,t,i){if(!this.pendingSegment_||t!==this.pendingSegment_.requestId)return;const s=this.pendingSegment_.segment,r=`${e}TimingInfo`;s[r]||(s[r]={}),s[r].transmuxerPrependedSeconds=i.prependedContentDuration||0,s[r].transmuxedPresentationStart=i.start.presentation,s[r].transmuxedDecodeStart=i.start.decode,s[r].transmuxedPresentationEnd=i.end.presentation,s[r].transmuxedDecodeEnd=i.end.decode,s[r].baseMediaDecodeTime=i.baseMediaDecodeTime}appendData_(e,t){const{type:i,data:s}=t;if(!s||!s.byteLength)return;if("audio"===i&&this.audioDisabled_)return;const r=this.getInitSegmentAndUpdateState_({type:i,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:i,initSegment:r,data:s})}loadSegment_(e){if(this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),"number"==typeof e.timestampOffset&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),!this.hasEnoughInfoToLoad_())return au(this),void this.loadQueue_.push(()=>{const t=G({},e,{forceTimestampOffset:!0});G(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)});this.updateTransmuxerAndRequestSegment_(e)}updateTransmuxerAndRequestSegment_(e){this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:e.timestampOffset}));const t=this.createSimplifiedSegmentObj_(e),i=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),s=null!==this.mediaIndex,r=e.timeline!==this.currentTimeline_&&e.timeline>0,n=i||s&&r;this.logger_(`Requesting\n${Kd(e.uri)}\n${su(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=Nd({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:t,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"audio",e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:n,endedTimelineFn:()=>{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:t,level:i,stream:s})=>{this.logger_(`${su(e)} logged from transmuxer stream ${s} as a ${i}: ${t}`)},triggerSegmentEventFn:({type:e,segment:t,keyInfo:i,trackInfo:s,timingInfo:r})=>{const n={segmentInfo:du({segment:t})};i&&(n.keyInfo=i),s&&(n.trackInfo=s),r&&(n.timingInfo=r),this.trigger({type:e,metadata:n})}})}trimBackBuffer_(e){const t=((e,t,i)=>{let s=t-od.BACK_BUFFER_LENGTH;e.length&&(s=Math.max(s,e.start(0)));const r=t-i;return Math.min(r,s)})(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){const t=e.segment,i=e.part,s=e.segment.key||e.segment.map&&e.segment.map.key,r=e.segment.map&&!e.segment.map.bytes,n={resolvedUri:i?i.resolvedUri:t.resolvedUri,byterange:i?i.byterange:t.byterange,requestId:e.requestId,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,part:e.part,type:this.loaderType_,start:e.startOfSegment,duration:e.duration,isEncrypted:s,isMediaInitialization:r},a=e.playlist.segments[e.mediaIndex-1];if(a&&a.timeline===t.timeline&&(a.videoTimingInfo?n.baseStartTime=a.videoTimingInfo.transmuxedDecodeEnd:a.audioTimingInfo&&(n.baseStartTime=a.audioTimingInfo.transmuxedDecodeEnd)),t.key){const i=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);n.key=this.segmentKey(t.key),n.key.iv=i}return t.map&&(n.map=this.initSegmentForMap(t.map)),n}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){if(this.pendingSegment_.byteLength=t.bytesReceived,e<iu)return void this.logger_(`Ignoring segment's bandwidth because its duration of ${e} is less than the min to record 0.016666666666666666`);const i={bandwidthInfo:{from:this.bandwidth,to:t.bandwidth}};this.trigger({type:"bandwidthupdated",metadata:i}),this.bandwidth=t.bandwidth,this.roundTrip=t.roundTripTime}handleTimeout_(){this.mediaRequestsTimedout+=1,this.bandwidth=1,this.roundTrip=NaN,this.trigger("bandwidthupdate"),this.trigger("timeout")}segmentRequestFinished_(e,t,i){if(this.callQueue_.length)return void this.callQueue_.push(this.segmentRequestFinished_.bind(this,e,t,i));if(this.saveTransferStats_(t.stats),!this.pendingSegment_)return;if(t.requestId!==this.pendingSegment_.requestId)return;if(e){if(this.pendingSegment_=null,this.state="READY",e.code===wd)return;return this.pause(),e.code===Ed?void this.handleTimeout_():(this.mediaRequestsErrored+=1,this.error(e),void this.trigger("error"))}const s=this.pendingSegment_;this.saveBandwidthRelatedStats_(s.duration,t.stats),s.endOfAllRequests=t.endOfAllRequests,i.gopInfo&&(this.gopBuffer_=((e,t,i)=>{if(!t.length)return e;if(i)return t.slice();const s=t[0].pts;let r=0;for(;r<e.length&&!(e[r].pts>=s);r++);return e.slice(0,r).concat(t)})(this.gopBuffer_,i.gopInfo,this.safeAppend_)),this.state="APPENDING",this.trigger("appending"),this.waitForAppendsToComplete_(s)}setTimeMapping_(e){const t=this.syncController_.mappingForTimeline(e);null!==t&&(this.timeMapping_=t)}updateMediaSecondsLoaded_(e){"number"==typeof e.start&&"number"==typeof e.end?this.mediaSecondsLoaded+=e.end-e.start:this.mediaSecondsLoaded+=e.duration}shouldUpdateTransmuxerTimestampOffset_(e){return null!==e&&("main"===this.loaderType_&&e!==this.sourceUpdater_.videoTimestampOffset()||!this.audioDisabled_&&e!==this.sourceUpdater_.audioTimestampOffset())}trueSegmentStart_({currentStart:e,playlist:t,mediaIndex:i,firstVideoFrameTimeForData:s,currentVideoTimestampOffset:r,useVideoTimingInfo:n,videoTimingInfo:a,audioTimingInfo:o}){if(void 0!==e)return e;if(!n)return o.start;const l=t.segments[i-1];return 0!==i&&l&&void 0!==l.start&&l.end===s+r?a.start:s}waitForAppendsToComplete_(e){const t=this.getCurrentMediaInfo_(e);if(!t)return this.error({message:"No starting media returned, likely due to an unsupported media format.",playlistExclusionDuration:1/0}),void this.trigger("error");const{hasAudio:i,hasVideo:s,isMuxed:r}=t,n="main"===this.loaderType_&&s,a=!this.audioDisabled_&&i&&!r;if(e.waitingOnAppends=0,!e.hasAppendedData_)return e.timingInfo||"number"!=typeof e.timestampOffset||(this.isPendingTimestampOffset_=!0),e.timingInfo={start:0},e.waitingOnAppends++,this.isPendingTimestampOffset_||(this.updateSourceBufferTimestampOffset_(e),this.processMetadataQueue_()),void this.checkAppendsDone_(e);n&&e.waitingOnAppends++,a&&e.waitingOnAppends++,n&&this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this,e)),a&&this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this,e))}checkAppendsDone_(e){this.checkForAbort_(e.requestId)||(e.waitingOnAppends--,0===e.waitingOnAppends&&this.handleAppendsDone_())}checkForIllegalMediaSwitch(e){const t=((e,t,i)=>"main"===e&&t&&i?i.hasAudio||i.hasVideo?t.hasVideo&&!i.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.":!t.hasVideo&&i.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.loaderType_,this.getCurrentMediaInfo_(),e);return!!t&&(this.error({message:t,playlistExclusionDuration:1/0}),this.trigger("error"),!0)}updateSourceBufferTimestampOffset_(e){if(null===e.timestampOffset||"number"!=typeof e.timingInfo.start||e.changedTimestampOffset||"main"!==this.loaderType_)return;let t=!1;e.timestampOffset-=this.getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e.segment.videoTimingInfo,audioTimingInfo:e.segment.audioTimingInfo,timingInfo:e.timingInfo}),e.changedTimestampOffset=!0,e.timestampOffset!==this.sourceUpdater_.videoTimestampOffset()&&(this.sourceUpdater_.videoTimestampOffset(e.timestampOffset),t=!0),e.timestampOffset!==this.sourceUpdater_.audioTimestampOffset()&&(this.sourceUpdater_.audioTimestampOffset(e.timestampOffset),t=!0),t&&this.trigger("timestampoffset")}getSegmentStartTimeForTimestampOffsetCalculation_({videoTimingInfo:e,audioTimingInfo:t,timingInfo:i}){return this.useDtsForTimestampOffset_?e&&"number"==typeof e.transmuxedDecodeStart?e.transmuxedDecodeStart:t&&"number"==typeof t.transmuxedDecodeStart?t.transmuxedDecodeStart:i.start:i.start}updateTimingInfoEnd_(e){e.timingInfo=e.timingInfo||{};const t=this.getMediaInfo_(),i="main"===this.loaderType_&&t&&t.hasVideo&&e.videoTimingInfo?e.videoTimingInfo:e.audioTimingInfo;i&&(e.timingInfo.end="number"==typeof i.end?i.end:i.start+e.duration)}handleAppendsDone_(){if(this.pendingSegment_){const e={segmentInfo:du({type:this.loaderType_,segment:this.pendingSegment_})};this.trigger({type:"appendsdone",metadata:e})}if(!this.pendingSegment_)return this.state="READY",void(this.paused()||this.monitorBuffer_());const e=this.pendingSegment_;e.part&&e.part.syncInfo?e.part.syncInfo.markAppended():e.segment.syncInfo&&e.segment.syncInfo.markAppended(),this.updateTimingInfoEnd_(e),this.shouldSaveSegmentTimingInfo_&&this.syncController_.saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:"main"===this.loaderType_});const t=lu(e,this.sourceType_);if(t&&("warn"===t.severity?Fo.log.warn(t.message):this.logger_(t.message)),this.recordThroughput_(e),this.pendingSegment_=null,this.state="READY",e.isSyncRequest&&(this.trigger("syncinfoupdate"),!e.hasAppendedData_))return void this.logger_(`Throwing away un-appended sync request ${su(e)}`);this.logger_(`Appended ${su(e)}`),this.addSegmentMetadataCue_(e),this.fetchAtBuffer_=!0,this.currentTimeline_!==e.timeline&&(this.timelineChangeController_.lastTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline}),"main"!==this.loaderType_||this.audioDisabled_||this.timelineChangeController_.lastTimelineChange({type:"audio",from:this.currentTimeline_,to:e.timeline})),this.currentTimeline_=e.timeline,this.trigger("syncinfoupdate");const i=e.segment,s=e.part,r=i.end&&this.currentTime_()-i.end>3*e.playlist.targetDuration,n=s&&s.end&&this.currentTime_()-s.end>3*e.playlist.partTargetDuration;if(r||n)return this.logger_(`bad ${r?"segment":"part"} ${su(e)}`),void this.resetEverything();null!==this.mediaIndex&&this.trigger("bandwidthupdate"),this.trigger("progress"),this.mediaIndex=e.mediaIndex,this.partIndex=e.partIndex,this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex)&&this.endOfStream(),this.trigger("appended"),e.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitorBuffer_()}recordThroughput_(e){if(e.duration<iu)return void this.logger_(`Ignoring segment's throughput because its duration of ${e.duration} is less than the min to record 0.016666666666666666`);const t=this.throughput.rate,i=Date.now()-e.endOfAllRequests+1,s=Math.floor(e.byteLength/i*8*1e3);this.throughput.rate+=(s-t)/++this.throughput.count}addSegmentMetadataCue_(e){if(!this.segmentMetadataTrack_)return;const t=e.segment,i=t.start,s=t.end;if(!tu(i)||!tu(s))return;eu(i,s,this.segmentMetadataTrack_);const r=p.WebKitDataCue||p.VTTCue,n={custom:t.custom,dateTimeObject:t.dateTimeObject,dateTimeString:t.dateTimeString,programDateTime:t.programDateTime,bandwidth:e.playlist.attributes.BANDWIDTH,resolution:e.playlist.attributes.RESOLUTION,codecs:e.playlist.attributes.CODECS,byteLength:e.byteLength,uri:e.uri,timeline:e.timeline,playlist:e.playlist.id,start:i,end:s},a=new r(i,s,JSON.stringify(n));a.value=n,this.segmentMetadataTrack_.addCue(a)}}function cu(){}const hu=function(e){return"string"!=typeof e?e:e.replace(/./,e=>e.toUpperCase())},pu=["video","audio"],mu=(e,t)=>{const i=t[`${e}Buffer`];return i&&i.updating||t.queuePending[e]},gu=(e,t)=>{if(0===t.queue.length)return;let i=0,s=t.queue[i];if("mediaSource"!==s.type){if("mediaSource"!==e&&t.ready()&&"closed"!==t.mediaSource.readyState&&!mu(e,t)){if(s.type!==e){if(i=((e,t)=>{for(let i=0;i<t.length;i++){const s=t[i];if("mediaSource"===s.type)return null;if(s.type===e)return i}return null})(e,t.queue),null===i)return;s=t.queue[i]}return t.queue.splice(i,1),t.queuePending[e]=s,s.action(e,t),s.doneFn?void 0:(t.queuePending[e]=null,void gu(e,t))}}else t.updating()||"closed"===t.mediaSource.readyState||(t.queue.shift(),s.action(t),s.doneFn&&s.doneFn(),gu("audio",t),gu("video",t))},fu=(e,t)=>{const i=t[`${e}Buffer`],s=hu(e);i&&(i.removeEventListener("updateend",t[`on${s}UpdateEnd_`]),i.removeEventListener("error",t[`on${s}Error_`]),t.codecs[e]=null,t[`${e}Buffer`]=null)},yu=(e,t)=>e&&t&&-1!==Array.prototype.indexOf.call(e.sourceBuffers,t),_u=(e,t,i)=>(s,r)=>{const n=r[`${s}Buffer`];if(yu(r.mediaSource,n)){r.logger_(`Appending segment ${t.mediaIndex}'s ${e.length} bytes to ${s}Buffer`);try{n.appendBuffer(e)}catch(e){r.logger_(`Error with code ${e.code} `+(22===e.code?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${t.mediaIndex} to ${s}Buffer`),r.queuePending[s]=null,i(e)}}},bu=(e,t)=>(i,s)=>{const r=s[`${i}Buffer`];if(yu(s.mediaSource,r)){s.logger_(`Removing ${e} to ${t} from ${i}Buffer`);try{r.remove(e,t)}catch(r){s.logger_(`Remove ${e} to ${t} from ${i}Buffer failed`)}}},vu=e=>(t,i)=>{const s=i[`${t}Buffer`];yu(i.mediaSource,s)&&(i.logger_(`Setting ${t}timestampOffset to ${e}`),s.timestampOffset=e)},Tu=e=>(t,i)=>{e()},Su=e=>t=>{if("open"===t.mediaSource.readyState){t.logger_(`Calling mediaSource endOfStream(${e||""})`);try{t.mediaSource.endOfStream(e)}catch(e){Fo.log.warn("Failed to call media source endOfStream",e)}}},Eu=e=>t=>{t.logger_(`Setting mediaSource duration to ${e}`);try{t.mediaSource.duration=e}catch(e){Fo.log.warn("Failed to set media source duration",e)}},wu=()=>(e,t)=>{if("open"!==t.mediaSource.readyState)return;const i=t[`${e}Buffer`];if(yu(t.mediaSource,i)){t.logger_(`calling abort on ${e}Buffer`);try{i.abort()}catch(t){Fo.log.warn(`Failed to abort on ${e}Buffer`,t)}}},ku=(e,t)=>i=>{const s=hu(e),r=ge(t);i.logger_(`Adding ${e}Buffer with codec ${t} to mediaSource`);const n=i.mediaSource.addSourceBuffer(r);n.addEventListener("updateend",i[`on${s}UpdateEnd_`]),n.addEventListener("error",i[`on${s}Error_`]),i.codecs[e]=t,i[`${e}Buffer`]=n},Cu=e=>t=>{const i=t[`${e}Buffer`];if(fu(e,t),yu(t.mediaSource,i)){t.logger_(`Removing ${e}Buffer with codec ${t.codecs[e]} from mediaSource`);try{t.mediaSource.removeSourceBuffer(i)}catch(t){Fo.log.warn(`Failed to removeSourceBuffer ${e}Buffer`,t)}}},Iu=e=>(t,i)=>{const s=i[`${t}Buffer`],r=ge(e);if(!yu(i.mediaSource,s))return;const n=e.substring(0,e.indexOf(".")),a=i.codecs[t];if(a.substring(0,a.indexOf("."))===n)return;const o={codecsChangeInfo:{from:a,to:e}};i.trigger({type:"codecschange",metadata:o}),i.logger_(`changing ${t}Buffer codec from ${a} to ${e}`);try{s.changeType(r),i.codecs[t]=e}catch(e){o.errorType=Fo.Error.StreamingCodecsChangeError,o.error=e,e.metadata=o,i.error_=e,i.trigger("error"),Fo.log.warn(`Failed to changeType on ${t}Buffer`,e)}},xu=({type:e,sourceUpdater:t,action:i,doneFn:s,name:r})=>{t.queue.push({type:e,action:i,doneFn:s,name:r}),gu(e,t)},Au=(e,t)=>i=>{const s=function(e){if(0===e.length)return"Buffered Ranges are empty";let t="Buffered Ranges: \n";for(let i=0;i<e.length;i++){const s=e.start(i),r=e.end(i);t+=`${s} --\x3e ${r}. Duration (${r-s})\n`}return t}(t[`${e}Buffered`]());if(t.logger_(`received "updateend" event for ${e} Source Buffer: `,s),t.queuePending[e]){const i=t.queuePending[e].doneFn;t.queuePending[e]=null,i&&i(t[`${e}Error_`])}gu(e,t)};class Du extends Fo.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>gu("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=Wo("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=Au("video",this),this.onAudioUpdateEnd_=Au("audio",this),this.onVideoError_=e=>{this.videoError_=e},this.onAudioError_=e=>{this.audioError_=e},this.createdSourceBuffers_=!1,this.initializedEme_=!1,this.triggeredReady_=!1}initializedEme(){this.initializedEme_=!0,this.triggerReady()}hasCreatedSourceBuffers(){return this.createdSourceBuffers_}hasInitializedAnyEme(){return this.initializedEme_}ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme()}createSourceBuffers(e){this.hasCreatedSourceBuffers()||(this.addOrChangeSourceBuffers(e),this.createdSourceBuffers_=!0,this.trigger("createdsourcebuffers"),this.triggerReady())}triggerReady(){this.ready()&&!this.triggeredReady_&&(this.triggeredReady_=!0,this.trigger("ready"))}addSourceBuffer(e,t){xu({type:"mediaSource",sourceUpdater:this,action:ku(e,t),name:"addSourceBuffer"})}abort(e){xu({type:e,sourceUpdater:this,action:wu(e),name:"abort"})}removeSourceBuffer(e){this.canRemoveSourceBuffer()?xu({type:"mediaSource",sourceUpdater:this,action:Cu(e),name:"removeSourceBuffer"}):Fo.log.error("removeSourceBuffer is not supported!")}canRemoveSourceBuffer(){return!Fo.browser.IS_FIREFOX&&p.MediaSource&&p.MediaSource.prototype&&"function"==typeof p.MediaSource.prototype.removeSourceBuffer}static canChangeType(){return p.SourceBuffer&&p.SourceBuffer.prototype&&"function"==typeof p.SourceBuffer.prototype.changeType}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){this.canChangeType()?xu({type:e,sourceUpdater:this,action:Iu(t),name:"changeType"}):Fo.log.error("changeType is not supported!")}addOrChangeSourceBuffers(e){if(!e||"object"!=typeof e||0===Object.keys(e).length)throw new Error("Cannot addOrChangeSourceBuffers to undefined codecs");Object.keys(e).forEach(t=>{const i=e[t];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(t,i);this.canChangeType()&&this.changeType(t,i)})}appendBuffer(e,t){const{segmentInfo:i,type:s,bytes:r}=e;if(this.processedAppend_=!0,"audio"===s&&this.videoBuffer&&!this.videoAppendQueued_)return this.delayedAudioAppendQueue_.push([e,t]),void this.logger_(`delayed audio append of ${r.length} until video append`);if(xu({type:s,sourceUpdater:this,action:_u(r,i||{mediaIndex:-1},t),doneFn:t,name:"appendBuffer"}),"video"===s){if(this.videoAppendQueued_=!0,!this.delayedAudioAppendQueue_.length)return;const e=this.delayedAudioAppendQueue_.slice();this.logger_(`queuing delayed audio ${e.length} appendBuffers`),this.delayedAudioAppendQueue_.length=0,e.forEach(e=>{this.appendBuffer.apply(this,e)})}}audioBuffered(){return yu(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:Xo()}videoBuffered(){return yu(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:Xo()}buffered(){const e=yu(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=yu(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():function(e,t){let i=null,s=null,r=0;const n=[],a=[];if(!(e&&e.length&&t&&t.length))return Xo();let o=e.length;for(;o--;)n.push({time:e.start(o),type:"start"}),n.push({time:e.end(o),type:"end"});for(o=t.length;o--;)n.push({time:t.start(o),type:"start"}),n.push({time:t.end(o),type:"end"});for(n.sort(function(e,t){return e.time-t.time}),o=0;o<n.length;o++)"start"===n[o].type?(r++,2===r&&(i=n[o].time)):"end"===n[o].type&&(r--,1===r&&(s=n[o].time)),null!==i&&null!==s&&(a.push([i,s]),i=null,s=null);return Xo(a)}(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=cu){xu({type:"mediaSource",sourceUpdater:this,action:Eu(e),name:"duration",doneFn:t})}endOfStream(e=null,t=cu){"string"!=typeof e&&(e=void 0),xu({type:"mediaSource",sourceUpdater:this,action:Su(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=cu){this.audioBuffered().length&&0!==this.audioBuffered().end(0)?xu({type:"audio",sourceUpdater:this,action:bu(e,t),doneFn:i,name:"remove"}):i()}removeVideo(e,t,i=cu){this.videoBuffered().length&&0!==this.videoBuffered().end(0)?xu({type:"video",sourceUpdater:this,action:bu(e,t),doneFn:i,name:"remove"}):i()}updating(){return!(!mu("audio",this)&&!mu("video",this))}audioTimestampOffset(e){return void 0!==e&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(xu({type:"audio",sourceUpdater:this,action:vu(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return void 0!==e&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(xu({type:"video",sourceUpdater:this,action:vu(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&xu({type:"audio",sourceUpdater:this,action:Tu(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&xu({type:"video",sourceUpdater:this,action:Tu(e),name:"callback"})}dispose(){this.trigger("dispose"),pu.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>fu(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}const Pu=e=>decodeURIComponent(escape(String.fromCharCode.apply(null,e))),Lu=new Uint8Array("\n\n".split("").map(e=>e.charCodeAt(0)));class Ou extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class Mu extends uu{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.loadVttJs=e.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return Xo();const e=this.subtitlesTrack_.cues;return Xo([[e[0].startTime,e[e.length-1].startTime]])}initSegmentForMap(e,t=!1){if(!e)return null;const i=Wl(e);let s=this.initSegments_[i];if(t&&!s&&e.bytes){const t=Lu.byteLength+e.bytes.byteLength,r=new Uint8Array(t);r.set(e.bytes),r.set(Lu,e.bytes.byteLength),this.initSegments_[i]=s={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:r}}return s||e}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}track(e){return void 0===e||(this.subtitlesTrack_=e,"INIT"===this.state&&this.couldBeginLoading_()&&this.init_()),this.subtitlesTrack_}remove(e,t){eu(e,t,this.subtitlesTrack_)}fillBuffer_(){const e=this.chooseNextRequest_();if(e){if(null===this.syncController_.timestampOffsetForTimeline(e.timeline)){const e=()=>{this.state="READY",this.paused()||this.monitorBuffer_()};return this.syncController_.one("timestampoffset",e),void(this.state="WAITING_ON_TIMELINE")}this.loadSegment_(e)}}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(e){for(;e&&e.segment.empty;){if(e.mediaIndex+1>=e.playlist.segments.length){e=null;break}e=this.generateSegmentInfo_({playlist:e.playlist,mediaIndex:e.mediaIndex+1,startOfSegment:e.startOfSegment+e.duration,isSyncRequest:e.isSyncRequest})}return e}stopForError(e){this.error(e),this.state="READY",this.pause(),this.trigger("error")}segmentRequestFinished_(e,t,i){if(!this.subtitlesTrack_)return void(this.state="READY");if(this.saveTransferStats_(t.stats),!this.pendingSegment_)return this.state="READY",void(this.mediaRequestsAborted+=1);if(e)return e.code===Ed&&this.handleTimeout_(),e.code===wd?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,void this.stopForError(e);const s=this.pendingSegment_,r=i.mp4VttCues&&i.mp4VttCues.length;r&&(s.mp4VttCues=i.mp4VttCues),this.saveBandwidthRelatedStats_(s.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");const n=s.segment;if(n.map&&(n.map.bytes=t.map.bytes),s.bytes=t.bytes,"function"!=typeof p.WebVTT&&"function"==typeof this.loadVttJs)return this.state="WAITING_ON_VTTJS",void this.loadVttJs().then(()=>this.segmentRequestFinished_(e,t,i),()=>this.stopForError({message:"Error loading vtt.js"}));n.requested=!0;try{this.parseVTTCues_(s)}catch(e){return void this.stopForError({message:e.message,metadata:{errorType:Fo.Error.StreamingVttParserError,error:e}})}if(r||this.updateTimeMapping_(s,this.syncController_.timelines[s.timeline],this.playlist_),s.cues.length?s.timingInfo={start:s.cues[0].startTime,end:s.cues[s.cues.length-1].endTime}:s.timingInfo={start:s.startOfSegment,end:s.startOfSegment+s.duration},s.isSyncRequest)return this.trigger("syncinfoupdate"),this.pendingSegment_=null,void(this.state="READY");s.byteLength=s.bytes.byteLength,this.mediaSecondsLoaded+=n.duration,s.cues.forEach(e=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new p.VTTCue(e.startTime,e.endTime,e.text):e)}),function(e){const t=e.cues;if(!t)return;const i={};for(let s=t.length-1;s>=0;s--){const r=t[s],n=`${r.startTime}-${r.endTime}-${r.text}`;i[n]?e.removeCue(r):i[n]=r}}(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(e,t){const i=e&&"vtt"===e.type,s=t&&"text"===t.type;i&&s&&super.handleData_(e,t)}updateTimingInfoEnd_(){}parseMp4VttCues_(e){const t=null===this.sourceUpdater_.videoTimestampOffset()?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();e.mp4VttCues.forEach(i=>{const s=i.start+t,r=i.end+t,n=new p.VTTCue(s,r,i.cueText);i.settings&&i.settings.split(" ").forEach(e=>{const t=e.split(":"),i=t[0],s=t[1];n[i]=isNaN(s)?s:Number(s)}),e.cues.push(n)})}parseVTTCues_(e){let t,i=!1;if("function"!=typeof p.WebVTT)throw new Ou;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues)return void this.parseMp4VttCues_(e);"function"==typeof p.TextDecoder?t=new p.TextDecoder("utf8"):(t=p.WebVTT.StringDecoder(),i=!0);const s=new p.WebVTT.Parser(p,p.vttjs,t);if(s.oncue=e.cues.push.bind(e.cues),s.ontimestampmap=t=>{e.timestampmap=t},s.onparsingerror=e=>{Fo.log.warn("Error encountered when parsing cues: "+e.message)},e.segment.map){let t=e.segment.map.bytes;i&&(t=Pu(t)),s.parse(t)}let r=e.bytes;i&&(r=Pu(r)),s.parse(r),s.flush()}updateTimeMapping_(e,t,i){const s=e.segment;if(!t)return;if(!e.cues.length)return void(s.empty=!0);const{MPEGTS:r,LOCAL:n}=e.timestampmap,a=r/Si.ONE_SECOND_IN_TS-n+t.mapping;if(e.cues.forEach(e=>{const i=e.endTime-e.startTime,s=this.handleRollover_(e.startTime+a,t.time);e.startTime=Math.max(s,0),e.endTime=Math.max(s+i,0)}),!i.syncInfo){const t=e.cues[0].startTime,r=e.cues[e.cues.length-1].startTime;i.syncInfo={mediaSequence:i.mediaSequence+e.mediaIndex,time:Math.min(t,r-s.duration)}}}handleRollover_(e,t){if(null===t)return e;let i=e*Si.ONE_SECOND_IN_TS;const s=t*Si.ONE_SECOND_IN_TS;let r;for(r=s<i?-8589934592:8589934592;Math.abs(i-s)>4294967296;)i+=r;return i/Si.ONE_SECOND_IN_TS}}const Ru=function(e,t){const i=e.cues;for(let e=0;e<i.length;e++){const s=i[e];if(t>=s.adStartTime&&t<=s.adEndTime)return s}return null};class Nu{constructor({start:e,end:t,segmentIndex:i,partIndex:s=null,appended:r=!1}){this.start_=e,this.end_=t,this.segmentIndex_=i,this.partIndex_=s,this.appended_=r}isInRange(e){return e>=this.start&&e<this.end}markAppended(){this.appended_=!0}resetAppendedStatus(){this.appended_=!1}get isAppended(){return this.appended_}get start(){return this.start_}get end(){return this.end_}get segmentIndex(){return this.segmentIndex_}get partIndex(){return this.partIndex_}}class Uu{constructor(e,t=[]){this.segmentSyncInfo_=e,this.partsSyncInfo_=t}get segmentSyncInfo(){return this.segmentSyncInfo_}get partsSyncInfo(){return this.partsSyncInfo_}get hasPartsSyncInfo(){return this.partsSyncInfo_.length>0}resetAppendStatus(){this.segmentSyncInfo_.resetAppendedStatus(),this.partsSyncInfo_.forEach(e=>e.resetAppendedStatus())}}class Bu{constructor(){this.storage_=new Map,this.diagnostics_="",this.isReliable_=!1,this.start_=-1/0,this.end_=1/0}get start(){return this.start_}get end(){return this.end_}get diagnostics(){return this.diagnostics_}get isReliable(){return this.isReliable_}resetAppendedStatus(){this.storage_.forEach(e=>e.resetAppendStatus())}update(e,t){const{mediaSequence:i,segments:s}=e;if(this.isReliable_=this.isReliablePlaylist_(i,s),this.isReliable_)return this.updateStorage_(s,i,this.calculateBaseTime_(i,s,t))}getSyncInfoForTime(e){for(const{segmentSyncInfo:t,partsSyncInfo:i}of this.storage_.values())if(i.length){for(const t of i)if(t.isInRange(e))return t}else if(t.isInRange(e))return t;return null}getSyncInfoForMediaSequence(e){return this.storage_.get(e)}updateStorage_(e,t,i){const s=new Map;let r="\n",n=i,a=t;this.start_=n,e.forEach((e,t)=>{const i=this.storage_.get(a),o=n,l=o+e.duration,d=Boolean(i&&i.segmentSyncInfo&&i.segmentSyncInfo.isAppended),u=new Nu({start:o,end:l,appended:d,segmentIndex:t});e.syncInfo=u;let c=n;const h=(e.parts||[]).map((e,s)=>{const n=c,o=c+e.duration,l=Boolean(i&&i.partsSyncInfo&&i.partsSyncInfo[s]&&i.partsSyncInfo[s].isAppended),d=new Nu({start:n,end:o,appended:l,segmentIndex:t,partIndex:s});return c=o,r+=`Media Sequence: ${a}.${s} | Range: ${n} --\x3e ${o} | Appended: ${l}\n`,e.syncInfo=d,d});s.set(a,new Uu(u,h)),r+=`${Kd(e.resolvedUri)} | Media Sequence: ${a} | Range: ${o} --\x3e ${l} | Appended: ${d}\n`,a++,n=l}),this.end_=n,this.storage_=s,this.diagnostics_=r}calculateBaseTime_(e,t,i){if(!this.storage_.size)return 0;if(this.storage_.has(e))return this.storage_.get(e).segmentSyncInfo.start;const s=Math.min(...this.storage_.keys());if(e<s){const i=s-e;let r=this.storage_.get(s).segmentSyncInfo.start;for(let e=0;e<i;e++){r-=t[e].duration}return r}return i}isReliablePlaylist_(e,t){return null!=e&&Array.isArray(t)&&t.length}}class Fu extends Bu{constructor(e){super(),this.parent_=e}calculateBaseTime_(e,t,i){if(!this.storage_.size){const t=this.parent_.getSyncInfoForMediaSequence(e);return t?t.segmentSyncInfo.start:0}return super.calculateBaseTime_(e,t,i)}}const qu=[{name:"VOD",run:(e,t,i,s,r)=>{if(i!==1/0){return{time:0,segmentIndex:0,partIndex:null}}return null}},{name:"MediaSequence",run:(e,t,i,s,r,n)=>{const a=e.getMediaSequenceSync(n);if(!a)return null;if(!a.isReliable)return null;const o=a.getSyncInfoForTime(r);return o?{time:o.start,partIndex:o.partIndex,segmentIndex:o.segmentIndex}:null}},{name:"ProgramDateTime",run:(e,t,i,s,r)=>{if(!Object.keys(e.timelineToDatetimeMappings).length)return null;let n=null,a=null;const o=nl(t);r=r||0;for(let i=0;i<o.length;i++){const s=o[t.endList||0===r?i:o.length-(i+1)],l=s.segment,d=e.timelineToDatetimeMappings[l.timeline];if(!d||!l.dateTimeObject)continue;let u=l.dateTimeObject.getTime()/1e3+d;if(l.parts&&"number"==typeof s.partIndex)for(let e=0;e<s.partIndex;e++)u+=l.parts[e].duration;const c=Math.abs(r-u);if(null!==a&&(0===c||a<c))break;a=c,n={time:u,segmentIndex:s.segmentIndex,partIndex:s.partIndex}}return n}},{name:"Segment",run:(e,t,i,s,r)=>{let n=null,a=null;r=r||0;const o=nl(t);for(let e=0;e<o.length;e++){const i=o[t.endList||0===r?e:o.length-(e+1)],l=i.segment,d=i.part&&i.part.start||l&&l.start;if(l.timeline===s&&void 0!==d){const e=Math.abs(r-d);if(null!==a&&a<e)break;(!n||null===a||a>=e)&&(a=e,n={time:d,segmentIndex:i.segmentIndex,partIndex:i.partIndex})}}return n}},{name:"Discontinuity",run:(e,t,i,s,r)=>{let n=null;if(r=r||0,t.discontinuityStarts&&t.discontinuityStarts.length){let i=null;for(let s=0;s<t.discontinuityStarts.length;s++){const a=t.discontinuityStarts[s],o=t.discontinuitySequence+s+1,l=e.discontinuities[o];if(l){const e=Math.abs(r-l.time);if(null!==i&&i<e)break;(!n||null===i||i>=e)&&(i=e,n={time:l.time,segmentIndex:a,partIndex:null})}}}return n}},{name:"Playlist",run:(e,t,i,s,r)=>{if(t.syncInfo){return{time:t.syncInfo.time,segmentIndex:t.syncInfo.mediaSequence-t.mediaSequence,partIndex:null}}return null}}];class ju extends Fo.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};const t=new Bu,i=new Fu(t),s=new Fu(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:s},this.logger_=Wo("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,s,r){if(t!==1/0){return qu.find(({name:e})=>"VOD"===e).run(this,e,t)}const n=this.runStrategies_(e,t,i,s,r);if(!n.length)return null;for(const t of n){const{syncPoint:i,strategy:r}=t,{segmentIndex:n,time:a}=i;if(n<0)continue;const o=a,l=o+e.segments[n].duration;if(this.logger_(`Strategy: ${r}. Current time: ${s}. selected segment: ${n}. Time: [${o} -> ${l}]}`),s>=o&&s<l)return this.logger_("Found sync point with exact match: ",i),i}return this.selectSyncPoint_(n,{key:"time",value:s})}getExpiredTime(e,t){if(!e||!e.segments)return null;const i=this.runStrategies_(e,t,e.discontinuitySequence,0);if(!i.length)return null;const s=this.selectSyncPoint_(i,{key:"segmentIndex",value:0});return s.segmentIndex>0&&(s.time*=-1),Math.abs(s.time+cl({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:s.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,s,r){const n=[];for(let a=0;a<qu.length;a++){const o=qu[a],l=o.run(this,e,t,i,s,r);l&&(l.strategy=o.name,n.push({strategy:o.name,syncPoint:l}))}return n}selectSyncPoint_(e,t){let i=e[0].syncPoint,s=Math.abs(e[0].syncPoint[t.key]-t.value),r=e[0].strategy;for(let n=1;n<e.length;n++){const a=Math.abs(e[n].syncPoint[t.key]-t.value);a<s&&(s=a,i=e[n].syncPoint,r=e[n].strategy)}return this.logger_(`syncPoint for [${t.key}: ${t.value}] chosen with strategy [${r}]: [time:${i.time}, segmentIndex:${i.segmentIndex}`+("number"==typeof i.partIndex?`,partIndex:${i.partIndex}`:"")+"]"),i}saveExpiredSegmentInfo(e,t){const i=t.mediaSequence-e.mediaSequence;if(i>86400)Fo.log.warn(`Not saving expired segment info. Media sequence gap ${i} is too large.`);else for(let s=i-1;s>=0;s--){const i=e.segments[s];if(i&&void 0!==i.start){t.syncInfo={mediaSequence:e.mediaSequence+s,time:i.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){const t=e.segments[0],i=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-i}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){const i=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),s=e.segment;i&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:s.start}));const r=s.dateTimeObject;s.discontinuity&&t&&r&&(this.timelineToDatetimeMappings[s.timeline]=-r.getTime()/1e3)}timestampOffsetForTimeline(e){return void 0===this.timelines[e]?null:this.timelines[e].time}mappingForTimeline(e){return void 0===this.timelines[e]?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,i){const s=e.segment,r=e.part;let n,a,o=this.timelines[e.timeline];if("number"==typeof e.timestampOffset)o={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=o,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${o.time}] [mapping: ${o.mapping}]`)),n=e.startOfSegment,a=t.end+o.mapping;else{if(!o)return!1;n=t.start+o.mapping,a=t.end+o.mapping}return r&&(r.start=n,r.end=a),(!s.start||n<s.start)&&(s.start=n),s.end=a,!0}saveDiscontinuitySyncInfo_(e){const t=e.playlist,i=e.segment;if(i.discontinuity)this.discontinuities[i.timeline]={time:i.start,accuracy:0};else if(t.discontinuityStarts&&t.discontinuityStarts.length)for(let s=0;s<t.discontinuityStarts.length;s++){const r=t.discontinuityStarts[s],n=t.discontinuitySequence+s+1,a=r-e.mediaIndex,o=Math.abs(a);if(!this.discontinuities[n]||this.discontinuities[n].accuracy>o){let s;s=a<0?i.start-cl({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:r}):i.end+cl({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:r}),this.discontinuities[n]={time:s,accuracy:o}}}}dispose(){this.trigger("dispose"),this.off()}}class Vu extends Fo.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange({type:e,from:t,to:i}){return"number"==typeof t&&"number"==typeof i&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:i},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:i}){if("number"==typeof t&&"number"==typeof i){this.lastTimelineChanges_[e]={type:e,from:t,to:i},delete this.pendingTimelineChanges_[e];const s={timelineChangeInfo:{from:t,to:i}};this.trigger({type:"timelinechange",metadata:s})}return this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}const $u=ud(cd(function(){var e=function(){function e(){this.listeners={}}var t=e.prototype;return t.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)},t.off=function(e,t){if(!this.listeners[e])return!1;var i=this.listeners[e].indexOf(t);return this.listeners[e]=this.listeners[e].slice(0),this.listeners[e].splice(i,1),i>-1},t.trigger=function(e){var t=this.listeners[e];if(t)if(2===arguments.length)for(var i=t.length,s=0;s<i;++s)t[s].call(this,arguments[1]);else for(var r=Array.prototype.slice.call(arguments,1),n=t.length,a=0;a<n;++a)t[a].apply(this,r)},t.dispose=function(){this.listeners={}},t.pipe=function(e){this.on("data",function(t){e.push(t)})},e}();
27
27
  /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */let t=null;class i{constructor(e){let i,s,r;t||(t=function(){const e=[[[],[],[],[],[]],[[],[],[],[],[]]],t=e[0],i=e[1],s=t[4],r=i[4];let n,a,o;const l=[],d=[];let u,c,h,p,m,g;for(n=0;n<256;n++)d[(l[n]=n<<1^283*(n>>7))^n]=n;for(a=o=0;!s[a];a^=u||1,o=d[o]||1)for(p=o^o<<1^o<<2^o<<3^o<<4,p=p>>8^255&p^99,s[a]=p,r[p]=a,h=l[c=l[u=l[a]]],g=16843009*h^65537*c^257*u^16843008*a,m=257*l[p]^16843008*p,n=0;n<4;n++)t[n][a]=m=m<<24^m>>>8,i[n][p]=g=g<<24^g>>>8;for(n=0;n<5;n++)t[n]=t[n].slice(0),i[n]=i[n].slice(0);return e}()),this._tables=[[t[0][0].slice(),t[0][1].slice(),t[0][2].slice(),t[0][3].slice(),t[0][4].slice()],[t[1][0].slice(),t[1][1].slice(),t[1][2].slice(),t[1][3].slice(),t[1][4].slice()]];const n=this._tables[0][4],a=this._tables[1],o=e.length;let l=1;if(4!==o&&6!==o&&8!==o)throw new Error("Invalid aes key size");const d=e.slice(0),u=[];for(this._key=[d,u],i=o;i<4*o+28;i++)r=d[i-1],(i%o===0||8===o&&i%o===4)&&(r=n[r>>>24]<<24^n[r>>16&255]<<16^n[r>>8&255]<<8^n[255&r],i%o===0&&(r=r<<8^r>>>24^l<<24,l=l<<1^283*(l>>7))),d[i]=d[i-o]^r;for(s=0;i;s++,i--)r=d[3&s?i:i-4],u[s]=i<=4||s<4?r:a[0][n[r>>>24]]^a[1][n[r>>16&255]]^a[2][n[r>>8&255]]^a[3][n[255&r]]}decrypt(e,t,i,s,r,n){const a=this._key[1];let o,l,d,u=e^a[0],c=s^a[1],h=i^a[2],p=t^a[3];const m=a.length/4-2;let g,f=4;const y=this._tables[1],_=y[0],b=y[1],v=y[2],T=y[3],S=y[4];for(g=0;g<m;g++)o=_[u>>>24]^b[c>>16&255]^v[h>>8&255]^T[255&p]^a[f],l=_[c>>>24]^b[h>>16&255]^v[p>>8&255]^T[255&u]^a[f+1],d=_[h>>>24]^b[p>>16&255]^v[u>>8&255]^T[255&c]^a[f+2],p=_[p>>>24]^b[u>>16&255]^v[c>>8&255]^T[255&h]^a[f+3],f+=4,u=o,c=l,h=d;for(g=0;g<4;g++)r[(3&-g)+n]=S[u>>>24]<<24^S[c>>16&255]<<16^S[h>>8&255]<<8^S[255&p]^a[f++],o=u,u=c,c=h,h=p,p=o}}class s extends e{constructor(){super(e),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(e){this.jobs.push(e),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}const r=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24};class n{constructor(e,t,i,a){const o=n.STEP,l=new Int32Array(e.buffer),d=new Uint8Array(e.byteLength);let u=0;for(this.asyncStream_=new s,this.asyncStream_.push(this.decryptChunk_(l.subarray(u,u+o),t,i,d)),u=o;u<l.length;u+=o)i=new Uint32Array([r(l[u-4]),r(l[u-3]),r(l[u-2]),r(l[u-1])]),this.asyncStream_.push(this.decryptChunk_(l.subarray(u,u+o),t,i,d));this.asyncStream_.push(function(){var e;
28
28
  /*! @name aes-decrypter @version 4.0.2 @license Apache-2.0 */a(null,(e=d).subarray(0,e.byteLength-e[e.byteLength-1]))})}static get STEP(){return 32e3}decryptChunk_(e,t,s,n){return function(){const a=function(e,t,s){const n=new Int32Array(e.buffer,e.byteOffset,e.byteLength>>2),a=new i(Array.prototype.slice.call(t)),o=new Uint8Array(e.byteLength),l=new Int32Array(o.buffer);let d,u,c,h,p,m,g,f,y;for(d=s[0],u=s[1],c=s[2],h=s[3],y=0;y<n.length;y+=4)p=r(n[y]),m=r(n[y+1]),g=r(n[y+2]),f=r(n[y+3]),a.decrypt(p,m,g,f,l,y),l[y]=r(l[y]^d),l[y+1]=r(l[y+1]^u),l[y+2]=r(l[y+2]^c),l[y+3]=r(l[y+3]^h),d=p,u=m,c=g,h=f;return o}(e,t,s);n.set(a,e.byteOffset)}}}var a,o="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};a="undefined"!=typeof window?window:void 0!==o?o:"undefined"!=typeof self?self:{};var l=a.BigInt||Number;l("0x1"),l("0x100"),l("0x10000"),l("0x1000000"),l("0x100000000"),l("0x10000000000"),l("0x1000000000000"),l("0x100000000000000"),l("0x10000000000000000"),function(){var e=new Uint16Array([65484]),t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);255===t[0]||t[0]}();const d=function(e){const t={};return Object.keys(e).forEach(i=>{const s=e[i];var r;r=s,("function"===ArrayBuffer.isView?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer)?t[i]={bytes:s.buffer,byteOffset:s.byteOffset,byteLength:s.byteLength}:t[i]=s}),t};self.onmessage=function(e){const t=e.data,i=new Uint8Array(t.encrypted.bytes,t.encrypted.byteOffset,t.encrypted.byteLength),s=new Uint32Array(t.key.bytes,t.key.byteOffset,t.key.byteLength/4),r=new Uint32Array(t.iv.bytes,t.iv.byteOffset,t.iv.byteLength/4);new n(i,s,r,function(e,i){self.postMessage(d({source:t.source,decrypted:i}),[i.buffer])})}}));var Hu=dd($u);const zu=e=>{let t=e.default?"main":"alternative";return e.characteristics&&e.characteristics.indexOf("public.accessibility.describes-video")>=0&&(t="main-desc"),t},Wu=(e,t)=>{e.abort(),e.pause(),t&&t.activePlaylistLoader&&(t.activePlaylistLoader.pause(),t.activePlaylistLoader=null)},Gu=(e,t)=>{t.activePlaylistLoader=e,e.load()},Xu={AUDIO:(e,t)=>()=>{const{mediaTypes:{[e]:i},excludePlaylist:s}=t,r=i.activeTrack(),n=i.activeGroup(),a=(n.filter(e=>e.default)[0]||n[0]).id,o=i.tracks[a];if(r!==o){Fo.log.warn("Problem encountered loading the alternate audio track.Switching back to default.");for(const e in i.tracks)i.tracks[e].enabled=i.tracks[e]===o;i.onTrackChanged()}else s({error:{message:"Problem encountered loading the default audio track."}})},SUBTITLES:(e,t)=>()=>{const{mediaTypes:{[e]:i}}=t;Fo.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");const s=i.activeTrack();s&&(s.mode="disabled"),i.onTrackChanged()}},Ku={AUDIO:(e,t,i)=>{if(!t)return;const{tech:s,requestOptions:r,segmentLoaders:{[e]:n}}=i;t.on("loadedmetadata",()=>{const e=t.media();n.playlist(e,r),(!s.paused()||e.endList&&"none"!==s.preload())&&n.load()}),t.on("loadedplaylist",()=>{n.playlist(t.media(),r),s.paused()||n.load()}),t.on("error",Xu[e](e,i))},SUBTITLES:(e,t,i)=>{const{tech:s,requestOptions:r,segmentLoaders:{[e]:n},mediaTypes:{[e]:a}}=i;t.on("loadedmetadata",()=>{const e=t.media();n.playlist(e,r),n.track(a.activeTrack()),(!s.paused()||e.endList&&"none"!==s.preload())&&n.load()}),t.on("loadedplaylist",()=>{n.playlist(t.media(),r),s.paused()||n.load()}),t.on("error",Xu[e](e,i))}},Yu={AUDIO:(e,t)=>{const{vhs:i,sourceType:s,segmentLoaders:{[e]:r},requestOptions:n,main:{mediaGroups:a},mediaTypes:{[e]:{groups:o,tracks:l,logger_:d}},mainPlaylistLoader:u}=t,c=vl(u.main);a[e]&&0!==Object.keys(a[e]).length||(a[e]={main:{default:{default:!0}}},c&&(a[e].main.default.playlists=u.main.playlists));for(const r in a[e]){o[r]||(o[r]=[]);for(const h in a[e][r]){let p,m=a[e][r][h];if(c?(d(`AUDIO group '${r}' label '${h}' is a main playlist`),m.isMainPlaylist=!0,p=null):p="vhs-json"===s&&m.playlists?new Bl(m.playlists[0],i,n):m.resolvedUri?new Bl(m.resolvedUri,i,n):m.playlists&&"dash"===s?new ad(m.playlists[0],i,n,u):null,m=Go({id:h,playlistLoader:p},m),Ku[e](e,m.playlistLoader,t),o[r].push(m),void 0===l[h]){const e=new Fo.AudioTrack({id:h,kind:zu(m),enabled:!1,language:m.language,default:m.default,label:h});l[h]=e}}}r.on("error",Xu[e](e,t))},SUBTITLES:(e,t)=>{const{tech:i,vhs:s,sourceType:r,segmentLoaders:{[e]:n},requestOptions:a,main:{mediaGroups:o},mediaTypes:{[e]:{groups:l,tracks:d}},mainPlaylistLoader:u}=t;for(const n in o[e]){l[n]||(l[n]=[]);for(const c in o[e][n]){if(!s.options_.useForcedSubtitles&&o[e][n][c].forced)continue;let h,p=o[e][n][c];if("hls"===r)h=new Bl(p.resolvedUri,s,a);else if("dash"===r){if(!p.playlists.filter(e=>e.excludeUntil!==1/0).length)return;h=new ad(p.playlists[0],s,a,u)}else"vhs-json"===r&&(h=new Bl(p.playlists?p.playlists[0]:p.resolvedUri,s,a));if(p=Go({id:c,playlistLoader:h},p),Ku[e](e,p.playlistLoader,t),l[n].push(p),void 0===d[c]){const e=i.addRemoteTextTrack({id:c,kind:"subtitles",default:p.default&&p.autoselect,language:p.language,label:c},!1).track;d[c]=e}}}n.on("error",Xu[e](e,t))},"CLOSED-CAPTIONS":(e,t)=>{const{tech:i,main:{mediaGroups:s},mediaTypes:{[e]:{groups:r,tracks:n}}}=t;for(const t in s[e]){r[t]||(r[t]=[]);for(const a in s[e][t]){const o=s[e][t][a];if(!/^(?:CC|SERVICE)/.test(o.instreamId))continue;const l=i.options_.vhs&&i.options_.vhs.captionServices||{};let d={label:a,language:o.language,instreamId:o.instreamId,default:o.default&&o.autoselect};if(l[d.instreamId]&&(d=Go(d,l[d.instreamId])),void 0===d.default&&delete d.default,r[t].push(Go({id:a},o)),void 0===n[a]){const e=i.addRemoteTextTrack({id:d.instreamId,kind:"captions",default:d.default,language:d.language,label:d.label},!1).track;n[a]=e}}}}},Qu=(e,t)=>{for(let i=0;i<e.length;i++){if(_l(t,e[i]))return!0;if(e[i].playlists&&Qu(e[i].playlists,t))return!0}return!1},Ju={AUDIO:(e,t)=>()=>{const{mediaTypes:{[e]:{tracks:i}}}=t;for(const e in i)if(i[e].enabled)return i[e];return null},SUBTITLES:(e,t)=>()=>{const{mediaTypes:{[e]:{tracks:i}}}=t;for(const e in i)if("showing"===i[e].mode||"hidden"===i[e].mode)return i[e];return null}},Zu=e=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(t=>{Yu[t](t,e)});const{mediaTypes:t,mainPlaylistLoader:i,tech:s,vhs:r,segmentLoaders:{AUDIO:n,main:a}}=e;["AUDIO","SUBTITLES"].forEach(i=>{t[i].activeGroup=((e,t)=>i=>{const{mainPlaylistLoader:s,mediaTypes:{[e]:{groups:r}}}=t,n=s.media();if(!n)return null;let a=null;n.attributes[e]&&(a=r[n.attributes[e]]);const o=Object.keys(r);if(!a)if("AUDIO"===e&&o.length>1&&vl(t.main))for(let e=0;e<o.length;e++){const t=r[o[e]];if(Qu(t,n)){a=t;break}}else r.main?a=r.main:1===o.length&&(a=r[o[0]]);return void 0===i?a:null!==i&&a&&a.filter(e=>e.id===i.id)[0]||null})(i,e),t[i].activeTrack=Ju[i](i,e),t[i].onGroupChanged=((e,t)=>()=>{const{segmentLoaders:{[e]:i,main:s},mediaTypes:{[e]:r}}=t,n=r.activeTrack(),a=r.getActiveGroup(),o=r.activePlaylistLoader,l=r.lastGroup_;a&&l&&a.id===l.id||(r.lastGroup_=a,r.lastTrack_=n,Wu(i,r),a&&!a.isMainPlaylist&&(a.playlistLoader?(i.resyncLoader(),Gu(a.playlistLoader,r)):o&&s.resetEverything()))})(i,e),t[i].onGroupChanging=((e,t)=>()=>{const{segmentLoaders:{[e]:i},mediaTypes:{[e]:s}}=t;s.lastGroup_=null,i.abort(),i.pause()})(i,e),t[i].onTrackChanged=((e,t)=>()=>{const{mainPlaylistLoader:i,segmentLoaders:{[e]:s,main:r},mediaTypes:{[e]:n}}=t,a=n.activeTrack(),o=n.getActiveGroup(),l=n.activePlaylistLoader,d=n.lastTrack_;if((!d||!a||d.id!==a.id)&&(n.lastGroup_=o,n.lastTrack_=a,Wu(s,n),o)){if(o.isMainPlaylist){if(!a||!d||a.id===d.id)return;const e=t.vhs.playlistController_,s=e.selectPlaylist();if(e.media()===s)return;return n.logger_(`track change. Switching main audio from ${d.id} to ${a.id}`),i.pause(),r.resetEverything(),void e.fastQualityChange_(s)}if("AUDIO"===e){if(!o.playlistLoader)return r.setAudio(!0),void r.resetEverything();s.setAudio(!0),r.setAudio(!1)}l!==o.playlistLoader?(s.track&&s.track(a),s.resetEverything(),Gu(o.playlistLoader,n)):Gu(o.playlistLoader,n)}})(i,e),t[i].getActiveGroup=((e,{mediaTypes:t})=>()=>{const i=t[e].activeTrack();return i?t[e].activeGroup(i):null})(i,e)});const o=t.AUDIO.activeGroup();if(o){const e=(o.filter(e=>e.default)[0]||o[0]).id;t.AUDIO.tracks[e].enabled=!0,t.AUDIO.onGroupChanged(),t.AUDIO.onTrackChanged();t.AUDIO.getActiveGroup().playlistLoader?(a.setAudio(!1),n.setAudio(!0)):a.setAudio(!0)}i.on("mediachange",()=>{["AUDIO","SUBTITLES"].forEach(e=>t[e].onGroupChanged())}),i.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(e=>t[e].onGroupChanging())});const l=()=>{t.AUDIO.onTrackChanged(),s.trigger({type:"usage",name:"vhs-audio-change"})};s.audioTracks().addEventListener("change",l),s.remoteTextTracks().addEventListener("change",t.SUBTITLES.onTrackChanged),r.on("dispose",()=>{s.audioTracks().removeEventListener("change",l),s.remoteTextTracks().removeEventListener("change",t.SUBTITLES.onTrackChanged)}),s.clearTracks("audio");for(const e in t.AUDIO.tracks)s.audioTracks().addTrack(t.AUDIO.tracks[e])};class ec{constructor(){this.priority_=[],this.pathwayClones_=new Map}set version(e){1===e&&(this.version_=e)}set ttl(e){this.ttl_=e||300}set reloadUri(e){e&&(this.reloadUri_=Ho(this.reloadUri_,e))}set priority(e){e&&e.length&&(this.priority_=e)}set pathwayClones(e){e&&e.length&&(this.pathwayClones_=new Map(e.map(e=>[e.ID,e])))}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 tc extends Fo.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new ec,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=Wo("Content Steering"),this.xhr_=e,this.getBandwidth_=t}assignTagProperties(e,t){this.manifestType_=t.serverUri?"HLS":"DASH";const i=t.serverUri||t.serverURL;if(!i)return this.logger_(`steering manifest URL is ${i}, cannot request steering manifest.`),void this.trigger("error");i.startsWith("data:")?this.decodeDataUriManifest_(i.substring(i.indexOf(",")+1)):(this.steeringManifest.reloadUri=Ho(e,i),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering"))}requestSteeringManifest(e){const t=this.steeringManifest.reloadUri;if(!t)return;const i=e?t:this.getRequestURI(t);if(!i)return this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),void this.dispose();const s={contentSteeringInfo:{uri:i}};this.trigger({type:"contentsteeringloadstart",metadata:s}),this.request_=this.xhr_({uri:i,requestType:"content-steering-manifest"},(e,t)=>{if(e){if(410===t.status)return this.logger_(`manifest request 410 ${e}.`),this.logger_(`There will be no more content steering requests to ${i} this session.`),void this.excludedSteeringManifestURLs.add(i);if(429===t.status){const i=t.responseHeaders["retry-after"];return this.logger_(`manifest request 429 ${e}.`),this.logger_(`content steering will retry in ${i} seconds.`),void this.startTTLTimeout_(parseInt(i,10))}return this.logger_(`manifest failed to load ${e}.`),void this.startTTLTimeout_()}let r;this.trigger({type:"contentsteeringloadcomplete",metadata:s});try{r=JSON.parse(this.request_.responseText)}catch(e){const t={errorType:Fo.Error.StreamingContentSteeringParserError,error:e};this.trigger({type:"error",metadata:t})}this.assignSteeringProperties_(r);const n={contentSteeringInfo:s.contentSteeringInfo,contentSteeringManifest:{version:this.steeringManifest.version,reloadUri:this.steeringManifest.reloadUri,priority:this.steeringManifest.priority}};this.trigger({type:"contentsteeringparsed",metadata:n}),this.startTTLTimeout_()})}setProxyServerUrl_(e){const t=new p.URL(e),i=new p.URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){const t=JSON.parse(p.atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){const t=new p.URL(e),i=this.getPathway(),s=this.getBandwidth_();if(i){const e=`_${this.manifestType_}_pathway`;t.searchParams.set(e,i)}if(s){const e=`_${this.manifestType_}_throughput`;t.searchParams.set(e,s)}return t.toString()}assignSteeringProperties_(e){if(this.steeringManifest.version=e.VERSION,!this.steeringManifest.version)return this.logger_(`manifest version is ${e.VERSION}, which is not supported.`),void this.trigger("error");this.steeringManifest.ttl=e.TTL,this.steeringManifest.reloadUri=e["RELOAD-URI"],this.steeringManifest.priority=e["PATHWAY-PRIORITY"]||e["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=e["PATHWAY-CLONES"],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_("There are no available pathways for content steering. Ending content steering."),this.trigger("error"),this.dispose());const t=(e=>{for(const t of e)if(this.availablePathways_.has(t))return t;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==t&&(this.currentPathway=t,this.trigger("content-steering"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(e){if(!e)return null;const t=e=>this.excludedSteeringManifestURLs.has(e);if(this.proxyServerUrl_){const i=this.setProxyServerUrl_(e);if(!t(i))return i}const i=this.setSteeringParams_(e);return t(i)?null:i}startTTLTimeout_(e=this.steeringManifest.ttl){const t=1e3*e;this.ttlTimeout_=p.setTimeout(()=>{this.requestSteeringManifest()},t)}clearTTLTimeout_(){p.clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off("content-steering"),this.off("error"),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new ec}addAvailablePathway(e){e&&this.availablePathways_.add(e)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(e){return this.availablePathways_.delete(e)}didDASHTagChange(e,t){return!t&&this.steeringManifest.reloadUri||t&&(Ho(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}}let ic;const sc=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],rc=function(e){return this.audioSegmentLoader_[e]+this.mainSegmentLoader_[e]};class nc extends Fo.EventTarget{constructor(e){super(),this.fastQualityChange_=((e,t)=>{let i=null;return(...s)=>{clearTimeout(i),i=setTimeout(()=>{e.apply(null,s)},t)}})(this.fastQualityChange_.bind(this),100);const{src:t,withCredentials:i,tech:s,bandwidth:r,externVhs:n,useCueTags:a,playlistExclusionDuration:o,enableLowInitialPlaylist:l,sourceType:d,cacheEncryptionKeys:u,bufferBasedABR:c,leastPixelDiffSelector:h,captionServices:m,experimentalUseMMS:g}=e;if(!t)throw new Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:f}=e;null==f&&(f=1/0),ic=n,this.bufferBasedABR=Boolean(c),this.leastPixelDiffSelector=Boolean(h),this.withCredentials=i,this.tech_=s,this.vhs_=s.vhs,this.player_=e.player_,this.sourceType_=d,this.useCueTags_=a,this.playlistExclusionDuration=o,this.maxPlaylistRetries=f,this.enableLowInitialPlaylist=l,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:f,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=(()=>{const e={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(t=>{e[t]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:cu,activeTrack:cu,getActiveGroup:cu,onGroupChanged:cu,onTrackChanged:cu,lastTrack_:null,logger_:Wo(`MediaGroups[${t}]`)}}),e})(),g&&p.ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new p.ManagedMediaSource,this.usingManagedMediaSource_=!0,Fo.log("Using ManagedMediaSource")):p.MediaSource&&(this.mediaSource=new p.MediaSource),this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.load=this.load.bind(this),this.pause=this.pause.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.mediaSource.addEventListener("startstreaming",this.load),this.mediaSource.addEventListener("endstreaming",this.pause),this.seekable_=Xo(),this.hasPlayed_=!1,this.syncController_=new ju(e),this.segmentMetadataTrack_=s.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.decrypter_=new Hu,this.sourceUpdater_=new Du(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new Vu,this.keyStatusMap_=new Map;const y={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:m,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:r,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:u,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_="dash"===this.sourceType_?new ad(t,this.vhs_,Go(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new Bl(t,this.vhs_,Go(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new uu(Go(y,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new uu(Go(y,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new Mu(Go(y,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((e,t)=>{function i(){s.off("vttjserror",r),e()}function r(){s.off("vttjsloaded",i),t()}s.one("vttjsloaded",i),s.one("vttjserror",r),s.addWebVttScript_()})}),e);this.contentSteeringController_=new tc(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_())),sc.forEach(e=>{this[e+"_"]=rc.bind(this,e)}),this.logger_=Wo("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.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;const _="none"===this.tech_.preload()?"play":"loadstart";this.tech_.one(_,()=>{const e=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-e,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){const e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return-1===e||-1===t?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e="abr"){const t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,i){const s=this.media(),r=s&&(s.id||s.uri),n=e&&(e.id||e.uri);if(r&&r!==n){this.logger_(`switch media ${r} -> ${n} from ${t}`);const i={renditionInfo:{id:n,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:"renditionselected",metadata:i}),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,i)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{const t=this.mediaTypes_[e],i=t?t.activeGroup():null,s=this.contentSteeringController_.getPathway();if(i&&s){const t=(i.length?i[0].playlists:i.playlists).filter(e=>e.attributes.serviceLocation===s);t.length&&this.mediaTypes_[e].activePlaylistLoader.media(t[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=p.setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){this.tech_.scrubbing&&this.tech_.scrubbing()||(p.clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){const e=this.main(),t=e&&e.playlists||[];if(!e||!e.mediaGroups||!e.mediaGroups.AUDIO)return t;const i=e.mediaGroups.AUDIO,s=Object.keys(i);let r;if(Object.keys(this.mediaTypes_.AUDIO.groups).length)r=this.mediaTypes_.AUDIO.activeTrack();else{const e=i.main||s.length&&i[s[0]];for(const t in e)if(e[t].default){r={label:t};break}}if(!r)return t;const n=[];for(const t in i)if(i[t][r.label]){const s=i[t][r.label];if(s.playlists&&s.playlists.length)n.push.apply(n,s.playlists);else if(s.uri)n.push(s);else if(e.playlists.length)for(let i=0;i<e.playlists.length;i++){const s=e.playlists[i];s.attributes&&s.attributes.AUDIO&&s.attributes.AUDIO===t&&n.push(s)}}return n.length?n:t}setupMainPlaylistLoaderListeners_(){this.mainPlaylistLoader_.on("loadedmetadata",()=>{const e=this.mainPlaylistLoader_.media(),t=1.5*e.targetDuration*1e3;yl(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,e.endList&&"none"!==this.tech_.preload()&&(this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.mainSegmentLoader_.load()),Zu({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),e),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger("selectedinitialmedia"):this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",()=>{this.trigger("selectedinitialmedia")})}),this.mainPlaylistLoader_.on("loadedplaylist",()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let e=this.mainPlaylistLoader_.media();if(!e){let t;if(this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_(),this.enableLowInitialPlaylist&&(t=this.selectInitialPlaylist()),t||(t=this.selectPlaylist()),!t||!this.shouldSwitchToMedia_(t))return;this.initialMedia_=t,this.switchMedia_(this.initialMedia_,"initial");if(!("vhs-json"===this.sourceType_&&this.initialMedia_.segments))return;e=this.initialMedia_}this.handleUpdatedMediaPlaylist(e)}),this.mainPlaylistLoader_.on("error",()=>{const e=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:e.playlist,error:e})}),this.mainPlaylistLoader_.on("mediachanging",()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()}),this.mainPlaylistLoader_.on("mediachange",()=>{const e=this.mainPlaylistLoader_.media(),t=1.5*e.targetDuration*1e3;yl(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,"dash"===this.sourceType_&&this.mainPlaylistLoader_.isPaused&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})}),this.mainPlaylistLoader_.on("playlistunchanged",()=>{const e=this.mainPlaylistLoader_.media();if("playlist-unchanged"===e.lastExcludeReason_)return;this.stuckAtPlaylistEnd_(e)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))}),this.mainPlaylistLoader_.on("renditiondisabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})}),this.mainPlaylistLoader_.on("renditionenabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-enabled"})});["manifestrequeststart","manifestrequestcomplete","manifestparsestart","manifestparsecomplete","playlistrequeststart","playlistrequestcomplete","playlistparsestart","playlistparsecomplete","renditiondisabled","renditionenabled"].forEach(e=>{this.mainPlaylistLoader_.on(e,e=>{this.player_.trigger(G({},e))})})}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!e.endList),this.tech_.paused()||(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){const i=e.mediaGroups||{};let s=!0;const r=Object.keys(i.AUDIO);for(const e in i.AUDIO)for(const t in i.AUDIO[e]){i.AUDIO[e][t].uri||(s=!1)}s&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(i.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),ic.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),r.length&&Object.keys(i.AUDIO[r[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(e){const t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,i=this.tech_.currentTime(),s=this.bufferLowWaterLine(),r=this.bufferHighWaterLine();return function({currentPlaylist:e,buffered:t,currentTime:i,nextPlaylist:s,bufferLowWaterLine:r,bufferHighWaterLine:n,duration:a,bufferBasedABR:o,log:l}){if(!s)return Fo.log.warn("We received no playlist to switch to. Please check your stream."),!1;const d=`allowing switch ${e&&e.id||"null"} -> ${s.id}`;if(!e)return l(`${d} as current playlist is not set`),!0;if(s.id===e.id)return!1;const u=Boolean(Jo(t,i).length);if(!e.endList)return u||"number"!=typeof e.partTargetDuration?(l(`${d} as current playlist is live`),!0):(l(`not ${d} as current playlist is live llhls, but currentTime isn't in buffered.`),!1);const c=sl(t,i),h=o?od.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:od.MAX_BUFFER_LOW_WATER_LINE;if(a<h)return l(`${d} as duration < max low water line (${a} < ${h})`),!0;const p=s.attributes.BANDWIDTH,m=e.attributes.BANDWIDTH;if(p<m&&(!o||c<n)){let e=`${d} as next bandwidth < current bandwidth (${p} < ${m})`;return o&&(e+=` and forwardBuffer < bufferHighWaterLine (${c} < ${n})`),l(e),!0}if((!o||p>m)&&c>=r){let e=`${d} as forwardBuffer >= bufferLowWaterLine (${c} >= ${r})`;return o&&(e+=` and next bandwidth > current bandwidth (${p} > ${m})`),l(e),!0}return l(`not ${d} as no switching criteria met`),!1}({buffered:this.tech_.buffered(),currentTime:i,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:s,bufferHighWaterLine:r,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")}),this.mainSegmentLoader_.on("timeout",()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()}),this.bufferBasedABR||this.mainSegmentLoader_.on("progress",()=>{this.trigger("progress")}),this.mainSegmentLoader_.on("error",()=>{const e=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:e.playlist,error:e})}),this.mainSegmentLoader_.on("appenderror",()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.mainSegmentLoader_.on("timestampoffset",()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})}),this.audioSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.audioSegmentLoader_.on("appenderror",()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("ended",()=>{this.logger_("main segment loader ended"),this.onEndOfStream()}),this.timelineChangeController_.on("audioTimelineBehind",()=>{const e=this.audioSegmentLoader_.pendingSegment_;if(!e||!e.segment||!e.segment.syncInfo)return;const t=e.segment.syncInfo.end+.01;this.tech_.setCurrentTime(t)}),this.timelineChangeController_.on("fixBadTimelineChange",()=>{this.logger_("Fix bad timeline change. Restarting al segment loaders..."),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}),this.mainSegmentLoader_.on("earlyabort",e=>{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 e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();const e=this.getCodecsOrExclude_();e&&this.sourceUpdater_.addOrChangeSourceBuffers(e)};this.mainSegmentLoader_.on("trackinfo",e),this.audioSegmentLoader_.on("trackinfo",e),this.mainSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("ended",()=>{this.logger_("audioSegmentLoader ended"),this.onEndOfStream()});["segmentselected","segmentloadstart","segmentloaded","segmentkeyloadstart","segmentkeyloadcomplete","segmentdecryptionstart","segmentdecryptioncomplete","segmenttransmuxingstart","segmenttransmuxingcomplete","segmenttransmuxingtrackinfoavailable","segmenttransmuxingtiminginfoavailable","segmentappendstart","appendsdone","bandwidthupdated","timelinechange","codecschange"].forEach(e=>{this.mainSegmentLoader_.on(e,e=>{this.player_.trigger(G({},e))}),this.audioSegmentLoader_.on(e,e=>{this.player_.trigger(G({},e))}),this.subtitleSegmentLoader_.on(e,e=>{this.player_.trigger(G({},e))})})}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}pause(){this.mainSegmentLoader_.pause(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.pause(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.pause()}fastQualityChange_(e=this.selectPlaylist()){e&&e===this.mainPlaylistLoader_.media()?this.logger_("skipping fastQualityChange because new media is same as old"):(this.switchMedia_(e,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0)}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();const e=this.tech_.seekable();return this.tech_.duration()===1/0&&this.tech_.currentTime()<e.start(0)?this.tech_.setCurrentTime(e.end(e.length-1)):void 0}setupFirstPlay(){const e=this.mainPlaylistLoader_.media();if(!e||this.tech_.paused()||this.hasPlayed_)return!1;if(!e.endList||e.start){const t=this.seekable();if(!t.length)return!1;const i=t.end(0);let s=i;if(e.start){const r=e.start.timeOffset;s=r<0?Math.max(i+r,t.start(0)):Math.min(i,r)}this.trigger("firstplay"),this.tech_.setCurrentTime(s)}return this.hasPlayed_=!0,this.load(),!0}handleSourceOpen_(){if(this.tryToCreateSourceBuffers_(),this.tech_.autoplay()){const e=this.tech_.play();void 0!==e&&"function"==typeof e.then&&e.then(null,e=>{})}this.trigger("sourceopen")}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;const e=this.inbandTextTracks_.metadataTrack_.cues;if(!e||!e.length)return;const t=this.duration();e[e.length-1].endTime=isNaN(t)||Math.abs(t)===1/0?Number.MAX_VALUE:t}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let e=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){const t=this.mainSegmentLoader_.getCurrentMediaInfo_();e=!t||t.hasVideo?e&&this.audioSegmentLoader_.ended_:this.audioSegmentLoader_.ended_}e&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(e){if(!this.seekable().length)return!1;const t=this.syncController_.getExpiredTime(e,this.duration());if(null===t)return!1;const i=ic.Playlist.playlistEnd(e,t),s=this.tech_.currentTime(),r=this.tech_.buffered();if(!r.length)return i-s<=Yo;const n=r.end(r.length-1);return n-s<=Yo&&i-n<=Yo}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:i}){if(e=e||this.mainPlaylistLoader_.media(),i=i||t.playlistExclusionDuration||this.playlistExclusionDuration,!e)return this.error=t,void("open"!==this.mediaSource.readyState?this.trigger("error"):this.sourceUpdater_.endOfStream("network"));e.playlistErrors_++;const s=this.mainPlaylistLoader_.main.playlists,r=s.filter(gl),n=1===r.length&&r[0]===e;if(1===s.length&&i!==1/0)return Fo.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(n);if(n){if(this.main().contentSteering){const t=this.pathwayAttribute_(e),i=1e3*this.contentSteeringController_.steeringManifest.ttl;return this.contentSteeringController_.excludePathway(t),this.excludeThenChangePathway_(),void setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(t)},i)}let t=!1;s.forEach(i=>{if(i===e)return;const s=i.excludeUntil;void 0!==s&&s!==1/0&&(t=!0,delete i.excludeUntil)}),t&&(Fo.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),this.tech_.trigger("retryplaylist"))}let a;a=e.playlistErrors_>this.maxPlaylistRetries?1/0:Date.now()+1e3*i,e.excludeUntil=a,t.reason&&(e.lastExcludeReason_=t.reason),this.tech_.trigger("excludeplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});const o=this.selectPlaylist();if(!o)return this.error="Playback cannot continue. No available working or supported playlists.",void this.trigger("error");const l=t.internal?this.logger_:Fo.log.warn,d=t.message?" "+t.message:"";l(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${d} Switching to playlist ${o.id}.`),o.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),o.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);const u=o.targetDuration/2*1e3||5e3,c="number"==typeof o.lastRequest&&Date.now()-o.lastRequest<=u;return this.switchMedia_(o,"exclude",n||c)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(e,t){const i=[],s="all"===e;(s||"main"===e)&&i.push(this.mainPlaylistLoader_);const r=[];(s||"audio"===e)&&r.push("AUDIO"),(s||"subtitle"===e)&&(r.push("CLOSED-CAPTIONS"),r.push("SUBTITLES")),r.forEach(e=>{const t=this.mediaTypes_[e]&&this.mediaTypes_[e].activePlaylistLoader;t&&i.push(t)}),["main","audio","subtitle"].forEach(t=>{const s=this[`${t}SegmentLoader_`];!s||e!==t&&"all"!==e||i.push(s)}),i.forEach(e=>t.forEach(t=>{"function"==typeof e[t]&&e[t]()}))}setCurrentTime(e){const t=Jo(this.tech_.buffered(),e);return this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media()&&this.mainPlaylistLoader_.media().segments?t&&t.length?e:(this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),void this.load()):0}duration(){if(!this.mainPlaylistLoader_)return 0;const e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:ic.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}getSeekableRange_(e,t){const i=e.media();if(!i)return null;const s=this.syncController_.getMediaSequenceSync(t);if(s&&s.isReliable){const e=s.start,t=s.end;if(!isFinite(e)||!isFinite(t))return null;const r=ic.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i),n=Math.max(0,t-r);return n<e?null:Xo([[e,n]])}const r=this.syncController_.getExpiredTime(i,this.duration());if(null===r)return null;const n=ic.Playlist.seekable(i,r,ic.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i));return n.length?n:null}computeFinalSeekable_(e,t){if(!t)return e;const i=e.start(0),s=e.end(0),r=t.start(0),n=t.end(0);return r>s||i>n?e:Xo([[Math.max(i,r),Math.min(s,n)]])}onSyncInfoUpdate_(){if(!this.mainPlaylistLoader_)return;const e=this.getSeekableRange_(this.mainPlaylistLoader_,"main");if(!e)return;let t;if(this.mediaTypes_.AUDIO.activePlaylistLoader&&(t=this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader,"audio"),!t))return;const i=this.seekable_;if(this.seekable_=this.computeFinalSeekable_(e,t),!this.seekable_)return;if(i&&i.length&&this.seekable_.length&&i.start(0)===this.seekable_.start(0)&&i.end(0)===this.seekable_.end(0))return;this.logger_(`seekable updated [${el(this.seekable_)}]`);const s={seekableRanges:this.seekable_};this.trigger({type:"seekablerangeschanged",metadata:s}),this.tech_.trigger("seekablechanged")}updateDuration(e){if(this.updateDuration_&&(this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.updateDuration_=null),"open"!==this.mediaSource.readyState)return this.updateDuration_=this.updateDuration.bind(this,e),void this.mediaSource.addEventListener("sourceopen",this.updateDuration_);if(e){const e=this.seekable();if(!e.length)return;return void((isNaN(this.mediaSource.duration)||this.mediaSource.duration<e.end(e.length-1))&&this.sourceUpdater_.setDuration(e.end(e.length-1)))}const t=this.tech_.buffered();let i=ic.Playlist.duration(this.mainPlaylistLoader_.media());t.length>0&&(i=Math.max(i,t.end(t.length-1))),this.mediaSource.duration!==i&&this.sourceUpdater_.setDuration(i)}dispose(){this.trigger("dispose"),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach(e=>{const t=this.mediaTypes_[e].groups;for(const e in t)t[e].forEach(e=>{e.playlistLoader&&e.playlistLoader.dispose()})}),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){const e=!!this.mediaTypes_.AUDIO.activePlaylistLoader,t=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),i=!e||!!this.audioSegmentLoader_.getCurrentMediaInfo_();return!(!t||!i)}getCodecsOrExclude_(){const e={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},t=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();e.video=e.main;const i=jd(this.main(),t),s={},r=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(e.main.hasVideo&&(s.video=i.video||e.main.videoCodec||"avc1.4d400d"),e.main.isMuxed&&(s.video+=`,${i.audio||e.main.audioCodec||_e}`),(e.main.hasAudio&&!e.main.isMuxed||e.audio.hasAudio||r)&&(s.audio=i.audio||e.main.audioCodec||e.audio.audioCodec||_e,e.audio.isFmp4=e.main.hasAudio&&!e.main.isMuxed?e.main.isFmp4:e.audio.isFmp4),!s.audio&&!s.video)return void this.excludePlaylist({playlistToExclude:t,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});const n=(e,t)=>e?fe(t,this.usingManagedMediaSource_):ye(t),a={};let o;if(["video","audio"].forEach(function(t){if(s.hasOwnProperty(t)&&!n(e[t].isFmp4,s[t])){const i=e[t].isFmp4?"browser":"muxer";a[i]=a[i]||[],a[i].push(s[t]),"audio"===t&&(o=i)}}),r&&o&&t.attributes.AUDIO){const e=t.attributes.AUDIO;this.main().playlists.forEach(i=>{(i.attributes&&i.attributes.AUDIO)===e&&i!==t&&(i.excludeUntil=1/0)}),this.logger_(`excluding audio group ${e} as ${o} does not support codec(s): "${s.audio}"`)}if(Object.keys(a).length){const e=Object.keys(a).reduce((e,t)=>(e&&(e+=", "),e+=`${t} does not support codec(s): "${a[t].join(",")}"`),"")+".";return void this.excludePlaylist({playlistToExclude:t,error:{internal:!0,message:e},playlistExclusionDuration:1/0})}if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){const e=[];if(["video","audio"].forEach(t=>{const i=(pe(this.sourceUpdater_.codecs[t]||"")[0]||{}).type,r=(pe(s[t]||"")[0]||{}).type;i&&r&&i.toLowerCase()!==r.toLowerCase()&&e.push(`"${this.sourceUpdater_.codecs[t]}" -> "${s[t]}"`)}),e.length)return void this.excludePlaylist({playlistToExclude:t,error:{message:`Codec switching not supported: ${e.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0})}return s}tryToCreateSourceBuffers_(){if("open"!==this.mediaSource.readyState||this.sourceUpdater_.hasCreatedSourceBuffers())return;if(!this.areMediaTypesKnown_())return;const e=this.getCodecsOrExclude_();if(!e)return;this.sourceUpdater_.createSourceBuffers(e);const t=[e.video,e.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(t)}excludeUnsupportedVariants_(){const e=this.main().playlists,t=[];Object.keys(e).forEach(i=>{const s=e[i];if(-1!==t.indexOf(s.id))return;t.push(s.id);const r=jd(this.main,s),n=[];!r.audio||ye(r.audio)||fe(r.audio,this.usingManagedMediaSource_)||n.push(`audio codec ${r.audio}`),!r.video||ye(r.video)||fe(r.video,this.usingManagedMediaSource_)||n.push(`video codec ${r.video}`),r.text&&"stpp.ttml.im1t"===r.text&&n.push(`text codec ${r.text}`),n.length&&(s.excludeUntil=1/0,this.logger_(`excluding ${s.id} for unsupported: ${n.join(", ")}`))})}excludeIncompatibleVariants_(e){const t=[],i=this.main().playlists,s=Fd(pe(e)),r=qd(s),n=s.video&&pe(s.video)[0]||null,a=s.audio&&pe(s.audio)[0]||null;Object.keys(i).forEach(e=>{const s=i[e];if(-1!==t.indexOf(s.id)||s.excludeUntil===1/0)return;t.push(s.id);const o=[],l=jd(this.mainPlaylistLoader_.main,s),d=qd(l);if(l.audio||l.video){if(d!==r&&o.push(`codec count "${d}" !== "${r}"`),!this.sourceUpdater_.canChangeType()){const e=l.video&&pe(l.video)[0]||null,t=l.audio&&pe(l.audio)[0]||null;e&&n&&e.type.toLowerCase()!==n.type.toLowerCase()&&o.push(`video codec "${e.type}" !== "${n.type}"`),t&&a&&t.type.toLowerCase()!==a.type.toLowerCase()&&o.push(`audio codec "${t.type}" !== "${a.type}"`)}o.length&&(s.excludeUntil=1/0,this.logger_(`excluding ${s.id}: ${o.join(" && ")}`))}})}updateAdCues_(e){let t=0;const i=this.seekable();i.length&&(t=i.start(0)),function(e,t,i=0){if(!e.segments)return;let s,r=i;for(let i=0;i<e.segments.length;i++){const n=e.segments[i];if(s||(s=Ru(t,r+n.duration/2)),s){if("cueIn"in n){s.endTime=r,s.adEndTime=r,r+=n.duration,s=null;continue}if(r<s.endTime){r+=n.duration;continue}s.endTime+=n.duration}else if("cueOut"in n&&(s=new p.VTTCue(r,r+n.duration,n.cueOut),s.adStartTime=r,s.adEndTime=r+parseFloat(n.cueOut),t.addCue(s)),"cueOutCont"in n){const[e,i]=n.cueOutCont.split("/").map(parseFloat);s=new p.VTTCue(r,r+n.duration,""),s.adStartTime=r-e,s.adEndTime=s.adStartTime+i,t.addCue(s)}r+=n.duration}}(e,this.cueTagsTrack_,t)}goalBufferLength(){const e=this.tech_.currentTime(),t=od.GOAL_BUFFER_LENGTH,i=od.GOAL_BUFFER_LENGTH_RATE,s=Math.max(t,od.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,s)}bufferLowWaterLine(){const e=this.tech_.currentTime(),t=od.BUFFER_LOW_WATER_LINE,i=od.BUFFER_LOW_WATER_LINE_RATE,s=Math.max(t,od.MAX_BUFFER_LOW_WATER_LINE),r=Math.max(t,od.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?r:s)}bufferHighWaterLine(){return od.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){Zd(this.inbandTextTracks_,"com.apple.streaming",this.tech_),(({inbandTextTracks:e,dateRanges:t})=>{const i=e.metadataTrack_;if(!i)return;const s=p.WebKitDataCue||p.VTTCue;t.forEach(e=>{for(const t of Object.keys(e)){if(Jd.has(t))continue;const r=new s(e.startTime,e.endTime,"");r.id=e.id,r.type="com.apple.quicktime.HLS",r.value={key:Qd[t],data:e[t]},"scte35Out"!==t&&"scte35In"!==t||(r.value.data=new Uint8Array(r.value.data.match(/[\da-f]{2}/gi)).buffer),i.addCue(r)}e.processDateRange()})})({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){const s=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();Zd(this.inbandTextTracks_,e,this.tech_),Yd({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:s,videoDuration:i})}pathwayAttribute_(e){return e.attributes["PATHWAY-ID"]||e.attributes.serviceLocation}initContentSteeringController_(){const e=this.main();if(e.contentSteering){for(const t of e.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(t));this.contentSteeringController_.assignTagProperties(e.uri,e.contentSteering),this.contentSteeringController_.queryBeforeStart?this.contentSteeringController_.requestSteeringManifest(!0):this.tech_.one("canplay",()=>{this.contentSteeringController_.requestSteeringManifest()})}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on("content-steering",this.excludeThenChangePathway_.bind(this));["contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach(e=>{this.contentSteeringController_.on(e,e=>{this.trigger(G({},e))})}),"dash"===this.sourceType_&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{const e=this.main();(this.contentSteeringController_.didDASHTagChange(e.uri,e.contentSteering)||(()=>{const t=this.contentSteeringController_.getAvailablePathways(),i=[];for(const s of e.playlists){const e=s.attributes.serviceLocation;if(e&&(i.push(e),!t.has(e)))return!0}return!(i.length||!t.size)})())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){const e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();const t=this.main().playlists,i=new Set;let s=!1;Object.keys(t).forEach(r=>{const n=t[r],a=this.pathwayAttribute_(n),o=a&&e!==a;n.excludeUntil===1/0&&"content-steering"===n.lastExcludeReason_&&!o&&(delete n.excludeUntil,delete n.lastExcludeReason_,s=!0);const l=!n.excludeUntil&&n.excludeUntil!==1/0;!i.has(n.id)&&o&&l&&(i.add(n.id),n.excludeUntil=1/0,n.lastExcludeReason_="content-steering",this.logger_(`excluding ${n.id} for ${n.lastExcludeReason_}`))}),"DASH"===this.contentSteeringController_.manifestType_&&Object.keys(this.mediaTypes_).forEach(t=>{const i=this.mediaTypes_[t];if(i.activePlaylistLoader){const t=i.activePlaylistLoader.media_;t&&t.attributes.serviceLocation!==e&&(s=!0)}}),s&&this.changeSegmentPathway_()}handlePathwayClones_(){const e=this.main().playlists,t=this.contentSteeringController_.currentPathwayClones,i=this.contentSteeringController_.nextPathwayClones;if(t&&t.size||i&&i.size){for(const[e,s]of t.entries()){i.get(e)||(this.mainPlaylistLoader_.updateOrDeleteClone(s),this.contentSteeringController_.excludePathway(e))}for(const[s,r]of i.entries()){const i=t.get(s);if(!i){e.filter(e=>e.attributes["PATHWAY-ID"]===r["BASE-ID"]).forEach(e=>{this.mainPlaylistLoader_.addClonePathway(r,e)}),this.contentSteeringController_.addAvailablePathway(s);continue}this.equalPathwayClones_(i,r)||(this.mainPlaylistLoader_.updateOrDeleteClone(r,!0),this.contentSteeringController_.addAvailablePathway(s))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...i])))}}equalPathwayClones_(e,t){if(e["BASE-ID"]!==t["BASE-ID"]||e.ID!==t.ID||e["URI-REPLACEMENT"].HOST!==t["URI-REPLACEMENT"].HOST)return!1;const i=e["URI-REPLACEMENT"].PARAMS,s=t["URI-REPLACEMENT"].PARAMS;for(const e in i)if(i[e]!==s[e])return!1;for(const e in s)if(i[e]!==s[e])return!1;return!0}changeSegmentPathway_(){const e=this.selectPlaylist();this.pauseLoading(),"DASH"===this.contentSteeringController_.manifestType_&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0;const t="non-usable";this.mainPlaylistLoader_.main.playlists.forEach(i=>{const s=this.mainPlaylistLoader_.getKeyIdSet(i);s&&s.size&&s.forEach(s=>{const r="usable",n=this.keyStatusMap_.has(s)&&this.keyStatusMap_.get(s)===r,a=i.lastExcludeReason_===t&&i.excludeUntil===1/0;n?n&&a&&(delete i.excludeUntil,delete i.lastExcludeReason_,this.logger_(`enabling playlist ${i.id} because key ID ${s} is ${r}`)):(i.excludeUntil!==1/0&&i.lastExcludeReason_!==t&&(i.excludeUntil=1/0,i.lastExcludeReason_=t,this.logger_(`excluding playlist ${i.id} because the key ID ${s} doesn't exist in the keyStatusMap or is not ${r}`)),e++)})}),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(e=>{const i=e&&e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.height<720,s=e.excludeUntil===1/0&&e.lastExcludeReason_===t;i&&s&&(delete e.excludeUntil,Fo.log.warn(`enabling non-HD playlist ${e.id} because all playlists were excluded due to ${t} key IDs`))})}addKeyStatus_(e,t){const i=("string"==typeof e?e:(e=>{const t=new Uint8Array(e);return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")})(e)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${t}' with key ID ${i} added to the keyStatusMap`),this.keyStatusMap_.set(i,t)}updatePlaylistByKeyStatus(e,t){this.addKeyStatus_(e,t),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}}class ac{constructor(e,t,i){const{playlistController_:s}=e,r=s.fastQualityChange_.bind(s);if(t.attributes){const e=t.attributes.RESOLUTION;this.width=e&&e.width,this.height=e&&e.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}var n,a,o;this.codecs=jd(s.main(),t),this.playlist=t,this.id=i,this.enabled=(n=e.playlists,a=t.id,o=r,e=>{const t=n.main.playlists[a],i=ml(t),s=gl(t);if(void 0===e)return s;e?delete t.disabled:t.disabled=!0;const r={renditionInfo:{id:a,bandwidth:t.attributes.BANDWIDTH,resolution:t.attributes.RESOLUTION,codecs:t.attributes.CODECS},cause:"fast-quality"};return e===s||i||(e?(o(t),n.trigger({type:"renditionenabled",metadata:r})):n.trigger({type:"renditiondisabled",metadata:r})),e})}}const oc=["seeking","seeked","pause","playing","error"];class lc extends Fo.EventTarget{constructor(e){super(),this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.playedRanges_=[],this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=Wo("PlaybackWatcher"),this.logger_("initialize");const t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),s=()=>this.techWaiting_(),r=()=>this.resetTimeUpdate_(),n=this.playlistController_,a=["main","subtitle","audio"],o={};a.forEach(e=>{o[e]={reset:()=>this.resetSegmentDownloads_(e),updateend:()=>this.checkSegmentDownloads_(e)},n[`${e}SegmentLoader_`].on("appendsdone",o[e].updateend),n[`${e}SegmentLoader_`].on("playlistupdate",o[e].reset),this.tech_.on(["seeked","seeking"],o[e].reset)});const l=e=>{["main","audio"].forEach(t=>{n[`${t}SegmentLoader_`][e]("appended",this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),l("off"))},this.clearSeekingAppendCheck_=()=>l("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),l("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",s),this.tech_.on(oc,r),this.tech_.on("canplay",i),this.tech_.one("play",t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",s),this.tech_.off(oc,r),this.tech_.off("canplay",i),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),a.forEach(e=>{n[`${e}SegmentLoader_`].off("appendsdone",o[e].updateend),n[`${e}SegmentLoader_`].off("playlistupdate",o[e].reset),this.tech_.off(["seeked","seeking"],o[e].reset)}),this.checkCurrentTimeTimeout_&&p.clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&p.clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=p.setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(e){const t=this.playlistController_[`${e}SegmentLoader_`];this[`${e}StalledDownloads_`]>0&&this.logger_(`resetting possible stalled download count for ${e} loader`),this[`${e}StalledDownloads_`]=0,this[`${e}Buffered_`]=t.buffered_()}checkSegmentDownloads_(e){const t=this.playlistController_,i=t[`${e}SegmentLoader_`],s=i.buffered_(),r=function(e,t){if(e===t)return!1;if(!e&&t||!t&&e)return!0;if(e.length!==t.length)return!0;for(let i=0;i<e.length;i++)if(e.start(i)!==t.start(i)||e.end(i)!==t.end(i))return!0;return!1}(this[`${e}Buffered_`],s);if(this[`${e}Buffered_`]=s,r){const i={bufferedRanges:s};return t.trigger({type:"bufferedrangeschanged",metadata:i}),void this.resetSegmentDownloads_(e)}this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:i.playlist_&&i.playlist_.id,buffered:tl(s)}),this[`${e}StalledDownloads_`]<10||(this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:"usage",name:`vhs-${e}-download-exclusion`}),"subtitle"!==e&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0}))}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;const e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+Yo>=t.end(t.length-1)))return this.techWaiting_();if(this.consecutiveUpdates>=5&&e===this.lastRecordedTime)this.consecutiveUpdates++,this.waiting_();else if(e===this.lastRecordedTime)this.consecutiveUpdates++;else{this.playedRanges_.push(Xo([this.lastRecordedTime,e]));const t={playedRanges:this.playedRanges_};this.playlistController_.trigger({type:"playedrangeschanged",metadata:t}),this.consecutiveUpdates=0,this.lastRecordedTime=e}}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){if(!this.tech_.seeking())return!1;const e=this.seekable(),t=this.tech_.currentTime();let i;if(this.afterSeekableWindow_(e,t,this.media(),this.allowSeeksWithinUnsafeLiveWindow)){i=e.end(e.length-1)}if(this.beforeSeekableWindow_(e,t)){const t=e.start(0);i=t+(t===e.end(0)?0:Yo)}if(void 0!==i)return this.logger_(`Trying to seek outside of seekable at time ${t} with seekable range ${el(e)}. Seeking to ${i}.`),this.tech_.setCurrentTime(i),!0;const s=this.playlistController_.sourceUpdater_,r=this.tech_.buffered(),n=s.audioBuffer?s.audioBuffered():null,a=s.videoBuffer?s.videoBuffered():null,o=this.media(),l=o.partTargetDuration?o.partTargetDuration:2*(o.targetDuration-Ko),d=[n,a];for(let e=0;e<d.length;e++){if(!d[e])continue;if(sl(d[e],t)<l)return!1}const u=Zo(r,t);return 0!==u.length&&(i=u.start(0)+Yo,this.logger_(`Buffered region starts (${u.start(0)}) just beyond seek point (${t}). Seeking to ${i}.`),this.tech_.setCurrentTime(i),!0)}waiting_(){if(this.techWaiting_())return;const e=this.tech_.currentTime(),t=this.tech_.buffered(),i=Jo(t,e);return i.length&&e+3<=i.end(0)?(this.resetTimeUpdate_(),this.tech_.setCurrentTime(e),this.logger_(`Stopped at ${e} while inside a buffered region [${i.start(0)} -> ${i.end(0)}]. Attempting to resume playback by seeking to the current time.`),void this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"})):void 0}techWaiting_(){const e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){const i=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${i}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(i),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}const i=this.tech_.vhs.playlistController_.sourceUpdater_,s=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:i.audioBuffered(),videoBuffered:i.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;const r=Zo(s,t);return r.length>0&&(this.logger_(`Stopped at ${t} and seeking to ${r.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0)}afterSeekableWindow_(e,t,i,s=!1){if(!e.length)return!1;let r=e.end(e.length-1)+Yo;const n=!i.endList,a="number"==typeof i.partTargetDuration;return n&&(a||s)&&(r=e.end(e.length-1)+3*i.targetDuration),t>r}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t<e.start(0)-this.liveRangeSafeTimeDelta)}videoUnderflow_({videoBuffered:e,audioBuffered:t,currentTime:i}){if(!e)return;let s;if(e.length&&t.length){const r=Jo(e,i-3),n=Jo(e,i),a=Jo(t,i);a.length&&!n.length&&r.length&&(s={start:r.end(0),end:a.end(0)})}else{Zo(e,i).length||(s=this.gapFromVideoUnderflow_(e,i))}return!!s&&(this.logger_(`Encountered a gap in video from ${s.start} to ${s.end}. Seeking to current time ${i}`),!0)}skipTheGap_(e){const t=this.tech_.buffered(),i=this.tech_.currentTime(),s=Zo(t,i);if(this.resetTimeUpdate_(),0===s.length||i!==e)return;this.logger_("skipTheGap_:","currentTime:",i,"scheduled currentTime:",e,"nextRange start:",s.start(0)),this.tech_.setCurrentTime(s.start(0)+Ko);const r={gapInfo:{from:i,to:s.start(0)}};this.playlistController_.trigger({type:"gapjumped",metadata:r}),this.tech_.trigger({type:"usage",name:"vhs-gap-skip"})}gapFromVideoUnderflow_(e,t){const i=function(e){if(e.length<2)return Xo();const t=[];for(let i=1;i<e.length;i++){const s=e.end(i-1),r=e.start(i);t.push([s,r])}return Xo(t)}(e);for(let e=0;e<i.length;e++){const s=i.start(e),r=i.end(e);if(t-s<4&&t-s>2)return{start:s,end:r}}return null}}const dc={errorInterval:30,getSource(e){return e(this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource())}},uc=function(e,t){let i=0,s=0;const r=Go(dc,t);e.ready(()=>{e.trigger({type:"usage",name:"vhs-error-reload-initialized"})});const n=function(){s&&e.currentTime(s)},a=function(t){null!=t&&(s=e.duration()!==1/0&&e.currentTime()||0,e.one("loadedmetadata",n),e.src(t),e.trigger({type:"usage",name:"vhs-error-reload"}),e.play())},o=function(){if(Date.now()-i<1e3*r.errorInterval)e.trigger({type:"usage",name:"vhs-error-reload-canceled"});else{if(r.getSource&&"function"==typeof r.getSource)return i=Date.now(),r.getSource.call(e,a);Fo.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!")}},l=function(){e.off("loadedmetadata",n),e.off("error",o),e.off("dispose",l)};e.on("error",o),e.on("dispose",l),e.reloadSourceOnError=function(t){l(),uc(e,t)}},cc=function(e){uc(this,e)};var hc="3.16.2";const pc={PlaylistLoader:Bl,Playlist:Tl,utils:Kl,STANDARD_PLAYLIST_SELECTOR:Xd,INITIAL_PLAYLIST_SELECTOR:function(){const e=this.playlists.main.playlists.filter(Tl.isEnabled);zd(e,(e,t)=>Wd(e,t));return e.filter(e=>!!jd(this.playlists.main,e).video)[0]||null},lastBandwidthSelector:Xd,movingAverageBandwidthSelector:function(e){let t=-1,i=-1;if(e<0||e>1)throw new Error("Moving average bandwidth decay must be between 0 and 1.");return function(){let s=this.useDevicePixelRatio&&p.devicePixelRatio||1;return isNaN(this.customPixelRatio)||(s=this.customPixelRatio),t<0&&(t=this.systemBandwidth,i=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==i&&(t=e*this.systemBandwidth+(1-e)*t,i=this.systemBandwidth),Gd(this.playlists.main,t,parseInt(Hd(this.tech_.el(),"width"),10)*s,parseInt(Hd(this.tech_.el(),"height"),10)*s,this.limitRenditionByPlayerDimensions,this.playlistController_)}},comparePlaylistBandwidth:Wd,comparePlaylistResolution:function(e,t){let i,s;return e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||p.Number.MAX_VALUE,t.attributes.RESOLUTION&&t.attributes.RESOLUTION.width&&(s=t.attributes.RESOLUTION.width),s=s||p.Number.MAX_VALUE,i===s&&e.attributes.BANDWIDTH&&t.attributes.BANDWIDTH?e.attributes.BANDWIDTH-t.attributes.BANDWIDTH:i-s},xhr:ql()};Object.keys(od).forEach(e=>{Object.defineProperty(pc,e,{get:()=>(Fo.log.warn(`using Vhs.${e} is UNSAFE be sure you know what you are doing`),od[e]),set(t){Fo.log.warn(`using Vhs.${e} is UNSAFE be sure you know what you are doing`),"number"!=typeof t||t<0?Fo.log.warn(`value of Vhs.${e} must be greater than or equal to 0`):od[e]=t}})});const mc="videojs-vhs",gc=function(e,t){const i=t.media();let s=-1;for(let t=0;t<e.length;t++)if(e[t].id===i.id){s=t;break}e.selectedIndex_=s,e.trigger({selectedIndex:s,type:"change"})};pc.canPlaySource=function(){return Fo.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};const fc=({player:e,sourceKeySystems:t,audioMedia:i,mainPlaylists:s})=>{if(!e.eme.initializeMediaKeys)return Promise.resolve();const r=((e,t)=>e.reduce((e,i)=>{if(!i.contentProtection)return e;const s=t.reduce((e,t)=>{const s=i.contentProtection[t];return s&&s.pssh&&(e[t]={pssh:s.pssh}),e},{});return Object.keys(s).length&&e.push(s),e},[]))(i?s.concat([i]):s,Object.keys(t)),n=[],a=[];return r.forEach(t=>{a.push(new Promise((t,i)=>{e.tech_.one("keysessioncreated",t)})),n.push(new Promise((i,s)=>{e.eme.initializeMediaKeys({keySystems:t},e=>{e?s(e):i()})}))}),Promise.race([Promise.all(n),Promise.race(a)])},yc=({player:e,sourceKeySystems:t,media:i,audioMedia:s})=>{const r=((e,t,i)=>{if(!e)return e;let s={};t&&t.attributes&&t.attributes.CODECS&&(s=Fd(pe(t.attributes.CODECS))),i&&i.attributes&&i.attributes.CODECS&&(s.audio=i.attributes.CODECS);const r=ge(s.video),n=ge(s.audio),a={};for(const i in e)a[i]={},n&&(a[i].audioContentType=n),r&&(a[i].videoContentType=r),t.contentProtection&&t.contentProtection[i]&&t.contentProtection[i].pssh&&(a[i].pssh=t.contentProtection[i].pssh),"string"==typeof e[i]&&(a[i].url=e[i]);return Go(e,a)})(t,i,s);return!!r&&(e.currentSource().keySystems=r,!(r&&!e.eme)||(Fo.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1))},_c=()=>{if(!p.localStorage)return null;const e=p.localStorage.getItem(mc);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}},bc=(e,t)=>{e._requestCallbackSet||(e._requestCallbackSet=new Set),e._requestCallbackSet.add(t)},vc=(e,t)=>{e._responseCallbackSet||(e._responseCallbackSet=new Set),e._responseCallbackSet.add(t)},Tc=(e,t)=>{e._requestCallbackSet&&(e._requestCallbackSet.delete(t),e._requestCallbackSet.size||delete e._requestCallbackSet)},Sc=(e,t)=>{e._responseCallbackSet&&(e._responseCallbackSet.delete(t),e._responseCallbackSet.size||delete e._responseCallbackSet)};pc.supportsNativeHls=function(){if(!_||!_.createElement)return!1;const e=_.createElement("video");if(!Fo.getTech("Html5").isSupported())return!1;return["application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"].some(function(t){return/maybe|probably/i.test(e.canPlayType(t))})}(),pc.supportsNativeDash=!!(_&&_.createElement&&Fo.getTech("Html5").isSupported())&&/maybe|probably/i.test(_.createElement("video").canPlayType("application/dash+xml")),pc.supportsTypeNatively=e=>"hls"===e?pc.supportsNativeHls:"dash"===e&&pc.supportsNativeDash,pc.isSupported=function(){return Fo.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")},pc.xhr.onRequest=function(e){bc(pc.xhr,e)},pc.xhr.onResponse=function(e){vc(pc.xhr,e)},pc.xhr.offRequest=function(e){Tc(pc.xhr,e)},pc.xhr.offResponse=function(e){Sc(pc.xhr,e)};const Ec=Fo.getComponent("Component");class wc extends Ec{constructor(e,t,i){if(super(t,i.vhs),"number"==typeof i.initialBandwidth&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=Wo("VhsHandler"),t.options_&&t.options_.playerId){const e=Fo.getPlayer(t.options_.playerId);this.player_=e}if(this.tech_=t,this.source_=e,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&t.overrideNativeAudioTracks&&t.overrideNativeVideoTracks)t.overrideNativeAudioTracks(!0),t.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(t.featuresNativeVideoTracks||t.featuresNativeAudioTracks))throw new Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on(_,["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],e=>{const t=_.fullscreenElement||_.webkitFullscreenElement||_.mozFullScreenElement||_.msFullscreenElement;t&&t.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_(e={}){if(this.options_=Go(this.options_,e),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=!1!==this.options_.limitRenditionByPlayerDimensions,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.useBandwidthFromLocalStorage=void 0!==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,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,"number"!=typeof this.options_.playlistExclusionDuration&&(this.options_.playlistExclusionDuration=60),"number"!=typeof this.options_.bandwidth&&this.options_.useBandwidthFromLocalStorage){const e=_c();e&&e.bandwidth&&(this.options_.bandwidth=e.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),e&&e.throughput&&(this.options_.throughput=e.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"}))}"number"!=typeof this.options_.bandwidth&&(this.options_.bandwidth=od.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===od.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","customPixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR","liveRangeSafeTimeDelta","llhls","useForcedSubtitles","useNetworkInformationApi","useDtsForTimestampOffset","exactManifestTimings","leastPixelDiffSelector"].forEach(e=>{void 0!==this.source_[e]&&(this.options_[e]=this.source_[e])}),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio;const t=this.options_.customPixelRatio;"number"==typeof t&&t>=0&&(this.customPixelRatio=t)}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;var i;this.setOptions_(),this.options_.src=0===(i=this.source_.src).toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")?JSON.parse(i.substring(i.indexOf(",")+1)):i,this.options_.tech=this.tech_,this.options_.externVhs=pc,this.options_.sourceType=Te(t),this.options_.seekTo=e=>{this.tech_.setCurrentTime(e)},this.options_.player_=this.player_,this.playlistController_=new nc(this.options_);const s=Go({liveRangeSafeTimeDelta:Yo},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new lc(s),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{const e=Fo.players[this.tech_.options_.playerId];let t=this.playlistController_.error;"object"!=typeof t||t.code?"string"==typeof t&&(t={message:t,code:3}):t.code=3,e.error(t)});const r=this.options_.bufferBasedABR?pc.movingAverageBandwidthSelector(.55):pc.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):r.bind(this),this.playlistController_.selectInitialPlaylist=pc.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(e){this.playlistController_.selectPlaylist=e.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(e){this.playlistController_.mainSegmentLoader_.throughput.rate=e,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let e=this.playlistController_.mainSegmentLoader_.bandwidth;const t=p.navigator.connection||p.navigator.mozConnection||p.navigator.webkitConnection,i=1e7;if(this.options_.useNetworkInformationApi&&t){const s=1e3*t.downlink*1e3;e=s>=i&&e>=i?Math.max(e,s):s}return e},set(e){this.playlistController_.mainSegmentLoader_.bandwidth=e,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){const e=1/(this.bandwidth||1);let t;t=this.throughput>0?1/this.throughput:0;return Math.floor(1/(e+t))},set(){Fo.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playlistController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>tl(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:()=>tl(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one("canplay",this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on("bandwidthupdate",()=>{this.options_.useBandwidthFromLocalStorage&&(e=>{if(!p.localStorage)return!1;let t=_c();t=t?Go(t,e):e;try{p.localStorage.setItem(mc,JSON.stringify(t))}catch(e){return!1}})({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{var e;(e=this).representations=()=>{const t=e.playlistController_.main(),i=vl(t)?e.playlistController_.getAudioTrackPlaylists_():t.playlists;return i?i.filter(e=>!ml(e)).map((t,i)=>new ac(e,t,t.id)):[]}}),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_=p.URL.createObjectURL(this.playlistController_.mediaSource),(Fo.browser.IS_ANY_SAFARI||Fo.browser.IS_IOS)&&this.options_.overrideNative&&"hls"===this.options_.sourceType&&"function"==typeof this.tech_.addSourceElement?(this.tech_.addSourceElement(this.mediaSourceUrl_),this.tech_.addSourceElement(this.source_.src)):this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),fc({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:e&&e.media(),mainPlaylists:this.playlists.main.playlists}).then(()=>{this.logger_("created EME key session"),this.playlistController_.sourceUpdater_.initializedEme()}).catch(e=>{this.logger_("error while creating EME key session",e),this.player_.error({message:"Failed to initialize media keys for EME",code:3})})}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){const e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=yc({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});this.player_.tech_.on("keystatuschange",e=>{this.playlistController_.updatePlaylistByKeyStatus(e.keyId,e.status)}),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),t?this.createKeySessions_():this.playlistController_.sourceUpdater_.initializedEme()}setupQualityLevels_(){const e=Fo.players[this.tech_.options_.playerId];e&&e.qualityLevels&&!this.qualityLevels_&&(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{!function(e,t){t.representations().forEach(t=>{e.addQualityLevel(t)}),gc(e,t.playlists)}(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{gc(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":hc,"mux.js":"7.1.0","mpd-parser":"1.3.1","m3u8-parser":"7.2.0","aes-decrypter":"4.0.2"}}version(){return this.constructor.version()}canChangeType(){return Du.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(e){this.playlistController_.setCurrentTime(e)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&p.URL.revokeObjectURL&&(p.URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return Yl({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,s=2){return Ql({programTime:e,playlist:this.playlistController_.media(),retryCount:s,pauseAfterSeek:i,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{bc(this.xhr,e)},this.xhr.onResponse=e=>{vc(this.xhr,e)},this.xhr.offRequest=e=>{Tc(this.xhr,e)},this.xhr.offResponse=e=>{Sc(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}attachStreamingEventListeners_(){["seekablerangeschanged","bufferedrangeschanged","contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach(e=>{this.playlistController_.on(e,e=>{this.player_.trigger(G({},e))})}),["gapjumped","playedrangeschanged"].forEach(e=>{this.playbackWatcher_.on(e,e=>{this.player_.trigger(G({},e))})})}}const kc={name:"videojs-http-streaming",VERSION:hc,canHandleSource(e,t={}){const i=Go(Fo.options,t);return!(!i.vhs.experimentalUseMMS&&!fe("avc1.4d400d,mp4a.40.2",!1))&&kc.canPlayType(e.type,i)},handleSource(e,t,i={}){const s=Go(Fo.options,i);return t.vhs=new wc(e,t,s),t.vhs.xhr=ql(),t.vhs.setupXhrHooks_(),t.vhs.src(e.src,e.type),t.vhs},canPlayType(e,t){const i=Te(e);if(!i)return"";const s=kc.getOverrideNative(t);return!pc.supportsTypeNatively(i)||s?"maybe":""},getOverrideNative(e={}){const{vhs:t={}}=e,i=!(Fo.browser.IS_ANY_SAFARI||Fo.browser.IS_IOS),{overrideNative:s=i}=t;return s}};fe("avc1.4d400d,mp4a.40.2",!0)&&Fo.getTech("Html5").registerSourceHandler(kc,0),Fo.VhsHandler=wc,Fo.VhsSourceHandler=kc,Fo.Vhs=pc,Fo.use||Fo.registerComponent("Vhs",pc),Fo.options.vhs=Fo.options.vhs||{},Fo.getPlugin&&Fo.getPlugin("reloadSourceOnError")||Fo.registerPlugin("reloadSourceOnError",cc)
29
- /*! @name videojs-contrib-eme @version 5.5.2 @license Apache-2.0 */;const Cc=(e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;const i=new DataView(e),s=new DataView(t);for(let e=0;e<i.byteLength;e++)if(i.getUint8(e)!==s.getUint8(e))return!1;return!0},Ic=e=>e instanceof Uint8Array||e instanceof Uint16Array?e.buffer:e,xc=(...e)=>{const t=Fo.obj||Fo;return(t.merge||t.mergeOptions).apply(t,e)},Ac=(...e)=>{const t=xc(...e);return Object.keys(t).forEach(e=>{null===t[e]&&delete t[e]}),t},Dc=e=>{const t=[];return Object.keys(e).forEach(i=>{const s=Vc(i,e[i])[0];t.push(s)}),t};let Pc=Fo.xhr.httpHandler;Pc||(Pc=(e,t)=>(i,s,r)=>{if(i)e(i);else{if(s.statusCode>=400&&s.statusCode<=599){let i=r;return t&&(i=String.fromCharCode.apply(null,new Uint8Array(r))),void e({cause:i})}e(null,r)}});const Lc=(e,t,i,s,r)=>{const n=(e=>{const t=String.fromCharCode.apply(null,new Uint16Array(e)),i=(new p.DOMParser).parseFromString(t,"application/xml"),s=i.getElementsByTagName("HttpHeaders")[0];let r={};if(s){const e=s.getElementsByTagName("name"),t=s.getElementsByTagName("value");for(let i=0;i<e.length;i++)r[e[i].childNodes[0].nodeValue]=t[i].childNodes[0].nodeValue}const n=i.getElementsByTagName("Challenge")[0];let a;return n&&(a=p.atob(n.childNodes[0].nodeValue)),i.querySelector("parsererror")&&(r={"Content-Type":"text/xml; charset=utf-8",SOAPAction:'"http://schemas.microsoft.com/DRM/2007/03/protocols/AcquireLicense"'},a=e),{headers:r,message:a}})(i),a=n.message,o=Ac(n.headers,s.emeHeaders,t.licenseHeaders);Fo.xhr({uri:t.url,method:"post",headers:o,body:a,responseType:"arraybuffer",requestType:"license",metadata:{keySystem:e}},Pc(r,!0))},Oc={EMEFailedToRequestMediaKeySystemAccess:"eme-failed-request-media-key-system-access",EMEFailedToCreateMediaKeys:"eme-failed-create-media-keys",EMEFailedToAttachMediaKeysToVideoElement:"eme-failed-attach-media-keys-to-video",EMEFailedToCreateMediaKeySession:"eme-failed-create-media-key-session",EMEFailedToSetServerCertificate:"eme-failed-set-server-certificate",EMEFailedToGenerateLicenseRequest:"eme-failed-generate-license-request",EMEFailedToUpdateSessionWithReceivedLicenseKeys:"eme-failed-update-session",EMEFailedToCloseSession:"eme-failed-close-session",EMEFailedToRemoveKeysFromSession:"eme-failed-remove-keys",EMEFailedToLoadSessionBySessionId:"eme-failed-load-session"},Mc="com.apple.fps.1_0",Rc=({initData:e,id:t,cert:i})=>{"string"==typeof t&&(t=(e=>{const t=new ArrayBuffer(2*e.length),i=new Uint16Array(t);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t);return i})(t));let s=0;const r=new ArrayBuffer(e.byteLength+4+t.byteLength+4+i.byteLength),n=new DataView(r);new Uint8Array(r,s,e.byteLength).set(e),s+=e.byteLength,n.setUint32(s,t.byteLength,!0),s+=4;const a=new Uint16Array(r,s,t.length);a.set(t),s+=a.byteLength,n.setUint32(s,i.byteLength,!0),s+=4;return new Uint8Array(r,s,i.byteLength).set(i),new Uint8Array(r,0,r.byteLength)},Nc=(e,t)=>(i,s)=>{const r=Ac(i.emeHeaders,t.certificateHeaders);Fo.xhr({uri:t.certificateUri,responseType:"arraybuffer",requestType:"license",metadata:{keySystem:e},headers:r},Pc((e,t)=>{e?s(e):s(null,new Uint8Array(t))}))},Uc=(e,t)=>(e=>{const t=_.createElement("a");return t.href=e,t.hostname})(t),Bc=(e,t)=>(i,s,r,n)=>{const a=Ac({"Content-type":"application/octet-stream"},i.emeHeaders,t.licenseHeaders);Fo.xhr({uri:t.licenseUri||t.url,method:"POST",responseType:"arraybuffer",requestType:"license",metadata:{keySystem:e,contentId:s},body:r,headers:a},Pc(n,!0))},Fc=({video:e,initData:t,options:i,eventBus:s,emeError:r})=>{const n=i.keySystems[Mc],a=n.getCertificate||Nc(Mc,n),o=n.getContentId||Uc,l=n.getLicense||Bc(Mc,n);return new Promise((e,t)=>{a(i,(i,s)=>{if(i){return r(i,{errorType:Oc.EMEFailedToSetServerCertificate,keySystem:Mc}),void t(i)}e(s)})}).then(n=>{return(({video:e,contentId:t,initData:i,cert:s,options:r,getLicense:n,eventBus:a,emeError:o})=>new Promise((l,d)=>{if(!e.webkitKeys)try{e.webkitSetMediaKeys(new p.WebKitMediaKeys(Mc))}catch(e){return o(e,{errorType:Oc.EMEFailedToCreateMediaKeys,keySystem:Mc}),void d("Could not create MediaKeys")}let u;try{u=e.webkitKeys.createSession("video/mp4",Rc({id:t,initData:i,cert:s}))}catch(e){return o(e,{errorType:Oc.EMEFailedToCreateMediaKeySession,keySystem:Mc}),void d("Could not create key session")}jc(a,{type:"keysessioncreated",keySession:u}),u.contentId=t,u.addEventListener("webkitkeymessage",e=>{jc(a,{type:"keymessage",messageEvent:e}),n(r,t,e.message,(e,t)=>{if(a&&jc(a,{type:"licenserequestattempted"}),e)return o(e,{errortype:Oc.EMEFailedToGenerateLicenseRequest,keySystem:Mc}),void d(e);u.update(new Uint8Array(t)),jc(a,{type:"keysessionupdated",keySession:u})})}),u.addEventListener("webkitkeyadded",()=>{l()}),u.addEventListener("webkitkeyerror",()=>{const e=u.error;o(e,{errorType:Oc.EMEFailedToUpdateSessionWithReceivedLicenseKeys,keySystem:Mc}),d(`KeySession error: code ${e.code}, systemCode ${e.systemCode}`)})}))({video:e,cert:n,initData:t,getLicense:l,options:i,contentId:o(i,(a=t,String.fromCharCode.apply(null,new Uint16Array(a.buffer||a)))),eventBus:s,emeError:r});var a})},qc=e=>e.startsWith("com.apple.fps"),jc=(e,t)=>{e.isDisposed()||e.trigger(G({},t))},Vc=(e,t)=>{if(t.supportedConfigurations)return t.supportedConfigurations;const i=qc(e),s={},r=t.initDataTypes||(i?["sinf"]:null),n=t.audioContentType,a=t.audioRobustness,o=t.videoContentType||(i?"video/mp4":null),l=t.videoRobustness,d=t.persistentState;return(n||a)&&(s.audioCapabilities=[G({},n?{contentType:n}:{},a?{robustness:a}:{})]),(o||l)&&(s.videoCapabilities=[G({},o?{contentType:o}:{},l?{robustness:l}:{})]),d&&(s.persistentState=d),r&&(s.initDataTypes=r),[s]},$c=(e,t)=>{const{mediaKeys:i,initDataType:s,initData:r,options:n,getLicense:a,removeSession:o,eventBus:l,contentId:d,emeError:u,keySystem:c}=t;let h,p=0;e.on("pause",()=>{n.limitRenewalsMaxPauseDuration&&"number"==typeof n.limitRenewalsMaxPauseDuration&&(h=setInterval(()=>{p++,p>=n.limitRenewalsMaxPauseDuration&&clearInterval(h)},1e3),e.on("play",()=>{clearInterval(h),p=0}))});try{const t=i.createSession(),h=()=>{Fo.log.debug("Session expired, closing the session."),t.close().then(()=>{l.isDisposed()||(jc(l,{type:"keysessionclosed",keySession:t}),o(r))}).catch(e=>{u(e,{errorType:Oc.EMEFailedToCloseSession,keySystem:c})})};return jc(l,{type:"keysessioncreated",keySession:t}),e.on("dispose",()=>{h()}),new Promise((i,o)=>{t.addEventListener("message",s=>{if(jc(l,{type:"keymessage",messageEvent:s}),"license-request"===s.messageType||"license-renewal"===s.messageType){if("license-renewal"===s.messageType){const t=n.limitRenewalsBeforePlay,i=n.limitRenewalsMaxPauseDuration,s="number"==typeof i,r=!e.hasStarted()&&t,a=e.paused()&&s&&p>=i,o=e.ended();if(r||a||o)return void h()}a(n,s.message,d).then(e=>{i(t.update(e).then(()=>{jc(l,{type:"keysessionupdated",keySession:t})}).catch(e=>{u(e,{errorType:Oc.EMEFailedToUpdateSessionWithReceivedLicenseKeys,keySystem:c})}))}).catch(e=>{o(e)})}},!1);const m="keystatuseschange";t.addEventListener(m,e=>{let i=!1;l.isDisposed()||(jc(l,{type:m,keyStatuses:t.keyStatuses}),t.keyStatuses.forEach((s,r)=>{switch(jc(l,{keyId:r,status:s,target:t,type:"keystatuschange"}),s){case"expired":i=!0;break;case"internal-error":const t='Key status reported as "internal-error." Leaving the session open since we don\'t have enough details to know if this error is fatal.';Fo.log.warn(t,e)}}),i&&h())},!1),t.generateRequest(s,r).catch(e=>{u(e,{errorType:Oc.EMEFailedToGenerateLicenseRequest,keySystem:c}),o("Unable to create or initialize key session")})})}catch(e){u(e,{errorType:Oc.EMEFailedToCreateMediaKeySession,keySystem:c})}},Hc=(e,t)=>{if("string"==typeof t&&(t={url:t}),!t.url&&t.licenseUri&&(t.url=t.licenseUri),!t.url&&!t.getLicense)throw new Error(`Missing url/licenseUri or getLicense in ${e} keySystem configuration.`);const i=qc(e);if(i&&t.certificateUri&&!t.getCertificate&&(t.getCertificate=Nc(e,t)),i&&!t.getCertificate)throw new Error(`Missing getCertificate or certificateUri in ${e} keySystem configuration.`);return i&&!t.getContentId&&(t.getContentId=Uc),t.url&&!t.getLicense&&(t.getLicense="com.microsoft.playready"===e?((e,t)=>(i,s,r)=>{Lc(e,t,s,i,r)})(e,t):i?Bc(e,t):((e,t)=>(i,s,r)=>{const n=Ac({"Content-type":"application/octet-stream"},i.emeHeaders,t.licenseHeaders);Fo.xhr({uri:t.url,method:"POST",responseType:"arraybuffer",requestType:"license",metadata:{keySystem:e},body:s,headers:n},Pc(r,!0))})(e,t)),t},zc=({player:e,video:t,initDataType:i,initData:s,keySystemAccess:r,options:n,removeSession:a,eventBus:o,emeError:l})=>{let d=Promise.resolve();const u=r.keySystem;let c;try{c=Hc(u,n.keySystems[u])}catch(e){return Promise.reject(e)}const h=c.getContentId?c.getContentId(n,(p=s,String.fromCharCode.apply(null,new Uint8Array(p.buffer||p)))):null;var p;if(void 0===t.mediaKeysObject){let i;t.mediaKeysObject=null,t.pendingSessionData=[],d=new Promise((e,s)=>{t.keySystem=u,c.getCertificate?c.getCertificate(n,(t,r)=>{t?s(t):(i=r,e())}):e(r)}).then(()=>r.createMediaKeys()).then(s=>(jc(o,{type:"keysystemaccesscomplete",mediaKeys:s}),(({player:e,video:t,certificate:i,createdMediaKeys:s,emeError:r})=>{t.mediaKeysObject=s;const n=[];i&&n.push(s.setServerCertificate(i).catch(e=>{const i={errorType:Oc.EMEFailedToSetServerCertificate,keySystem:t.keySystem};r(e,i)}));for(let i=0;i<t.pendingSessionData.length;i++){const s=t.pendingSessionData[i];n.push($c(e,{mediaKeys:t.mediaKeysObject,initDataType:s.initDataType,initData:s.initData,options:s.options,getLicense:s.getLicense,removeSession:s.removeSession,eventBus:s.eventBus,contentId:s.contentId,emeError:s.emeError,keySystem:t.keySystem}))}return t.pendingSessionData=[],n.push(t.setMediaKeys(s).catch(e=>{const i={errorType:Oc.EMEFailedToAttachMediaKeysToVideoElement,keySystem:t.keySystem};r(e,i)})),Promise.all(n)})({player:e,video:t,certificate:i,createdMediaKeys:s,emeError:l}))).catch(e=>(l(e,{errorType:Oc.EMEFailedToCreateMediaKeys,keySystem:u}),e?Promise.reject(e):Promise.reject("Failed to create and initialize a MediaKeys object")))}return d.then(()=>{const r=t.keySystem?((e,t,i)=>(s,r,n)=>new Promise((a,o)=>{const l=function(e,t){i&&jc(i,{type:"licenserequestattempted"}),e?o(e):a(t)};qc(e)?t(s,n,new Uint8Array(r),l):t(s,r,l)}))(u,c.getLicense,o):null;return(({player:e,video:t,initDataType:i,initData:s,options:r,getLicense:n,contentId:a,removeSession:o,eventBus:l,emeError:d})=>{const u={initDataType:i,initData:s,options:r,getLicense:n,removeSession:o,eventBus:l,contentId:a,emeError:d,keySystem:t.keySystem};return t.mediaKeysObject?(u.mediaKeys=t.mediaKeysObject,$c(e,u)):(t.pendingSessionData.push(u),Promise.resolve())})({player:e,video:t,initDataType:i,initData:s,options:n,getLicense:r,contentId:h,removeSession:a,eventBus:o,emeError:l})})},Wc="com.microsoft.playready",Gc=(e,t,i,s,r)=>{const n=e.msKeys.createSession("video/mp4",t);if(!n){const e=new Error("Could not create key session.");throw r(e,{errorType:Oc.EMEFailedToCreateMediaKeySession,keySystem:Wc}),e}jc(s,{type:"keysessioncreated",keySession:n}),n.addEventListener("mskeymessage",e=>{jc(s,{type:"keymessage",messageEvent:e}),((e,t,i,s,r)=>{let n=e.keySystems[Wc];if("function"==typeof n.getKey)return void n.getKey(e,i.destinationURL,i.message.buffer,(i,n)=>{if(i){const n={errorType:Oc.EMEFailedToRequestMediaKeySystemAccess,config:Dc(e.keySystems)};return r(i,n),void jc(s,{message:"Unable to get key: "+i,target:t,type:"mskeyerror"})}t.update(n),jc(s,{type:"keysessionupdated",keySession:t})});"string"==typeof n?n={url:n}:"boolean"==typeof n&&(n={}),n.url||(n.url=i.destinationURL);const a=(e,i)=>{if(s&&jc(s,{type:"licenserequestattempted"}),e)return r(e,{errorType:Oc.EMEFailedToGenerateLicenseRequest,keySystem:Wc}),void jc(s,{message:"Unable to request key from url: "+n.url,target:t,type:"mskeyerror"});t.update(new Uint8Array(i))};n.getLicense?n.getLicense(e,i.message.buffer,a):Lc(Wc,n,i.message.buffer,e,a)})(i,n,e,s,r)}),n.addEventListener("mskeyerror",e=>{const t={errorType:Oc.EMEFailedToCreateMediaKeySession,keySystem:Wc};r(n.error,t),jc(s,{message:`Unexpected key error from key session with code: ${n.error.code} and systemCode: ${n.error.systemCode}`,target:n,type:"mskeyerror"})}),n.addEventListener("mskeyadded",()=>{jc(s,{target:n,type:"mskeyadded"})})};const Xc=[{initDataTypes:["cenc"],audioCapabilities:[{contentType:'audio/mp4;codecs="mp4a.40.2"'}],videoCapabilities:[{contentType:'video/mp4;codecs="avc1.42E01E"'}]}],Kc=[{keySystem:"com.apple.fps",supportedConfig:[{initDataTypes:["sinf"],videoCapabilities:[{contentType:"video/mp4"}]}]},{keySystem:"com.microsoft.playready.recommendation",supportedConfig:Xc},{keySystem:"com.widevine.alpha",supportedConfig:Xc},{keySystem:"org.w3.clearkey",supportedConfig:Xc}],Yc=()=>{const e=p.Promise,t={fairplay:Boolean(p.WebKitMediaKeys),playready:!1,widevine:!1,clearkey:!1};return p.MediaKeys&&p.navigator.requestMediaKeySystemAccess?e.all(Kc.map(({keySystem:e,supportedConfig:t})=>p.navigator.requestMediaKeySystemAccess(e,t).catch(()=>{}))).then(([e,i,s,r])=>(t.fairplay=Boolean(e),t.playready=Boolean(i),t.widevine=Boolean(s),t.clearkey=Boolean(r),t)):e.resolve(t)};const Qc=(e,t)=>{for(let i=0;i<e.length;i++)if(e[i].initData===t)return void e.splice(i,1)};function Jc(e,t,i,s,r,n){if(!i||!i.keySystems)return Promise.resolve();if(i.keySystems[Mc]&&p.WebKitMediaKeys&&e.eme.legacyFairplayIsUsed)return Fo.log.debug("eme",`Ignoring 'encrypted' event, using legacy fairplay keySystem ${Mc}`),Promise.resolve();let a=t.initData;return(e=>{let t;return Object.keys(e).forEach(i=>{const s=Vc(i,e[i]);t=t?t.catch(e=>p.navigator.requestMediaKeySystemAccess(i,s)):p.navigator.requestMediaKeySystemAccess(i,s)}),t})(i.keySystems).then(o=>{const l=o.keySystem;return i.keySystems[l]&&i.keySystems[l].pssh&&(a=i.keySystems[l].pssh),((e,t)=>{for(let i=0;i<e.length;i++){if(!e[i].initData)continue;const s=Ic(e[i].initData),r=Ic(t);if(Cc(s,r))return!0}return!1})(s,a)||!a?Promise.resolve():(s.push({initData:a}),zc({player:e,video:t.target,initDataType:t.initDataType,initData:a,keySystemAccess:o,options:i,removeSession:Qc.bind(null,s),eventBus:r,emeError:n}))}).catch(e=>{const t={errorType:Oc.EMEFailedToRequestMediaKeySystemAccess,config:Dc(i.keySystems)};n(e,t)})}const Zc=(e,t,i,s,r)=>{if(!t.keySystems||!t.keySystems[Wc])return;if(i.reduce((e,t)=>e||t.playready,!1))return;let n=e.initData;t.keySystems[Wc]&&t.keySystems[Wc].pssh&&(n=t.keySystems[Wc].pssh),n&&(i.push({playready:!0,initData:n}),(({video:e,initData:t,options:i,eventBus:s,emeError:r})=>{e.msKeys&&delete e.msKeys;try{e.msSetMediaKeys(new p.MSMediaKeys(Wc))}catch(e){throw r(e,{errorType:Oc.EMEFailedToCreateMediaKeys,keySystem:Wc}),new Error("Unable to create media keys for PlayReady key system. Error: "+e.message)}Gc(e,t,i,s,r)})({video:e.target,initData:n,options:t,eventBus:s,emeError:r}))},eh=e=>xc(e.currentSource(),e.eme.options),th=e=>{const t=e.src();t!==e.eme.activeSrc&&(e.eme.activeSrc=t,e.eme.sessions=[])},ih=(e,t)=>{if("video"===e.$(".vjs-tech").tagName.toLowerCase())if(th(e),p.MediaKeys){const i=()=>{const i={initDataType:"cenc",initData:null,target:e.tech_.el_};th(e),Jc(e,i,eh(e),e.eme.sessions,e.tech_,t)};if(Fo.browser.IS_FIREFOX){let t;e.on("ended",()=>{t=!1,e.one(["seek","play"],s=>{t||0!==e.eme.sessions.length||(i(),t=!0)})}),e.on("play",()=>{const s=e.eme.options.limitRenewalsMaxPauseDuration;0===e.eme.sessions.length&&"number"==typeof s&&(t=!0,i())})}e.tech_.el_.addEventListener("encrypted",i=>{Fo.log.debug("eme","Received an 'encrypted' event"),th(e),Jc(e,i,eh(e),e.eme.sessions,e.tech_,t)})}else if(p.WebKitMediaKeys)e.eme.initLegacyFairplay();else if(p.MSMediaKeys){e.tech_.el_.addEventListener("msneedkey",i=>{Fo.log.debug("eme","Received an 'msneedkey' event"),th(e);try{Zc(i,eh(e),e.eme.sessions,e.tech_,t)}catch(e){t(e)}});const i=e=>{t(e)};e.tech_.on("mskeyerror",i),e.on("dispose",()=>{e.tech_.off("mskeyerror",i)})}},sh=function(e={}){const t=this,i=(e=>(t,i)=>{const s={code:5};"string"==typeof t?s.message=t:t&&(t.message&&(s.message=t.message),t.cause&&(t.cause.length||t.cause.byteLength)&&(s.cause=t.cause),t.keySystem&&(s.keySystem=t.keySystem),s.originalError=t),i&&(s.metadata=i),e.error(s)})(t);t.ready(()=>ih(t,i)),t.eme={setupEmeListeners(){ih(t,i)},initializeMediaKeys(s={},r=function(){},n=!1){const a=xc(t.currentSource(),e,s),o={initDataType:"cenc",initData:null,target:t.tech_.el_};if(th(t),p.MediaKeys)Jc(t,o,a,t.eme.sessions,t.tech_,i).then(()=>r()).catch(e=>{r(e),n||i(e)});else if(p.MSMediaKeys){const e=s=>{t.tech_.off("mskeyadded",e),t.tech_.off("mskeyerror",e),"mskeyerror"===s.type?(r(s.target.error),n||i(s.message)):r()};t.tech_.one("mskeyadded",e),t.tech_.one("mskeyerror",e);try{Zc(o,a,t.eme.sessions,t.tech_,i)}catch(s){t.tech_.off("mskeyadded",e),t.tech_.off("mskeyerror",e),r(s),n||i(s)}}},initLegacyFairplay(){const e=e=>{Fo.log.debug("eme","Received a 'webkitneedkey' event"),th(t),((e,t,i,s)=>t.keySystems&&t.keySystems[Mc]&&e.initData?Fc({video:e.target,initData:e.initData,options:t,eventBus:i,emeError:s}):Promise.resolve())(e,eh(t),t.tech_,i).catch(e=>{i(e)})},s=i=>{const s=eh(t).firstWebkitneedkeyTimeout||1e3,r=t.src();t.eme.webkitneedkey_=t.eme.webkitneedkey_||{},t.eme.webkitneedkey_.src!==r&&(t.eme.webkitneedkey_={handledFirstEvent:!1,src:r}),t.eme.webkitneedkey_.handledFirstEvent?e(i):(t.clearTimeout(t.eme.webkitneedkey_.timeout),t.eme.webkitneedkey_.timeout=t.setTimeout(()=>{t.eme.webkitneedkey_.handledFirstEvent=!0,t.eme.webkitneedkey_.timeout=null,e(i)},s))};t.eme.legacyFairplayIsUsed=!0;let r=t.tech_.el_;r.addEventListener("webkitneedkey",s);const n=()=>{t.off("dispose",n),null!==r&&r.removeEventListener("webkitneedkey",s),t.eme.legacyFairplayIsUsed=!1,r=null};return t.on("dispose",n),n},detectSupportedCDMs:Yc,legacyFairplayIsUsed:!1,options:e}};Fo.registerPlugin("eme",sh),sh.Error=Oc,sh.VERSION="5.5.2";const rh=Fo.getComponent("player");class nh extends rh{constructor(e,t,i){super(e,t=Fo.obj.merge(t,{plugins:{eme:!0}}),i)}audioTrack(e){const t=Array.from(this.player().audioTracks());if(!e)return t.find(e=>e.enabled);const{kind:i,language:s}=e,r=t.find(e=>e.language===s&&e.kind===i)||t.find(e=>e.language===s);return r&&(r.enabled=!0),r}bufferedRanges(){const e=[];for(let t=0;t<this.buffered().length;t++){const i=this.buffered().start(t),s=this.buffered().end(t);e.push({start:i,end:s})}return e}playedPercent(){if(!Number.isFinite(this.duration()))return NaN;let e=0;for(let t=0;t!=this.played().length;t++)e+=this.played().end(t)-this.played().start(t);return e/this.duration()}playedRanges(){const e=[];for(let t=0;t<this.played().length;t++){const i=this.played().start(t),s=this.played().end(t);e.push({start:i,end:s})}return e}seekableRanges(){const e=[];for(let t=0;t<this.seekable().length;t++){const i=this.seekable().start(t),s=this.seekable().end(t);e.push({start:i,end:s})}return e}textTrack(e){const t=Array.from(this.player().textTracks()).filter(e=>!["chapters","metadata"].includes(e.kind));if(!e)return t.find(e=>"showing"===e.mode);t.forEach(e=>e.mode="disabled");const{kind:i,language:s}=e;return t.find(e=>(e.language===s&&e.kind===i&&(e.mode="showing"),"showing"===e.mode))||t.find(e=>(e.language===s&&(e.mode="showing"),"showing"===e.mode))}}Fo.registerComponent("player",nh);const ah=Fo;ah.VERSION={pillarbox:"1.24.1",videojs:Fo.VERSION,[Fo.VhsSourceHandler.name]:Fo.VhsSourceHandler.VERSION,eme:Fo.getPlugin("eme").VERSION},ah.options.enableSmoothSeeking=!0,ah.options.fill=!0,ah.options.html5={vhs:{useForcedSubtitles:!0}},ah.options.liveTracker={trackingThreshold:120,liveTolerance:15},ah.options.liveui=!0,ah.options.playsinline=!0,ah.options.responsive=!0,ah.options.trackers={};class oh{constructor(e="il.srgssr.ch"){this.setIlHost(e)}setIlHost(e){this.baseUrl=`${e}/integrationlayer/2.1/`}handleRequest(e){var t=this;return function(){var s=i(function*(i){const s="function"==typeof e?e(i):t.mediaCompositionUrlHandler(i),r=yield fetch(s);if(!r.ok)throw r;return yield r.json()});return function(e){return s.apply(this,arguments)}}()}mediaCompositionUrlHandler(e){return`https://${this.baseUrl}mediaComposition/byUrn/${e}?onlyChapters=true&vector=portalplay`}}const lh="240",dh="320",uh="480",ch="960",hh="1920",ph="jpg",mh="webp",gh="png";class fh{static scale({url:e,width:t=ch,format:i=ph}={},s="https://il.srgssr.ch/images/"){if(!e)return;const r=new URL(s);return r.searchParams.set("imageUrl",e),r.searchParams.set("format",i),r.searchParams.set("width",t),decodeURIComponent(r.href)}static get JPG(){return ph}static get PNG(){return gh}static get WEBP(){return mh}static get WIDTH_240(){return lh}static get WIDTH_320(){return dh}static get WIDTH_480(){return uh}static get WIDTH_960(){return ch}static get WIDTH_1920(){return hh}}const yh={WIDEVINE:"com.widevine.alpha",FAIRPLAY:"com.apple.fps.1_0",PLAYREADY:"com.microsoft.playready"};class _h{static buildKeySystems(e=[]){const t={};return e.forEach(e=>{const i=_h.vendors[e.type];if(_h.vendors.FAIRPLAY===i){const{certificateUrl:s,licenseUrl:r}=e;t[i]={certificateUri:s,licenseUri:r}}else t[i]=e.licenseUrl}),{keySystems:t}}static hasDrm(e){return e.some(({drmList:e})=>e&&e.length>0)}static get vendors(){return yh}}const bh="AKAMAI",vh="NONE";class Th{static aclPath(e){const t=e.pathname;return`${t.substring(0,t.lastIndexOf("/")+1)}*`}static get AKAMAI(){return bh}static hasToken(e){return e.some(e=>Th.isAkamai(e.tokenType))}static isAkamai(e){return bh===e}static isNone(e){return vh===e}static get NONE(){return vh}static tokenize(e,t){const i=new URL(`${e.url}`),s=Th.aclPath(i),r=`${t}${encodeURIComponent(s)}`;return fetch(r).then(e=>e.ok?e.json():Promise.reject({status:e.status,statusText:e.statusText})).then(({token:{authparams:t}})=>(new URLSearchParams(t).forEach((e,t)=>i.searchParams.set(t,e)),Object.assign({},e,{url:i.toString()}))).catch(e=>Promise.reject(e))}static tokenizeSources(e,t="https://tp.srgssr.ch/akahd/token?acl="){const i=[];return e.forEach(e=>{const s=Th.tokenize(e,t);i.push(s)}),Promise.all(i).then(e=>e).catch(e=>Promise.reject(e))}}const Sh="emptied",Eh="ended",wh="loadeddata",kh="loadstart",Ch="pause",Ih="play",xh="playing",Ah="ratechange",Dh="seeking",Ph="timeupdate",Lh="waiting";class Oh{constructor(e,{debug:t=!1,environment:i="prod",playerVersion:s="none",tagCommanderScriptURL:r="//colibri-js.akamaized.net/penguin/tc_SRGGD_11.js"}={}){this.isDebugEnabled=t,this.elapsedPlaybackTime=0,this.environment=i,this.hasStarted=!1,this.heartBeatIntervalId=void 0,this.initialized=!1,this.isSeeking=!1,this.isWaiting=!1,this.mediaSession=0,this.pendingQueue=[],this.pendingTagCommanderReload=!1,this.player=e,this.playerVersion=s,this.srcMediaData=void 0,this.startPlaybackSession=0,this.tagCommanderScriptURL=r,this.trackedCurrentTime=0,this.uptimeIntervalId=void 0,this.initScript(),this.initListeners()}beforeunload(){this.notify("stop")}clearTimers(){clearInterval(this.heartBeatIntervalId),clearInterval(this.uptimeIntervalId),clearTimeout(this.uptimeTimeoutId)}currentTime(){return Math.round(this.trackedCurrentTime)}debug(e){if(void 0===e)return this.isDebugEnabled||this.player.debug();this.isDebugEnabled=Boolean(e)}destroy(){this.clearTimers(),window.tc_vars||(window.tc_vars={}),this.elapsedPlaybackTime=0,this.hasStarted=!1,this.heartBeatIntervalId=void 0,this.initialized=!1,this.isWaiting=!1,this.mediaSession=0,this.pendingQueue=[],this.srcMediaData=void 0,this.startPlaybackSession=0,this.trackedCurrentTime=0,this.uptimeIntervalId=void 0}dispose(){this.beforeunload(),this.clearTimers(),window.removeEventListener("beforeunload",this.beforeunloadListener),this.player.off(Sh,this.emptiedListener),this.player.off(Eh,this.endedListener),this.player.off(kh,this.loadstartListener),this.player.off(wh,this.loadeddataListener),this.player.off(xh,this.playListener),this.player.off(Ch,this.pauseListener),this.player.off(Ah,this.rateChangeListener),this.player.off(Dh,this.seekingListener),this.player.off(Ph,this.timeUpdateListener),this.player.off(Lh,this.waitingListener)}emptied(){this.player.ended()||this.notify("stop")}ended(){this.notify("eof"),this.mediaSession=0,this.clearTimers()}flush(){this.isTrackerDisabled()||(this.pendingTagCommanderReload&&window.tC&&(window.tC.container.reload(),this.pendingTagCommanderReload=!1),window.tc_events_11&&this.pendingQueue.length>0&&(this.pendingQueue.forEach(e=>{window.tc_events_11(this.player.el(),e.action,e.labels)}),this.pendingQueue=[]))}getCurrentAudioTrack(){const e=Array.from(this.player.audioTracks()).find(e=>e.enabled);let t="und";return e&&e.language&&(t=e.language),e?t.toUpperCase():""}getCurrentTextTrack(){const e=this.player.textTrack();let t="und";return e&&e.language&&(t=e.language),e?t.toUpperCase():""}getDvrWindowPosition(){const{liveTracker:e}=this.player,t=this.currentTime()-e.seekableStart()|0,i=e.liveWindow()-t;return i<0||i===1/0?0:1e3*i}getDvrWindowSize(){const e=this.player.liveTracker.liveWindow()===1/0,t=1e3*this.player.liveTracker.liveWindow();return e?0:t}getElapsedPlaybackTime(){return this.startPlaybackSession?this.getElapsedPlayingTime():this.elapsedPlaybackTime}getElapsedPlayingTime(){const e=Oh.now()-this.startPlaybackSession|0;return this.elapsedPlaybackTime+e}getEventLabels(e){const t={event_id:e,event_timestamp:Oh.now(),media_dvr_window_length:0,media_dvr_window_offset:0,media_is_dvr:!1,media_is_live:!1,media_mute:this.player.muted()?"1":"0",media_playback_rate:this.player.playbackRate(),media_position:this.currentTime(),media_quality:this.srcMediaData.mediaData.quality,media_subtitles_on:this.isTextTrackEnabled(),media_volume:(100*this.player.volume()).toFixed(0),navigation_environment:this.environment};return this.isAudioTrackEnabled()&&(t.media_audio_track=this.getCurrentAudioTrack(),t.media_audiodescription_on=this.isAudioDescriptionEnabled()),this.isTextTrackEnabled()&&(t.media_subtitle_selection=this.getCurrentTextTrack()),this.isMediaOnDemand()||(t.media_is_live=!0,t.media_position=this.getElapsedPlaybackTime()),this.isMediaDvr()&&(t.media_dvr_window_offset=0|this.getDvrWindowPosition(),t.media_dvr_window_length=0|this.getDvrWindowSize(),t.media_is_dvr=!0,t.media_timeshift=[Ih,Ch].includes(e)?this.timeShifted():0),t}getInternalLabels(){const e={media_bu_distributer:this.srcMediaData.mediaData.vendor,media_chromecast_selected:Boolean(this.player.tech(!0).isCasting),media_embedding_url:document.referrer,media_player_display:"default",media_player_name:"pillarbox-web",media_player_version:this.playerVersion,media_url:this.srcMediaData.src},t=this.srcMediaData.mediaData.analyticsMetadata||{};window.tc_vars=Object.assign({},window.tc_vars,e,t)}heartBeat(){this.heartBeatIntervalId=setInterval(()=>{this.player.paused()||this.notify("pos")},3e4)}initCallbacks(){this.beforeunloadListener=this.beforeunload.bind(this),this.emptiedListener=this.emptied.bind(this),this.endedListener=this.ended.bind(this),this.loadstartListener=this.loadstart.bind(this),this.loadeddataListener=this.loadeddata.bind(this),this.playListener=this.play.bind(this),this.pauseListener=this.pause.bind(this),this.rateChangeListener=this.rateChange.bind(this),this.seekingListener=this.seeking.bind(this),this.timeUpdateListener=this.timeUpdate.bind(this),this.waitingListener=this.waiting.bind(this)}initListeners(){this.initCallbacks(),window.addEventListener("beforeunload",this.beforeunloadListener),this.player.on(Sh,this.emptiedListener),this.player.on(Eh,this.endedListener),this.player.on(kh,this.loadstartListener),this.player.on(wh,this.loadeddataListener),this.player.on(xh,this.playListener),this.player.on(Ch,this.pauseListener),this.player.on(Ah,this.rateChangeListener),this.player.on(Dh,this.seekingListener),this.player.on(Ph,this.timeUpdateListener),this.player.on(Lh,this.waitingListener),this.player.one("dispose",this.dispose.bind(this))}initScript(){const e="tc_script__11";if(!document.querySelector(`#${e}`)){const t=document.createElement("script"),i=this.tagCommanderScriptURL;t.defer=!0,t.id=e,t.src=i,t.type="text/javascript",t.onload=e=>{this.flush()},document.body.appendChild(t)}}isAudioDescriptionEnabled(){const e=Array.from(this.player.audioTracks()).find(e=>e.enabled&&e.kind.includes("desc"));return Boolean(e)}isAudioTrackEnabled(){return!!this.getCurrentAudioTrack()}isMediaDvr(){const{trackingThreshold:e}=this.player.liveTracker.options();return!this.isMediaOnDemand()&&e<this.player.liveTracker.liveWindow()}isMediaLive(){const{trackingThreshold:e}=this.player.liveTracker.options();return!this.isMediaOnDemand()&&e>this.player.liveTracker.liveWindow()}isMediaOnDemand(){return Number.isFinite(this.player.duration())}isTextTrackEnabled(){return!!this.getCurrentTextTrack()}isTrackerDisabled(){return!this.srcMediaData||!this.srcMediaData.mediaData||(Array.isArray(this.srcMediaData.disableTrackers)?Boolean(this.srcMediaData.disableTrackers.find(e=>e.toLowerCase()===Oh.name.toLowerCase())):Boolean(this.srcMediaData.disableTrackers))}loadstart(){this.destroy(),this.updateSrcMediaData(this.player.currentSource()),this.isTrackerDisabled()||(this.getInternalLabels(),this.reloadTagCommanderContainer(),this.notify("buffer_start"),this.hasStarted=!1)}loadeddata(){this.notify("init"),this.initialized=!0,this.notify("buffer_stop")}log(e,t,i="log"){this.debug()&&console[i](`SRGAnalytics:${e}`,t,window.tc_vars)}notify(e,t){if(this.isTrackerDisabled())return;try{this.flush()}catch(t){this.log(e,t,"error")}const i=Object.assign({},this.getEventLabels(e),t);this.log(e,i);try{window.tc_events_11?window.tc_events_11(this.player.el(),e,i):this.pendingQueue.push({action:e,labels:i})}catch(t){this.log(e,t,"error")}}static now(){return(Date.now()/1e3).toFixed(0)}play(){this.hasStarted||(this.hasStarted=!0),this.startPlaybackSession||this.isMediaOnDemand()||(this.startPlaybackSession=Oh.now()),0===this.mediaSession&&(this.mediaSession=Oh.now(),this.heartBeat(),this.uptime()),this.timeUpdate(),this.notify("play"),this.isSeeking&&(this.isSeeking=!1)}pause(){this.isMediaOnDemand()||(this.elapsedPlaybackTime=this.getElapsedPlayingTime(),this.startPlaybackSession=0),!this.player.seeking()&&!this.isMediaLive()&&this.player.currentTime()<this.player.duration()?this.notify("pause"):this.hasStarted&&!this.isSeeking&&(this.notify("seek"),this.isSeeking=!0)}rateChange(){this.notify("change_playback_rate")}reloadTagCommanderContainer(){window.tC?(window.tC.container.reload(),this.pendingTagCommanderReload=!1):this.pendingTagCommanderReload=!0}seeking(){!this.hasStarted||this.player.paused()||this.isSeeking||(this.notify("seek"),this.isSeeking=!0)}timeUpdate(){this.player.paused()||(this.trackedCurrentTime=this.player.currentTime())}timeShifted(){const e=this.player.liveTracker.atLiveEdge(),t=this.player.liveTracker.liveCurrentTime(),i=this.player.currentTime();return e?0:(t-i).toFixed(0)}updateSrcMediaData(e){this.srcMediaData=e}uptime(){const e=()=>{this.player.paused()||this.isMediaOnDemand()||this.notify("uptime")};this.uptimeTimeoutId=setTimeout(()=>{e(),this.uptimeIntervalId=setInterval(()=>{e()},6e4)},3e4)}waiting(){if(!this.initialized||this.isWaiting)return;const e=()=>{this.isWaiting=!1,this.notify("buffer_stop")};this.isWaiting=!0,this.notify("buffer_start"),ah.browser.IS_ANY_SAFARI?this.player.one(Ph,e):this.player.one(xh,e)}}class Mh{constructor(e,{playerName:t="none",playerVersion:i="none",platform:s="Web",schemaVersion:r=1,heartbeatInterval:n=3e4,beaconUrl:a="https://monitoring.pillarbox.ch/api/events"}={}){this.player=e,this.playerName=t,this.playerVersion=i,this.platform=s,this.schemaVersion=r,this.heartbeatInterval=n,this.beaconUrl=a,this.currentSessionId=void 0,this.lastPlaybackDuration=0,this.lastPlaybackStartTimestamp=0,this.lastStallCount=0,this.lastStallDuration=0,this.loadStartTimestamp=void 0,this.metadataRequestTime=0,this.mediaAssetUrl=void 0,this.mediaId=void 0,this.mediaMetadataUrl=void 0,this.mediaOrigin=void 0,this.tokenRequestTime=0,this.addListeners()}addListeners(){this.bindCallBacks(),this.player.on("loadstart",this.loadStart),this.player.on("loadeddata",this.loadedData),this.player.on("playing",this.playbackStart),this.player.on("pause",this.playbackStop),this.player.on("error",this.error),this.player.on(["playerreset","dispose","ended"],this.sessionStop),this.player.on(["waiting","stalled"],this.stalled),window.addEventListener("beforeunload",this.sessionStop)}bandwidth(){const e=this.player.tech(!0).vhs?this.player.tech(!0).vhs.stats:void 0;return e?e.bandwidth:void 0}bindCallBacks(){this.error=this.error.bind(this),this.loadedData=this.loadedData.bind(this),this.loadStart=this.loadStart.bind(this),this.playbackStart=this.playbackStart.bind(this),this.playbackStop=this.playbackStop.bind(this),this.stalled=this.stalled.bind(this),this.sessionStop=this.sessionStop.bind(this)}bufferDuration(){const e=this.player.buffered();let t=0;for(let i=0;i<e.length;i++){const s=e.start(i);t+=e.end(i)-s}return Mh.secondsToMilliseconds(t)}currentAudioTrack(){const e=this.player.audioTrack();if(e&&e.language)return e.language}currentRepresentation(){const{activeCues:{cues_:[e]}={cues_:[]}}=Array.from(this.player.textTracks()).find(({label:e,kind:t})=>"metadata"===t&&"segment-metadata"===e)||{};return e?e.value:void 0}currentResource(){let{bandwidth:e,uri:t}=this.currentRepresentation()||{};if(ah.browser.IS_ANY_SAFARI){const{configuration:i}=Array.from(this.player.videoTracks()).find(e=>e.selected)||{};e=i?i.bitrate:void 0,t=this.player.currentSource().src}return{bitrate:e,url:t}}currentSourceMediaData(){return this.player.currentSource().mediaData?this.player.currentSource().mediaData:{}}currentTextTrack(){const e=this.player.textTrack();if(e&&e.language)return e.language}error(){const e=this.currentAudioTrack(),t=this.player.error(),i=this.playbackPosition(),s=this.currentRepresentation(),r=s?s.uri:this.player.currentSource().src,a=this.currentTextTrack();this.player.hasStarted()||this.sendEvent("START",this.startEventData()),this.sendEvent("ERROR",n(n({audio:e,log:JSON.stringify(t.metadata||ah.log.history().slice(-15)),message:t.message,name:Mh.errorKeyCode(t.code)},i),{},{subtitles:a,url:r})),this.reset()}getDrmRequestDuration(){const e=Object.values(this.player.currentSource().keySystems||{}).map(e=>e.url);if(!e.length)return;const t=performance.getEntriesByType("resource").filter(({initiatorType:t,name:i})=>"xmlhttprequest"===t&&e.includes(i)).pop();return t&&t.duration}getMetadataInfo(e){const t=performance.getEntriesByType("resource").filter(({initiatorType:t,name:i})=>"fetch"===t&&i.includes(e)).pop();return t?{name:t.name,duration:t.duration}:{}}getTokenRequestDuration(e){if(!e)return;const t=performance.getEntriesByType("resource").filter(({initiatorType:e,name:t})=>"fetch"===e&&t.includes("/akahd/token")).pop();return t&&t.duration}heartbeat(){this.heartbeatIntervalId=setInterval(()=>{this.sendEvent("HEARTBEAT",this.statusEventData())},this.heartbeatInterval)}isTrackerDisabled(){const e=this.player.currentSource();return Array.isArray(e.disableTrackers)?Boolean(e.disableTrackers.find(e=>e.toLowerCase()===Mh.name.toLowerCase())):Boolean(e.disableTrackers)}loadedData(){this.sendEvent("START",this.startEventData()),this.sendEvent("HEARTBEAT",this.statusEventData()),this.heartbeat()}loadStart(){!Object.keys(this.currentSourceMediaData()).length&&this.currentSessionId&&(this.sessionStop(),this.sessionStartTimestamp=Mh.timestamp()),this.loadStartTimestamp=Mh.timestamp()}mediaInfo(){return{asset_url:this.mediaAssetUrl,id:this.mediaId,metadata_url:this.mediaMetadataUrl,origin:this.mediaOrigin}}playbackDuration(){return this.lastPlaybackStartTimestamp?Mh.timestamp()+this.lastPlaybackDuration-this.lastPlaybackStartTimestamp:this.lastPlaybackDuration}playbackPosition(){const e=this.currentRepresentation(),t=Mh.secondsToMilliseconds(this.player.currentTime());let i;if(e&&(i=e.programDateTime),ah.browser.IS_ANY_SAFARI){const e=Date.parse(this.player.$("video").getStartDate());i=isNaN(e)?void 0:e+t}return{position:t,position_timestamp:i}}playbackStart(){this.lastPlaybackStartTimestamp=Mh.timestamp()}playbackStop(){this.lastPlaybackDuration+=Mh.timestamp()-this.lastPlaybackStartTimestamp,this.lastPlaybackStartTimestamp=0}playerCurrentDimensions(){return this.player.currentDimensions()}playerInfo(){return{name:this.playerName,version:this.playerVersion,platform:this.platform}}qoeTimings(e,t){return{metadata:this.metadataRequestTime,asset:e,total:t-this.sessionStartTimestamp}}qosTimings(e){return{asset:e,drm:this.getDrmRequestDuration(),metadata:this.metadataRequestTime,token:this.tokenRequestTime}}removeListeners(){this.player.off("loadstart",this.loadStart),this.player.off("loadeddata",this.loadedData),this.player.off("playing",this.playbackStart),this.player.off("pause",this.playbackStop),this.player.off("error",this.error),this.player.off(["playerreset","dispose","ended"],this.sessionStop),this.player.off(["waiting","stalled"],this.stalled),window.removeEventListener("beforeunload",this.sessionStop)}removeTokenFromAssetUrl(e){if(e)try{const t=new URL(e);return t.searchParams.delete("hdnts"),t.href}catch(e){return}}reset(e){this.currentSessionId=void 0,this.lastPlaybackDuration=0,this.lastPlaybackStartTimestamp=0,this.lastStallCount=0,this.lastStallDuration=0,this.loadStartTimestamp=0,this.metadataRequestTime=0,this.mediaAssetUrl=void 0,this.mediaId=void 0,this.mediaMetadataUrl=void 0,this.mediaOrigin=void 0,this.sessionStartTimestamp=void 0,this.tokenRequestTime=0,clearInterval(this.heartbeatIntervalId),e&&!["ended","playerreset"].includes(e.type)&&this.removeListeners()}sendEvent(e,t={}){if(this.isTrackerDisabled()&&!this.currentSessionId||!this.currentSessionId)return;const i=JSON.stringify({event_name:e,session_id:this.currentSessionId,timestamp:Mh.timestamp(),version:this.schemaVersion,data:t});navigator.sendBeacon(this.beaconUrl,i)}sessionStart(){this.sessionStartTimestamp&&this.sessionStop(),this.sessionStartTimestamp=Mh.timestamp(),this.mediaId=this.player.currentSource().src||void 0}sessionStop(e){this.sendEvent("STOP",this.statusEventData()),this.reset(e)}stalled(){if(!this.player.hasStarted()||this.player.seeking()||this.isStalled)return;this.isStalled=!0;const e=Mh.timestamp(),t=()=>{const t=Mh.timestamp();this.isStalled=!1,this.lastStallCount+=1,this.lastStallDuration+=t-e};ah.browser.IS_ANY_SAFARI?this.player.one("timeupdate",t):this.player.one("playing",t)}stallInfo(){return{count:this.lastStallCount,duration:this.lastStallDuration}}statusEventData(){const e=this.currentAudioTrack(),t=this.bandwidth(),i=this.bufferDuration(),{bitrate:s,url:r}=this.currentResource(),{droppedVideoFrames:n}=this.player.getVideoPlaybackQuality()||{},a=this.playbackDuration(),{position:o,position_timestamp:l}=this.playbackPosition(),d=isFinite(this.player.duration())?"On-demand":"Live";return{audio:e,bandwidth:t,bitrate:s,buffered_duration:i,frame_drops:n,playback_duration:a,position:o,position_timestamp:l,stall:this.stallInfo(),stream_type:d,subtitles:this.currentTextTrack(),url:r}}startEventData(){const e=Mh.timestamp(),t=this.loadStartTimestamp?e-this.loadStartTimestamp:0;return this.isTrackerDisabled()||(this.currentSessionId=Mh.sessionId()),this.mediaAssetUrl=this.removeTokenFromAssetUrl(this.player.currentSource().src),this.mediaMetadataUrl=this.getMetadataInfo(this.mediaId).name,this.metadataRequestTime=this.getMetadataInfo(this.mediaId).duration,this.mediaOrigin=window.location.href,this.tokenRequestTime=this.getTokenRequestDuration(this.currentSourceMediaData().tokenType),{browser:Mh.userAgent(),device:{id:Mh.deviceId()},media:this.mediaInfo(),player:this.playerInfo(),qoe_timings:this.qoeTimings(t,e),qos_timings:this.qosTimings(t),screen:this.playerCurrentDimensions()}}static errorKeyCode(e){return`${["MEDIA_ERR_CUSTOM",...Object.keys(window.MediaError),"MEDIA_ERR_ENCRYPTED"][e]}: ${e}`}static sessionId(){return Mh.randomUUID()}static deviceId(){if(!localStorage)return;const e="pillarbox_device_id";let t=localStorage.getItem(e);return t||(t=Mh.randomUUID(),localStorage.setItem(e,t)),t}static randomUUID(){return crypto.randomUUID?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+e/4).toString(16))}static secondsToMilliseconds(e){return parseInt(1e3*e)}static timestamp(){return Date.now()}static userAgent(){return{user_agent:navigator.userAgent}}}class Rh{findChapterByUrn(e){if(this.chapterList){const[t]=this.chapterList.filter(t=>t.urn===e);return t}}findMainSegment(){if(!this.segmentUrn)return;const e=this.getMainSegments(),[t]=e.filter(e=>e.urn===this.segmentUrn);return t}findResourceListByUrn(e){const t=this.findChapterByUrn(e);if(t)return t.resourceList||[]}getChapters(){const e="AUDIO";return this.getMainChapter().mediaType===e||"EPISODE"!==this.getMainChapter().type?[]:this.chapterList.filter(({mediaType:t})=>t!==e)}getFilteredExternalSubtitles(){const{subtitleList:e}=this.getMainChapter(),[{subtitleInformationList:t}={}]=this.getResourceList().filter(({subtitleInformationList:e})=>e),i=e&&!t;if(!e)return[];const s=e.filter(e=>"TTML"!==e.format);return i?s:s.filter(e=>!t.find(t=>t.locale===e.locale&&e.type===t.type))}getMainBlockReason(){const e=this.getMainChapter();if(!e)return;let{blockReason:t}=e;return!t&&new Date<this.getMainValidFromDate()&&(t="STARTDATE"),t}getMainBlockedSegments(){return this.getMainSegments().filter(e=>e.blockReason)}getMainChapter(){return this.mainChapter||(this.mainChapter=this.findChapterByUrn(this.chapterUrn)),!this.mainChapter&&this.chapterList&&this.chapterList.length>0&&([this.mainChapter]=this.chapterList),this.mainChapter}getMainChapterImageUrl(){const e=this.getMainChapter();if(e&&e.imageUrl)return e.imageUrl}getMainResources(){const e=this.getResourceList();if(e&&e.length)return e.map(e=>({analyticsData:this.getMergedAnalyticsData(e.analyticsData),analyticsMetadata:this.getMergedAnalyticsMetadata(e.analyticsMetadata),blockReason:this.getMainChapter().blockReason,blockedSegments:this.getMainBlockedSegments(),imageUrl:this.getMainChapterImageUrl(),chapters:this.getChapters(),description:this.getMainChapter().description,drmList:e.drmList,dvr:e.dvr,eventData:this.getMainChapter().eventData,id:this.getMainChapter().id,imageCopyright:this.getMainChapter().imageCopyright,intervals:this.getMainTimeIntervals(),live:e.live,mediaContainer:e.mediaContainer,mediaType:this.getMainChapter().mediaType,mimeType:e.mimeType,presentation:e.presentation,quality:e.quality,spriteSheet:this.getMainChapter().spriteSheet,streaming:e.streaming,streamOffset:e.streamOffset,subtitles:this.getFilteredExternalSubtitles(),title:this.getMainChapter().title,tokenType:e.tokenType,url:e.url,urn:this.chapterUrn,vendor:this.getMainChapter().vendor}))}getMainSegments(){const e=this.getMainChapter();return!this.mainSegments&&e&&e.segmentList&&(this.mainSegments=e.segmentList),this.mainSegments||[]}getMainTimeIntervals(){const{timeIntervalList:e=[]}=this.getMainChapter()||{};return e}getMainValidFromDate(){const e=this.getMainChapter();if(!e)return new Date(0);const{validFrom:t}=e;return t?new Date(t):void 0}getMergedAnalyticsData(e){return n(n(n({},this.analyticsData),this.getMainChapter().analyticsData),e)}getMergedAnalyticsMetadata(e){return n(n(n({},this.analyticsMetadata),this.getMainChapter().analyticsMetadata),e)}getResourceList(){const{resourceList:e}=this.getMainChapter();return e||[]}}const Nh={Play:"Wiedergabe",Pause:"Pause",Replay:"Erneut abspielen","Current Time":"Aktueller Zeitpunkt",Duration:"Dauer","Remaining Time":"Verbleibende Zeit","Stream Type":"Streamtyp",LIVE:"LIVE",Loaded:"Geladen",Progress:"Status",Fullscreen:"Vollbild","Exit Fullscreen":"Vollbildmodus beenden",Mute:"Stumm schalten",Unmute:"Ton einschalten","Playback Rate":"Wiedergabegeschwindigkeit",Subtitles:"Untertitel","subtitles off":"Untertitel aus",Captions:"Untertitel","captions off":"Untertitel aus",Chapters:"Kapitel","You aborted the media playback":"Sie haben die Videowiedergabe abgebrochen.","A network error caused the media download to fail part-way.":"Der Videodownload ist aufgrund eines Netzwerkfehlers fehlgeschlagen.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Das Video konnte nicht geladen werden, da entweder ein Server- oder Netzwerkfehler auftrat oder das Format nicht unterstützt wird.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Die Videowiedergabe wurde entweder wegen eines Problems mit einem beschädigten Video oder wegen verwendeten Funktionen, die vom Browser nicht unterstützt werden, abgebrochen.","No compatible source was found for this media.":"Für dieses Video wurde keine kompatible Quelle gefunden.","Play Video":"Video abspielen",Close:"Schließen","Modal Window":"Modales Fenster","This is a modal window":"Dies ist ein modales Fenster","This modal can be closed by pressing the Escape key or activating the close button.":'Durch Drücken der Esc-Taste bzw. Betätigung der Schaltfläche "Schließen" wird dieses modale Fenster geschlossen.',", opens captions settings dialog":", öffnet Einstellungen für Untertitel",", opens subtitles settings dialog":", öffnet Einstellungen für Untertitel",", selected":", ausgewählt","captions settings":"Untertiteleinstellungen","subtitles settings":"Untertiteleinstellungen","descriptions settings":"Einstellungen für Beschreibungen","Close Modal Dialog":"Modales Fenster schließen",Descriptions:"Beschreibungen","descriptions off":"Beschreibungen aus","The media is encrypted and we do not have the keys to decrypt it.":"Die Entschlüsselungsschlüssel für den verschlüsselten Medieninhalt sind nicht verfügbar.",", opens descriptions settings dialog":", öffnet Einstellungen für Beschreibungen","Audio Track":"Tonspur",Text:"Schrift",White:"Weiß",Black:"Schwarz",Red:"Rot",Green:"Grün",Blue:"Blau",Yellow:"Gelb",Magenta:"Magenta",Cyan:"Türkis",Background:"Hintergrund",Window:"Fenster",Transparent:"Durchsichtig","Semi-Transparent":"Halbdurchsichtig",Opaque:"Undurchsichtig","Font Size":"Schriftgröße","Text Edge Style":"Textkantenstil",None:"Kein",Raised:"Erhoben",Depressed:"Gedrückt",Uniform:"Uniform","Drop shadow":"Schlagschatten","Font Family":"Schriftfamilie","Proportional Sans-Serif":"Proportionale Sans-Serif","Monospace Sans-Serif":"Monospace Sans-Serif","Proportional Serif":"Proportionale Serif","Monospace Serif":"Monospace Serif",Casual:"Zwanglos",Script:"Schreibschrift","Small Caps":"Small-Caps",Reset:"Zurücksetzen","restore all settings to the default values":"Alle Einstellungen auf die Standardwerte zurücksetzen",Done:"Fertig","Caption Settings Dialog":"Einstellungsdialog für Untertitel","Beginning of dialog window. Escape will cancel and close the window.":"Anfang des Dialogfensters. Esc bricht ab und schließt das Fenster.","End of dialog window.":"Ende des Dialogfensters.","Audio Player":"Audio-Player","Video Player":"Video-Player","Progress Bar":"Fortschrittsbalken","progress bar timing: currentTime={1} duration={2}":"{1} von {2}","Volume Level":"Lautstärke","{1} is loading.":"{1} wird geladen.","Seek to live, currently behind live":"Zur Live-Übertragung wechseln. Aktuell wird es nicht live abgespielt.","Seek to live, currently playing live":"Zur Live-Übertragung wechseln. Es wird aktuell live abgespielt.","Exit Picture-in-Picture":"Bild-im-Bild-Modus beenden","Picture-in-Picture":"Bild-im-Bild-Modus","No content":"Kein Inhalt",Color:"Farbe",Opacity:"Deckkraft","Text Background":"Texthintergrund","Caption Area Background":"Hintergrund des Untertitelbereichs","Playing in Picture-in-Picture":"Wird im Bild-im-Bild-Modus wiedergegeben","Skip forward {1} seconds":"{1} Sekunden vorwärts","Skip backward {1} seconds":"{1} Sekunden zurück"},Uh={AGERATING12:"Aus Gründen des Jugendschutzes steht dieser Inhalt nur zwischen 20:00 und 06:00 Uhr zur Verfügung.",AGERATING18:"Aus Gründen des Jugendschutzes steht dieser Inhalt nur zwischen 23:00 und 05:00 Uhr zur Verfügung.",COMMERCIAL:"Die Werbung wurde übersprungen.",ENDDATE:"Dieser Inhalt ist nicht mehr verfügbar.",GEOBLOCK:"Dieser Inhalt ist ausserhalb der Schweiz nicht verfügbar.",JOURNALISTIC:"Dieser Inhalt steht aus publizistischen Gründen vorübergehend nicht zur Verfügung.",LEGAL:"Dieser Inhalt ist aus rechtlichen Gründen nicht verfügbar.",STARTDATE:"Dieser Inhalt ist noch nicht verfügbar. Bitte probieren Sie es später noch einmal.",VPNORPROXYDETECTED:"Dieser Inhalt ist mit VPN oder Proxy nicht abspielbar.",UNKNOWN:"Dieser Inhalt ist nicht verfügbar."};ah.addLanguage("de",n(n({},Nh),Uh));const Bh={"Audio Player":"Audio Player","Video Player":"Video Player",Play:"Play",Pause:"Pause",Replay:"Replay","Current Time":"Current Time",Duration:"Duration","Remaining Time":"Remaining Time","Stream Type":"Stream Type",LIVE:"LIVE","Seek to live, currently behind live":"Seek to live, currently behind live","Seek to live, currently playing live":"Seek to live, currently playing live",Loaded:"Loaded",Progress:"Progress","Progress Bar":"Progress Bar","progress bar timing: currentTime={1} duration={2}":"{1} of {2}",Fullscreen:"Fullscreen","Exit Fullscreen":"Exit Fullscreen",Mute:"Mute",Unmute:"Unmute","Playback Rate":"Playback Rate",Subtitles:"Subtitles","subtitles off":"subtitles off",Captions:"Captions","captions off":"captions off",Chapters:"Chapters",Descriptions:"Descriptions","descriptions off":"descriptions off","Audio Track":"Audio Track","Volume Level":"Volume Level","You aborted the media playback":"You aborted the media playback","A network error caused the media download to fail part-way.":"A network error caused the media download to fail part-way.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"The media could not be loaded, either because the server or network failed or because the format is not supported.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"The media playback was aborted due to a corruption problem or because the media used features your browser did not support.","No compatible source was found for this media.":"No compatible source was found for this media.","The media is encrypted and we do not have the keys to decrypt it.":"The media is encrypted and we do not have the keys to decrypt it.","Play Video":"Play Video",Close:"Close","Close Modal Dialog":"Close Modal Dialog","Modal Window":"Modal Window","This is a modal window":"This is a modal window","This modal can be closed by pressing the Escape key or activating the close button.":"This modal can be closed by pressing the Escape key or activating the close button.",", opens captions settings dialog":", opens captions settings dialog",", opens subtitles settings dialog":", opens subtitles settings dialog",", opens descriptions settings dialog":", opens descriptions settings dialog",", selected":", selected","captions settings":"captions settings","subtitles settings":"subtitles settings","descriptions settings":"descriptions settings",Text:"Text",White:"White",Black:"Black",Red:"Red",Green:"Green",Blue:"Blue",Yellow:"Yellow",Magenta:"Magenta",Cyan:"Cyan",Background:"Background",Window:"Window",Transparent:"Transparent","Semi-Transparent":"Semi-Transparent",Opaque:"Opaque","Font Size":"Font Size","Text Edge Style":"Text Edge Style",None:"None",Raised:"Raised",Depressed:"Depressed",Uniform:"Uniform","Drop shadow":"Drop shadow","Font Family":"Font Family","Proportional Sans-Serif":"Proportional Sans-Serif","Monospace Sans-Serif":"Monospace Sans-Serif","Proportional Serif":"Proportional Serif","Monospace Serif":"Monospace Serif",Casual:"Casual",Script:"Script","Small Caps":"Small Caps",Reset:"Reset","restore all settings to the default values":"restore all settings to the default values",Done:"Done","Caption Settings Dialog":"Caption Settings Dialog","Beginning of dialog window. Escape will cancel and close the window.":"Beginning of dialog window. Escape will cancel and close the window.","End of dialog window.":"End of dialog window.","{1} is loading.":"{1} is loading.","Exit Picture-in-Picture":"Exit Picture-in-Picture","Picture-in-Picture":"Picture-in-Picture","No content":"No content",Color:"Color",Opacity:"Opacity","Text Background":"Text Background","Caption Area Background":"Caption Area Background","Playing in Picture-in-Picture":"Playing in Picture-in-Picture","Skip backward {1} seconds":"Skip backward {1} seconds","Skip forward {1} seconds":"Skip forward {1} seconds"},Fh={AGERATING12:"To protect children this content is only available between 8PM and 6AM.",AGERATING18:"To protect children this content is only available between 10PM and 5AM.",COMMERCIAL:"This commercial content is not available.",ENDDATE:"This content is not available anymore.",GEOBLOCK:"This content is not available outside Switzerland.",JOURNALISTIC:"This content is temporarily unavailable for journalistic reasons.",LEGAL:"This content is not available due to legal restrictions.",STARTDATE:"This content is not available yet.",VPNORPROXYDETECTED:"This content cannot be played while using a VPN or a proxy.",UNKNOWN:"This content is not available."};ah.addLanguage("en",n(n({},Bh),Fh));const qh={"Audio Player":"Lecteur audio","Video Player":"Lecteur vidéo",Play:"Lecture",Pause:"Pause",Replay:"Revoir","Current Time":"Temps actuel",Duration:"Durée","Remaining Time":"Temps restant","Stream Type":"Type de flux",LIVE:"EN DIRECT","Seek to live, currently behind live":"Rechercher le direct, actuellement après le direct","Seek to live, currently playing live":"Rechercher le direct, le direct actuellement en cours de lecture",Loaded:"Chargé",Progress:"Progression","Progress Bar":"Barre de progression","progress bar timing: currentTime={1} duration={2}":"{1} de {2}",Fullscreen:"Plein écran","Exit Fullscreen":"Fenêtré",Mute:"Mettre en sourdine",Unmute:"Activer le son","Playback Rate":"Vitesse de lecture",Subtitles:"Sous-titres","subtitles off":"Sous-titres désactivés",Captions:"Sous-titres transcrits","captions off":"Sous-titres transcrits désactivés",Chapters:"Chapitres",Descriptions:"Descriptions","descriptions off":"descriptions désactivées","Audio Track":"Piste audio","Volume Level":"Niveau de volume","You aborted the media playback":"Vous avez interrompu la lecture de la vidéo.","A network error caused the media download to fail part-way.":"Une erreur de réseau a interrompu le téléchargement de la vidéo.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Cette vidéo n'a pas pu être chargée, soit parce que le serveur ou le réseau a échoué ou parce que le format n'est pas reconnu.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"La lecture de la vidéo a été interrompue à cause d'un problème de corruption ou parce que la vidéo utilise des fonctionnalités non prises en charge par votre navigateur.","No compatible source was found for this media.":"Aucune source compatible n'a été trouvée pour cette vidéo.","The media is encrypted and we do not have the keys to decrypt it.":"Le média est chiffré et nous n'avons pas les clés pour le déchiffrer.","Play Video":"Lire la vidéo",Close:"Fermer","Close Modal Dialog":"Fermer la boîte de dialogue modale","Modal Window":"Fenêtre modale","This is a modal window":"Ceci est une fenêtre modale","This modal can be closed by pressing the Escape key or activating the close button.":"Ce modal peut être fermé en appuyant sur la touche Échap ou activer le bouton de fermeture.",", opens captions settings dialog":", ouvrir les paramètres des sous-titres transcrits",", opens subtitles settings dialog":", ouvrir les paramètres des sous-titres",", opens descriptions settings dialog":", ouvrir les paramètres des descriptions",", selected":", sélectionné","captions settings":"Paramètres des sous-titres transcrits","subtitles settings":"Paramètres des sous-titres","descriptions settings":"Paramètres des descriptions",Text:"Texte",White:"Blanc",Black:"Noir",Red:"Rouge",Green:"Vert",Blue:"Bleu",Yellow:"Jaune",Magenta:"Magenta",Cyan:"Cyan",Background:"Arrière-plan",Window:"Fenêtre",Transparent:"Transparent","Semi-Transparent":"Semi-transparent",Opaque:"Opaque","Font Size":"Taille des caractères","Text Edge Style":"Style des contours du texte",None:"Aucun",Raised:"Élevé",Depressed:"Enfoncé",Uniform:"Uniforme","Drop shadow":"Ombre portée","Font Family":"Famille de polices","Proportional Sans-Serif":"Polices à chasse variable sans empattement (Proportional Sans-Serif)","Monospace Sans-Serif":"Polices à chasse fixe sans empattement (Monospace Sans-Serif)","Proportional Serif":"Polices à chasse variable avec empattement (Proportional Serif)","Monospace Serif":"Polices à chasse fixe avec empattement (Monospace Serif)",Casual:"Manuscrite",Script:"Scripte","Small Caps":"Petites capitales",Reset:"Réinitialiser","restore all settings to the default values":"Restaurer tous les paramètres aux valeurs par défaut",Done:"Terminé","Caption Settings Dialog":"Boîte de dialogue des paramètres des sous-titres transcrits","Beginning of dialog window. Escape will cancel and close the window.":"Début de la fenêtre de dialogue. La touche d'échappement annulera et fermera la fenêtre.","End of dialog window.":"Fin de la fenêtre de dialogue.","Exit Picture-in-Picture":"Quitter le mode image dans l'image","Picture-in-Picture":"Image dans l'image","{1} is loading.":"{1} en cours de chargement.","No content":"Aucun contenu",Color:"Couleur",Opacity:"Opacité","Text Background":"Arrière-plan du texte","Caption Area Background":"Arrière-plan de la zone de sous-titre","Skip backward {1} seconds":"Reculer de {1} secondes","Skip forward {1} seconds":"Avancer de {1} secondes"},jh={AGERATING12:"Pour protéger les enfants, ce contenu est accessible entre 20h et 6h.",AGERATING18:"Pour protéger les enfants, ce contenu est accessible entre 23h et 5h.",COMMERCIAL:"Ce contenu n'est actuellement pas disponible.",ENDDATE:"Ce contenu n'est plus disponible.",GEOBLOCK:"La RTS ne dispose pas des droits de diffusion en dehors de la Suisse.",JOURNALISTIC:"Ce contenu est temporairement indisponible pour des raisons éditoriales.",LEGAL:"Pour des raisons juridiques, ce contenu n'est pas disponible.",STARTDATE:"Ce contenu n'est pas encore disponible. Veuillez réessayer plus tard.",VPNORPROXYDETECTED:"Ce contenu ne peut pas être lu avec un VPN ou un proxy.",UNKNOWN:"Ce contenu n'est actuellement pas disponible."};ah.addLanguage("fr",n(n({},qh),jh));const Vh={"Audio Player":"Lettore audio","Video Player":"Lettore video",Play:"Play",Pause:"Pausa",Replay:"Replay","Current Time":"Orario attuale",Duration:"Durata","Remaining Time":"Tempo rimanente","Stream Type":"Tipo di streaming",LIVE:"LIVE",Loaded:"Caricato",Progress:"Stato","Progress Bar":"Barra di avanzamento","progress bar timing: currentTime={1} duration={2}":"{1} di {2}",Fullscreen:"Schermo intero","Exit Fullscreen":"Chiudi Schermo intero",Mute:"Disattiva l’audio",Unmute:"Attiva l’audio","Playback Rate":"Velocità di riproduzione",Subtitles:"Sottotitoli","subtitles off":"Senza sottotitoli",Captions:"Didascalie","captions off":"Senza didascalie",Chapters:"Capitolo",Descriptions:"Descrizioni","descriptions off":"Descrizioni disattivate","Audio Track":"Traccia audio","Volume Level":"Livello del volume","You aborted the media playback":"La riproduzione del contenuto multimediale è stata interrotta.","A network error caused the media download to fail part-way.":"Il download del contenuto multimediale è stato interrotto a causa di un problema rete.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Il contenuto multimediale non può essere caricato a causa di un errore nel server o nella rete o perché il formato non viene supportato.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"La riproduzione del contenuto multimediale è stata interrotta a causa di un file danneggiato o per l’utilizzo di impostazioni non supportate dal browser.","No compatible source was found for this media.":"Non ci sono fonti compatibili per questo contenuto multimediale.","The media is encrypted and we do not have the keys to decrypt it.":"Il contenuto multimediale è criptato e non disponiamo delle chiavi per decifrarlo.","Play Video":"Riproduci il video",Close:"Chiudi","Close Modal Dialog":"Chiudi la finestra di dialogo","Modal Window":"Finestra di dialogo","This is a modal window":"Questa è una finestra di dialogo","This modal can be closed by pressing the Escape key or activating the close button.":"Questa finestra di dialogo può essere chiusa premendo sul tasto Esc o attivando il pulsante di chiusura.",", opens captions settings dialog":", aprire le impostazioni delle didascalie",", opens subtitles settings dialog":", aprire le impostazioni dei sottotitoli",", opens descriptions settings dialog":", aprire le impostazioni delle descrizioni",", selected":", selezionato","captions settings":"Impostazioni didascalie","subtitles settings":"Impostazioni sottotitoli","descriptions settings":"Impostazioni descrizioni",Text:"Testo",White:"Bianco",Black:"Nero",Red:"Rosso",Green:"Verde",Blue:"Blu",Yellow:"Giallo",Magenta:"Magenta",Cyan:"Ciano",Background:"Sfondo",Window:"Finestra",Transparent:"Trasparente","Semi-Transparent":"Semi-Trasparente",Opaque:"Opaco","Font Size":"Dimensione dei caratteri","Text Edge Style":"Stile dei bordi del testo",None:"Nessuno",Uniform:"Uniforme","Drop shadow":"Ombra","Font Family":"Carattere","Proportional Sans-Serif":"Sans-Serif proporzionale","Monospace Sans-Serif":"Sans-Serif monospaziato","Proportional Serif":"Serif proporzionale","Monospace Serif":"Serif monospaziato","Small Caps":"Maiuscoletto",Reset:"Reinizializza","restore all settings to the default values":"Ripristina i valori predefiniti per tutti i parametri",Done:"Fatto","Caption Settings Dialog":"Finestra di dialogo dei parametri della trascrizione dei sottotitoli","Beginning of dialog window. Escape will cancel and close the window.":"Inizio della finestra di dialogo. Il tasto Esc annullerà l’operazione e chiuderà la finestra.","End of dialog window.":"Fine della finestra di dialogo.","{1} is loading.":"{1} in fase di caricamento.","Exit Picture-in-Picture":"Esci dalla modalità Picture-in-Picture","Picture-in-Picture":"Picture-in-Picture",Color:"Colore",Opacity:"Opacità","Text Background":"Sfondo testo","Caption Area Background":"Sfondo area sottotitoli","Skip forward {1} seconds":"Avanti {1} secondi","Skip backward {1} seconds":"Indietro {1} secondi"},$h={AGERATING12:"Per proteggere i bambini, questo media è disponibile solo fra le 20 e le 6.",AGERATING18:"Per proteggere i bambini, questo media è disponibile solo fra le 23 le 5.",COMMERCIAL:"Questo contenuto commerciale non è disponibile.",ENDDATE:"Questo media non è più disponibile.",GEOBLOCK:"Questo media non è disponibile fuori dalla Svizzera.",JOURNALISTIC:"Questo contenuto è temporaneamente non disponibile per motivi editoriali.",LEGAL:"Il contenuto non è fruibile a causa di restrizioni legali.",STARTDATE:"Il contenuto non è ancora disponibile. Per cortesia prova più tardi.",VPNORPROXYDETECTED:"Questo contenuto non può essere riprodotto con VPN o proxy.",UNKNOWN:"Questo media non è disponibile."};ah.addLanguage("it",n(n({},Vh),$h));const Hh={"Audio Player":"Audio-Player","Video Player":"Video-Player",Play:"Laschar ir",Pause:"Pausa",Replay:"Mussar danovamain","Current Time":"Temp actual",Duration:"Durada","Remaining Time":"Temp restant","Stream Type":"Tip dal stream",LIVE:"LIVE",Loaded:"Chargià",Progress:"Progress","Progress Bar":"Bar da progessiun","progress bar timing: currentTime={1} duration={2}":"{1} da {2}",Fullscreen:"Entir visur","Non-Fullscreen":"Betg entir visur",Mute:"Senza tun",Unmute:"Cun tun","Playback Rate":"Tempo ",Subtitles:"Suttitels","subtitles off":"senza suttitels",Captions:"Suttitels","captions off":"senza suttitels",Chapters:"Chapitels",Descriptions:"Descripziuns","descriptions off":"senza descripziuns","Audio Track":"Piese audio","Volume Level":"Nivel dal volumen","You aborted the media playback":"Vus avais interrut il vdieo","A network error caused the media download to fail part-way.":"In sbagl en la rait ha impedì il download","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Il video n'è betg chargià - ubain per in sbagl da server / da la rait, ubain ch'il format n'è betg cumpatibel.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Il video è interrut: Ubain ch'il video è donnegià, ubain che funcziuns n'èn betg cumpatiblas.","No compatible source was found for this media.":"Chattà nagina funtauna cumpatibla per quest video.","The media is encrypted and we do not have the keys to decrypt it.":"Il video è codifitgà da moda nunenconuschenta.","Play Video":"Aviar video",Close:"Serrar","Close Modal Dialog":"Serrar la fanestra modala","Modal Window":"Fanestra modala","This is a modal window":"Quai è ina fanestra modala","This modal can be closed by pressing the Escape key or activating the close button.":'Questa fanestra modala pudais serrar cun la tasta "Escape" ubain cun il buttun.',", opens captions settings dialog":", avra opziuns per ils suttitels",", opens subtitles settings dialog":", avra opziuns per ils suttitels",", opens descriptions settings dialog":", avra opziuns per la descripziun",", selected":", selecziunà","captions settings":"opziuns per ils suttitels","subtitles settings":"opziuns per ils suttitels","descriptions settings":"opziuns per la descripziun",Text:"Text",White:"Alv",Black:"Nair",Red:"Cotschn",Green:"Verd",Blue:"Blau",Yellow:"Mellen",Magenta:"Magenta",Cyan:"Cyan",Background:"Fund",Window:"Fanestra",Transparent:"Transparent","Semi-Transparent":"Mez transparent",Opaque:"Betg transparent","Font Size":"Grandezza dal text","Text Edge Style":"Stil dal text",None:"Nagin",Raised:"Auzà",Depressed:"Sbassà",Uniform:"Uniform",Dropshadow:"Sumbriva","Font Family":"Scrittira","Proportional Sans-Serif":"Proportionale Sans-Serif","Monospace Sans-Serif":"Monospace Sans-Serif","Proportional Serif":"Proportionale Serif","Monospace Serif":"Monospace Serif",Casual:"Casual",Script:"Script","Small Caps":"Bustabs pitschens",Reset:"Da nov","restore all settings to the default values":"Enavos tar las opziuns da standard",Done:"Fatg","Caption Settings Dialog":"Opziuns per suttitels","Beginning of dialog window. Escape will cancel and close the window.":"Entschatta da la fanestra da dialog. Escape stizza e serra la fanestra.","End of dialog window.":"Fin da la fanestra da dialog.",AGERATING12:"Per proteger uffants, è quest cuntegn disponibel mo tranter las 20.00 e las 06.00.",AGERATING18:"Per proteger uffants, è quest cuntegn disponibel mo tranter las 23.00 e las 05.00.",COMMERCIAL:"Quest medium commerzial n'è betg disponibel.",ENDDATE:"Quest cuntegn n'è betg pli disponibel.",GEOBLOCK:"Quest cuntegn n'è betg disponibel ordaifer la Svizra.",JOURNALISTIC:"Quest cuntegn na stat ad interim betg a disposiziun per motivs publicistics.",LEGAL:"Quest cuntegn n'è betg disponibel perquai ch'el è scadì.",STARTDATE:"Quest cuntegn n'è betg anc disponibel. Empruvai pli tard.",VPNORPROXYDETECTED:"Quest cuntegn na po betg vegnir reproducì cun VPN ni proxy activà.",UNKNOWN:"Quest cuntegn n'è betg disponibel."};ah.addLanguage("rm",n({},Hh));const zh=["url","mimeType","keySystems"],Wh=["src"];class Gh{static addBlockedSegments(e,t=[]){const i="srgssr-blocked-segments",s=e.textTracks().getTrackById(i);if(s&&e.textTracks().removeTrack(s),!Array.isArray(t)||!t.length)return;const r=t.filter(e=>e.blockReason);r.length&&Gh.createTextTrack(e,i).then(t=>{r.forEach(e=>{Gh.addTextTrackCue(t,e)}),e.textTracks().addTrack(t)})}static addRemoteTextTracks(e,t=[]){Array.isArray(t)&&t.forEach(({type:t,language:i,locale:s,url:r})=>{e.addRemoteTextTrack({kind:"SDH"===t?"captions":"subtitles",label:i,language:s,src:r})})}static addTextTrackCue(e,t){const i=(Number.isFinite(t.markIn)?t.markIn:t.fullLengthMarkIn)/1e3,s=(Number.isFinite(t.markOut)?t.markOut:t.fullLengthMarkOut)/1e3;e.addCue(new VTTCue(i,s,JSON.stringify(t)))}static addTextTracks(e,{mediaData:t}){Gh.addRemoteTextTracks(e,t.subtitles),Gh.addChapters(e,t.urn,t.chapters),Gh.addBlockedSegments(e,t.blockedSegments),Gh.addIntervals(e,t.intervals)}static addChapters(e,t,i=[]){const s="srgssr-chapters",r=e.textTracks().getTrackById(s);r&&e.textTracks().removeTrack(r),Array.isArray(i)&&i.length&&Gh.createTextTrack(e,s).then(s=>{i.forEach(e=>{t===e.fullLengthUrn&&Gh.addTextTrackCue(s,e)}),e.textTracks().addTrack(s)})}static addIntervals(e,t=[]){const i="srgssr-intervals",s=e.textTracks().getTrackById(i);s&&e.textTracks().removeTrack(s),Array.isArray(t)&&t.length&&Gh.createTextTrack(e,i).then(i=>{t.forEach(e=>{Gh.addTextTrackCue(i,e)}),e.textTracks().addTrack(i)})}static blockingReason(e,t){if(!t.mediaData.blockReason)return;const i=e.localize(t.mediaData.blockReason);return Gh.error(e,{code:MediaError.MEDIA_ERR_ABORTED,message:i,metadata:{errorType:t.mediaData.blockReason,src:t}}),!0}static composeAkamaiResources(){return i(function*(e=[]){return Th.hasToken(e)?Th.tokenizeSources(e):Promise.resolve(e)}).apply(this,arguments)}static composeKeySystemsResources(e=[]){if(!_h.hasDrm(e))return e;return e.map(e=>n(n({},e),_h.buildKeySystems(e.drmList)))}static composeMainResources(e){return Gh.composeAkamaiResources(Gh.composeKeySystemsResources(Gh.filterIncompatibleResources(e.getMainResources())))}static composeSrcMediaData({mediaData:e,disableTrackers:t},i){const s=ah.obj.merge(i,e),{url:r,mimeType:n,keySystems:o}=s;return{src:r,type:n,keySystems:o,disableTrackers:t,mediaData:a(s,zh)}}static createTextTrack(e,t){return new Promise(i=>{setTimeout(()=>{i(new ah.TextTrack({id:t,kind:"metadata",label:t,tech:e.tech(!0)}))},100)})}static cuechangeEventProxy(e){e.textTracks().on("addtrack",({track:t})=>{["srgssr-chapters","srgssr-intervals"].includes(t.id)&&t.on("cuechange",()=>{const[i]=Array.from(t.activeCues),s=t.id.includes("srgssr-chapters")?"srgssr/chapter":"srgssr/interval";e.trigger({type:s,data:i})})})}static dataProvider(e){if(!e.options().srgOptions.dataProvider){const{dataProviderHost:t,dataProviderUrlHandler:i}=e.options().srgOptions,s=new oh(t).handleRequest(i);e.options({srgOptions:{dataProvider:s}})}return e.options().srgOptions.dataProvider}static dataProviderError(e,t){if(!t)return;const i=t.statusText?t.statusText:t.message;return Gh.error(e,{code:0,message:e.localize("UNKNOWN"),metadata:{errorType:"UNKNOWN",urn:e.src(),status:t.status,statusText:i,url:t.url}}),!0}static error(e,{code:t,message:i,metadata:s}){e.error(null),e.error({code:t,message:i,metadata:s})}static filterIncompatibleResources(e=[]){return e.filter(e=>!["RTMP","HDS"].includes(e.streaming))}static getBlockedSegment(e){const t=e.textTracks().getTrackById("srgssr-blocked-segments");if(!t)return;const[i]=Array.from(t.activeCues);return i}static getBlockedSegmentByTime(e,t){const i=Gh.getBlockedSegment(e);if(!i)return;return t>=i.startTime&&t<i.endTime?i:void 0}static getMediaComposition(e){return i(function*(e,t=(new oh).handleRequest()){const i=yield t(e);return Object.assign(new Rh,i)}).apply(this,arguments)}static getMediaData(e=[]){if(Th.hasToken(e))return e[0];const t=ah.browser.IS_ANY_SAFARI?"HLS":"DASH";return e.find(({streaming:e})=>e===t)||e[0]}static getSrcMediaObj(e,t){return i(function*(){Gh.pillarboxMonitoring(e)&&Gh.pillarboxMonitoring(e).sessionStart();const{src:i}=t,s=a(t,Wh),r=yield Gh.getMediaComposition(i,Gh.dataProvider(e)),n=yield Gh.composeMainResources(r);let o=Gh.getMediaData(n);return o||(o={blockReason:r.getMainChapter().blockReason,imageUrl:r.getMainChapterImageUrl()}),Gh.composeSrcMediaData(s,o)})()}static handleCurrentTime(e,t){const i=Gh.getBlockedSegmentByTime(e,t);if(!i||!Number.isFinite(i.endTime))return t;const s=i.endTime+.1;return e.trigger({type:"srgssr/blocked-segment",data:i}),e.currentTime(s),s}static handleSetCurrentTime(e,t){const{endTime:i}=Gh.getBlockedSegmentByTime(e,t)||{};return Number.isFinite(i)?i:t}static handleSetSource(e,t,s){return i(function*(){try{const i=yield Gh.getSrcMediaObj(e,t);if(Gh.srgAnalytics(e),Gh.updateTitleBar(e,i),Gh.updatePoster(e,i),Gh.blockingReason(e,i))return;return Gh.addTextTracks(e,i),s(null,i)}catch(t){if(Gh.dataProviderError(e,t))return;return s(t)}})()}static srgAnalytics(e){if(!1!==e.options().trackers.srgAnalytics&&!e.options().trackers.srgAnalytics){const t=new Oh(e,{debug:e.debug(),playerVersion:ah.VERSION.pillarbox,tagCommanderScriptURL:e.options().srgOptions.tagCommanderScriptURL});e.options({trackers:{srgAnalytics:t}})}}static pillarboxMonitoring(e){if(!1!==e.options().trackers.pillarboxMonitoring){if(!e.options().trackers.pillarboxMonitoring){const t=new Mh(e,{debug:e.debug(),playerVersion:ah.VERSION.pillarbox,playerName:"Pillarbox"});e.options({trackers:{pillarboxMonitoring:t}})}return e.options().trackers.pillarboxMonitoring}}static updatePoster(e,t,i=fh){e.poster(i.scale({url:t.mediaData.imageUrl}))}static updateTitleBar(e,t){e.titleBar&&e.titleBar.update({title:t.mediaData.vendor,description:t.mediaData.title})}static middleware(e){return Gh.pillarboxMonitoring(e),Gh.cuechangeEventProxy(e),{currentTime:t=>Gh.handleCurrentTime(e,t),setCurrentTime:t=>Gh.handleSetCurrentTime(e,t),setSource:(t=i(function*(t,i){return Gh.handleSetSource(e,t,i)}),function(e,i){return t.apply(this,arguments)})};var t}}ah.use("srgssr/urn",Gh.middleware),ah.options.srgOptions={dataProvider:void 0,dataProviderHost:void 0,dataProviderUrlHandler:void 0,tagCommanderScriptURL:void 0},e.DataProvider=oh,e.MediaComposition=Rh,e.PillarboxMonitoring=Mh,e.Player=nh,e.SRGAnalytics=Oh,e.SrgSsr=Gh,e.default=ah,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),window.pillarbox=ah,window.videojs=window.pillarbox});
29
+ /*! @name videojs-contrib-eme @version 5.5.2 @license Apache-2.0 */;const Cc=(e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;const i=new DataView(e),s=new DataView(t);for(let e=0;e<i.byteLength;e++)if(i.getUint8(e)!==s.getUint8(e))return!1;return!0},Ic=e=>e instanceof Uint8Array||e instanceof Uint16Array?e.buffer:e,xc=(...e)=>{const t=Fo.obj||Fo;return(t.merge||t.mergeOptions).apply(t,e)},Ac=(...e)=>{const t=xc(...e);return Object.keys(t).forEach(e=>{null===t[e]&&delete t[e]}),t},Dc=e=>{const t=[];return Object.keys(e).forEach(i=>{const s=Vc(i,e[i])[0];t.push(s)}),t};let Pc=Fo.xhr.httpHandler;Pc||(Pc=(e,t)=>(i,s,r)=>{if(i)e(i);else{if(s.statusCode>=400&&s.statusCode<=599){let i=r;return t&&(i=String.fromCharCode.apply(null,new Uint8Array(r))),void e({cause:i})}e(null,r)}});const Lc=(e,t,i,s,r)=>{const n=(e=>{const t=String.fromCharCode.apply(null,new Uint16Array(e)),i=(new p.DOMParser).parseFromString(t,"application/xml"),s=i.getElementsByTagName("HttpHeaders")[0];let r={};if(s){const e=s.getElementsByTagName("name"),t=s.getElementsByTagName("value");for(let i=0;i<e.length;i++)r[e[i].childNodes[0].nodeValue]=t[i].childNodes[0].nodeValue}const n=i.getElementsByTagName("Challenge")[0];let a;return n&&(a=p.atob(n.childNodes[0].nodeValue)),i.querySelector("parsererror")&&(r={"Content-Type":"text/xml; charset=utf-8",SOAPAction:'"http://schemas.microsoft.com/DRM/2007/03/protocols/AcquireLicense"'},a=e),{headers:r,message:a}})(i),a=n.message,o=Ac(n.headers,s.emeHeaders,t.licenseHeaders);Fo.xhr({uri:t.url,method:"post",headers:o,body:a,responseType:"arraybuffer",requestType:"license",metadata:{keySystem:e}},Pc(r,!0))},Oc={EMEFailedToRequestMediaKeySystemAccess:"eme-failed-request-media-key-system-access",EMEFailedToCreateMediaKeys:"eme-failed-create-media-keys",EMEFailedToAttachMediaKeysToVideoElement:"eme-failed-attach-media-keys-to-video",EMEFailedToCreateMediaKeySession:"eme-failed-create-media-key-session",EMEFailedToSetServerCertificate:"eme-failed-set-server-certificate",EMEFailedToGenerateLicenseRequest:"eme-failed-generate-license-request",EMEFailedToUpdateSessionWithReceivedLicenseKeys:"eme-failed-update-session",EMEFailedToCloseSession:"eme-failed-close-session",EMEFailedToRemoveKeysFromSession:"eme-failed-remove-keys",EMEFailedToLoadSessionBySessionId:"eme-failed-load-session"},Mc="com.apple.fps.1_0",Rc=({initData:e,id:t,cert:i})=>{"string"==typeof t&&(t=(e=>{const t=new ArrayBuffer(2*e.length),i=new Uint16Array(t);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t);return i})(t));let s=0;const r=new ArrayBuffer(e.byteLength+4+t.byteLength+4+i.byteLength),n=new DataView(r);new Uint8Array(r,s,e.byteLength).set(e),s+=e.byteLength,n.setUint32(s,t.byteLength,!0),s+=4;const a=new Uint16Array(r,s,t.length);a.set(t),s+=a.byteLength,n.setUint32(s,i.byteLength,!0),s+=4;return new Uint8Array(r,s,i.byteLength).set(i),new Uint8Array(r,0,r.byteLength)},Nc=(e,t)=>(i,s)=>{const r=Ac(i.emeHeaders,t.certificateHeaders);Fo.xhr({uri:t.certificateUri,responseType:"arraybuffer",requestType:"license",metadata:{keySystem:e},headers:r},Pc((e,t)=>{e?s(e):s(null,new Uint8Array(t))}))},Uc=(e,t)=>(e=>{const t=_.createElement("a");return t.href=e,t.hostname})(t),Bc=(e,t)=>(i,s,r,n)=>{const a=Ac({"Content-type":"application/octet-stream"},i.emeHeaders,t.licenseHeaders);Fo.xhr({uri:t.licenseUri||t.url,method:"POST",responseType:"arraybuffer",requestType:"license",metadata:{keySystem:e,contentId:s},body:r,headers:a},Pc(n,!0))},Fc=({video:e,initData:t,options:i,eventBus:s,emeError:r})=>{const n=i.keySystems[Mc],a=n.getCertificate||Nc(Mc,n),o=n.getContentId||Uc,l=n.getLicense||Bc(Mc,n);return new Promise((e,t)=>{a(i,(i,s)=>{if(i){return r(i,{errorType:Oc.EMEFailedToSetServerCertificate,keySystem:Mc}),void t(i)}e(s)})}).then(n=>{return(({video:e,contentId:t,initData:i,cert:s,options:r,getLicense:n,eventBus:a,emeError:o})=>new Promise((l,d)=>{if(!e.webkitKeys)try{e.webkitSetMediaKeys(new p.WebKitMediaKeys(Mc))}catch(e){return o(e,{errorType:Oc.EMEFailedToCreateMediaKeys,keySystem:Mc}),void d("Could not create MediaKeys")}let u;try{u=e.webkitKeys.createSession("video/mp4",Rc({id:t,initData:i,cert:s}))}catch(e){return o(e,{errorType:Oc.EMEFailedToCreateMediaKeySession,keySystem:Mc}),void d("Could not create key session")}jc(a,{type:"keysessioncreated",keySession:u}),u.contentId=t,u.addEventListener("webkitkeymessage",e=>{jc(a,{type:"keymessage",messageEvent:e}),n(r,t,e.message,(e,t)=>{if(a&&jc(a,{type:"licenserequestattempted"}),e)return o(e,{errortype:Oc.EMEFailedToGenerateLicenseRequest,keySystem:Mc}),void d(e);u.update(new Uint8Array(t)),jc(a,{type:"keysessionupdated",keySession:u})})}),u.addEventListener("webkitkeyadded",()=>{l()}),u.addEventListener("webkitkeyerror",()=>{const e=u.error;o(e,{errorType:Oc.EMEFailedToUpdateSessionWithReceivedLicenseKeys,keySystem:Mc}),d(`KeySession error: code ${e.code}, systemCode ${e.systemCode}`)})}))({video:e,cert:n,initData:t,getLicense:l,options:i,contentId:o(i,(a=t,String.fromCharCode.apply(null,new Uint16Array(a.buffer||a)))),eventBus:s,emeError:r});var a})},qc=e=>e.startsWith("com.apple.fps"),jc=(e,t)=>{e.isDisposed()||e.trigger(G({},t))},Vc=(e,t)=>{if(t.supportedConfigurations)return t.supportedConfigurations;const i=qc(e),s={},r=t.initDataTypes||(i?["sinf"]:null),n=t.audioContentType,a=t.audioRobustness,o=t.videoContentType||(i?"video/mp4":null),l=t.videoRobustness,d=t.persistentState;return(n||a)&&(s.audioCapabilities=[G({},n?{contentType:n}:{},a?{robustness:a}:{})]),(o||l)&&(s.videoCapabilities=[G({},o?{contentType:o}:{},l?{robustness:l}:{})]),d&&(s.persistentState=d),r&&(s.initDataTypes=r),[s]},$c=(e,t)=>{const{mediaKeys:i,initDataType:s,initData:r,options:n,getLicense:a,removeSession:o,eventBus:l,contentId:d,emeError:u,keySystem:c}=t;let h,p=0;e.on("pause",()=>{n.limitRenewalsMaxPauseDuration&&"number"==typeof n.limitRenewalsMaxPauseDuration&&(h=setInterval(()=>{p++,p>=n.limitRenewalsMaxPauseDuration&&clearInterval(h)},1e3),e.on("play",()=>{clearInterval(h),p=0}))});try{const t=i.createSession(),h=()=>{Fo.log.debug("Session expired, closing the session."),t.close().then(()=>{l.isDisposed()||(jc(l,{type:"keysessionclosed",keySession:t}),o(r))}).catch(e=>{u(e,{errorType:Oc.EMEFailedToCloseSession,keySystem:c})})};return jc(l,{type:"keysessioncreated",keySession:t}),e.on("dispose",()=>{h()}),new Promise((i,o)=>{t.addEventListener("message",s=>{if(jc(l,{type:"keymessage",messageEvent:s}),"license-request"===s.messageType||"license-renewal"===s.messageType){if("license-renewal"===s.messageType){const t=n.limitRenewalsBeforePlay,i=n.limitRenewalsMaxPauseDuration,s="number"==typeof i,r=!e.hasStarted()&&t,a=e.paused()&&s&&p>=i,o=e.ended();if(r||a||o)return void h()}a(n,s.message,d).then(e=>{i(t.update(e).then(()=>{jc(l,{type:"keysessionupdated",keySession:t})}).catch(e=>{u(e,{errorType:Oc.EMEFailedToUpdateSessionWithReceivedLicenseKeys,keySystem:c})}))}).catch(e=>{o(e)})}},!1);const m="keystatuseschange";t.addEventListener(m,e=>{let i=!1;l.isDisposed()||(jc(l,{type:m,keyStatuses:t.keyStatuses}),t.keyStatuses.forEach((s,r)=>{switch(jc(l,{keyId:r,status:s,target:t,type:"keystatuschange"}),s){case"expired":i=!0;break;case"internal-error":const t='Key status reported as "internal-error." Leaving the session open since we don\'t have enough details to know if this error is fatal.';Fo.log.warn(t,e)}}),i&&h())},!1),t.generateRequest(s,r).catch(e=>{u(e,{errorType:Oc.EMEFailedToGenerateLicenseRequest,keySystem:c}),o("Unable to create or initialize key session")})})}catch(e){u(e,{errorType:Oc.EMEFailedToCreateMediaKeySession,keySystem:c})}},Hc=(e,t)=>{if("string"==typeof t&&(t={url:t}),!t.url&&t.licenseUri&&(t.url=t.licenseUri),!t.url&&!t.getLicense)throw new Error(`Missing url/licenseUri or getLicense in ${e} keySystem configuration.`);const i=qc(e);if(i&&t.certificateUri&&!t.getCertificate&&(t.getCertificate=Nc(e,t)),i&&!t.getCertificate)throw new Error(`Missing getCertificate or certificateUri in ${e} keySystem configuration.`);return i&&!t.getContentId&&(t.getContentId=Uc),t.url&&!t.getLicense&&(t.getLicense="com.microsoft.playready"===e?((e,t)=>(i,s,r)=>{Lc(e,t,s,i,r)})(e,t):i?Bc(e,t):((e,t)=>(i,s,r)=>{const n=Ac({"Content-type":"application/octet-stream"},i.emeHeaders,t.licenseHeaders);Fo.xhr({uri:t.url,method:"POST",responseType:"arraybuffer",requestType:"license",metadata:{keySystem:e},body:s,headers:n},Pc(r,!0))})(e,t)),t},zc=({player:e,video:t,initDataType:i,initData:s,keySystemAccess:r,options:n,removeSession:a,eventBus:o,emeError:l})=>{let d=Promise.resolve();const u=r.keySystem;let c;try{c=Hc(u,n.keySystems[u])}catch(e){return Promise.reject(e)}const h=c.getContentId?c.getContentId(n,(p=s,String.fromCharCode.apply(null,new Uint8Array(p.buffer||p)))):null;var p;if(void 0===t.mediaKeysObject){let i;t.mediaKeysObject=null,t.pendingSessionData=[],d=new Promise((e,s)=>{t.keySystem=u,c.getCertificate?c.getCertificate(n,(t,r)=>{t?s(t):(i=r,e())}):e(r)}).then(()=>r.createMediaKeys()).then(s=>(jc(o,{type:"keysystemaccesscomplete",mediaKeys:s}),(({player:e,video:t,certificate:i,createdMediaKeys:s,emeError:r})=>{t.mediaKeysObject=s;const n=[];i&&n.push(s.setServerCertificate(i).catch(e=>{const i={errorType:Oc.EMEFailedToSetServerCertificate,keySystem:t.keySystem};r(e,i)}));for(let i=0;i<t.pendingSessionData.length;i++){const s=t.pendingSessionData[i];n.push($c(e,{mediaKeys:t.mediaKeysObject,initDataType:s.initDataType,initData:s.initData,options:s.options,getLicense:s.getLicense,removeSession:s.removeSession,eventBus:s.eventBus,contentId:s.contentId,emeError:s.emeError,keySystem:t.keySystem}))}return t.pendingSessionData=[],n.push(t.setMediaKeys(s).catch(e=>{const i={errorType:Oc.EMEFailedToAttachMediaKeysToVideoElement,keySystem:t.keySystem};r(e,i)})),Promise.all(n)})({player:e,video:t,certificate:i,createdMediaKeys:s,emeError:l}))).catch(e=>(l(e,{errorType:Oc.EMEFailedToCreateMediaKeys,keySystem:u}),e?Promise.reject(e):Promise.reject("Failed to create and initialize a MediaKeys object")))}return d.then(()=>{const r=t.keySystem?((e,t,i)=>(s,r,n)=>new Promise((a,o)=>{const l=function(e,t){i&&jc(i,{type:"licenserequestattempted"}),e?o(e):a(t)};qc(e)?t(s,n,new Uint8Array(r),l):t(s,r,l)}))(u,c.getLicense,o):null;return(({player:e,video:t,initDataType:i,initData:s,options:r,getLicense:n,contentId:a,removeSession:o,eventBus:l,emeError:d})=>{const u={initDataType:i,initData:s,options:r,getLicense:n,removeSession:o,eventBus:l,contentId:a,emeError:d,keySystem:t.keySystem};return t.mediaKeysObject?(u.mediaKeys=t.mediaKeysObject,$c(e,u)):(t.pendingSessionData.push(u),Promise.resolve())})({player:e,video:t,initDataType:i,initData:s,options:n,getLicense:r,contentId:h,removeSession:a,eventBus:o,emeError:l})})},Wc="com.microsoft.playready",Gc=(e,t,i,s,r)=>{const n=e.msKeys.createSession("video/mp4",t);if(!n){const e=new Error("Could not create key session.");throw r(e,{errorType:Oc.EMEFailedToCreateMediaKeySession,keySystem:Wc}),e}jc(s,{type:"keysessioncreated",keySession:n}),n.addEventListener("mskeymessage",e=>{jc(s,{type:"keymessage",messageEvent:e}),((e,t,i,s,r)=>{let n=e.keySystems[Wc];if("function"==typeof n.getKey)return void n.getKey(e,i.destinationURL,i.message.buffer,(i,n)=>{if(i){const n={errorType:Oc.EMEFailedToRequestMediaKeySystemAccess,config:Dc(e.keySystems)};return r(i,n),void jc(s,{message:"Unable to get key: "+i,target:t,type:"mskeyerror"})}t.update(n),jc(s,{type:"keysessionupdated",keySession:t})});"string"==typeof n?n={url:n}:"boolean"==typeof n&&(n={}),n.url||(n.url=i.destinationURL);const a=(e,i)=>{if(s&&jc(s,{type:"licenserequestattempted"}),e)return r(e,{errorType:Oc.EMEFailedToGenerateLicenseRequest,keySystem:Wc}),void jc(s,{message:"Unable to request key from url: "+n.url,target:t,type:"mskeyerror"});t.update(new Uint8Array(i))};n.getLicense?n.getLicense(e,i.message.buffer,a):Lc(Wc,n,i.message.buffer,e,a)})(i,n,e,s,r)}),n.addEventListener("mskeyerror",e=>{const t={errorType:Oc.EMEFailedToCreateMediaKeySession,keySystem:Wc};r(n.error,t),jc(s,{message:`Unexpected key error from key session with code: ${n.error.code} and systemCode: ${n.error.systemCode}`,target:n,type:"mskeyerror"})}),n.addEventListener("mskeyadded",()=>{jc(s,{target:n,type:"mskeyadded"})})};const Xc=[{initDataTypes:["cenc"],audioCapabilities:[{contentType:'audio/mp4;codecs="mp4a.40.2"'}],videoCapabilities:[{contentType:'video/mp4;codecs="avc1.42E01E"'}]}],Kc=[{keySystem:"com.apple.fps",supportedConfig:[{initDataTypes:["sinf"],videoCapabilities:[{contentType:"video/mp4"}]}]},{keySystem:"com.microsoft.playready.recommendation",supportedConfig:Xc},{keySystem:"com.widevine.alpha",supportedConfig:Xc},{keySystem:"org.w3.clearkey",supportedConfig:Xc}],Yc=()=>{const e=p.Promise,t={fairplay:Boolean(p.WebKitMediaKeys),playready:!1,widevine:!1,clearkey:!1};return p.MediaKeys&&p.navigator.requestMediaKeySystemAccess?e.all(Kc.map(({keySystem:e,supportedConfig:t})=>p.navigator.requestMediaKeySystemAccess(e,t).catch(()=>{}))).then(([e,i,s,r])=>(t.fairplay=Boolean(e),t.playready=Boolean(i),t.widevine=Boolean(s),t.clearkey=Boolean(r),t)):e.resolve(t)};const Qc=(e,t)=>{for(let i=0;i<e.length;i++)if(e[i].initData===t)return void e.splice(i,1)};function Jc(e,t,i,s,r,n){if(!i||!i.keySystems)return Promise.resolve();if(i.keySystems[Mc]&&p.WebKitMediaKeys&&e.eme.legacyFairplayIsUsed)return Fo.log.debug("eme",`Ignoring 'encrypted' event, using legacy fairplay keySystem ${Mc}`),Promise.resolve();let a=t.initData;return(e=>{let t;return Object.keys(e).forEach(i=>{const s=Vc(i,e[i]);t=t?t.catch(e=>p.navigator.requestMediaKeySystemAccess(i,s)):p.navigator.requestMediaKeySystemAccess(i,s)}),t})(i.keySystems).then(o=>{const l=o.keySystem;return i.keySystems[l]&&i.keySystems[l].pssh&&(a=i.keySystems[l].pssh),((e,t)=>{for(let i=0;i<e.length;i++){if(!e[i].initData)continue;const s=Ic(e[i].initData),r=Ic(t);if(Cc(s,r))return!0}return!1})(s,a)||!a?Promise.resolve():(s.push({initData:a}),zc({player:e,video:t.target,initDataType:t.initDataType,initData:a,keySystemAccess:o,options:i,removeSession:Qc.bind(null,s),eventBus:r,emeError:n}))}).catch(e=>{const t={errorType:Oc.EMEFailedToRequestMediaKeySystemAccess,config:Dc(i.keySystems)};n(e,t)})}const Zc=(e,t,i,s,r)=>{if(!t.keySystems||!t.keySystems[Wc])return;if(i.reduce((e,t)=>e||t.playready,!1))return;let n=e.initData;t.keySystems[Wc]&&t.keySystems[Wc].pssh&&(n=t.keySystems[Wc].pssh),n&&(i.push({playready:!0,initData:n}),(({video:e,initData:t,options:i,eventBus:s,emeError:r})=>{e.msKeys&&delete e.msKeys;try{e.msSetMediaKeys(new p.MSMediaKeys(Wc))}catch(e){throw r(e,{errorType:Oc.EMEFailedToCreateMediaKeys,keySystem:Wc}),new Error("Unable to create media keys for PlayReady key system. Error: "+e.message)}Gc(e,t,i,s,r)})({video:e.target,initData:n,options:t,eventBus:s,emeError:r}))},eh=e=>xc(e.currentSource(),e.eme.options),th=e=>{const t=e.src();t!==e.eme.activeSrc&&(e.eme.activeSrc=t,e.eme.sessions=[])},ih=(e,t)=>{if("video"===e.$(".vjs-tech").tagName.toLowerCase())if(th(e),p.MediaKeys){const i=()=>{const i={initDataType:"cenc",initData:null,target:e.tech_.el_};th(e),Jc(e,i,eh(e),e.eme.sessions,e.tech_,t)};if(Fo.browser.IS_FIREFOX){let t;e.on("ended",()=>{t=!1,e.one(["seek","play"],s=>{t||0!==e.eme.sessions.length||(i(),t=!0)})}),e.on("play",()=>{const s=e.eme.options.limitRenewalsMaxPauseDuration;0===e.eme.sessions.length&&"number"==typeof s&&(t=!0,i())})}e.tech_.el_.addEventListener("encrypted",i=>{Fo.log.debug("eme","Received an 'encrypted' event"),th(e),Jc(e,i,eh(e),e.eme.sessions,e.tech_,t)})}else if(p.WebKitMediaKeys)e.eme.initLegacyFairplay();else if(p.MSMediaKeys){e.tech_.el_.addEventListener("msneedkey",i=>{Fo.log.debug("eme","Received an 'msneedkey' event"),th(e);try{Zc(i,eh(e),e.eme.sessions,e.tech_,t)}catch(e){t(e)}});const i=e=>{t(e)};e.tech_.on("mskeyerror",i),e.on("dispose",()=>{e.tech_.off("mskeyerror",i)})}},sh=function(e={}){const t=this,i=(e=>(t,i)=>{const s={code:5};"string"==typeof t?s.message=t:t&&(t.message&&(s.message=t.message),t.cause&&(t.cause.length||t.cause.byteLength)&&(s.cause=t.cause),t.keySystem&&(s.keySystem=t.keySystem),s.originalError=t),i&&(s.metadata=i),e.error(s)})(t);t.ready(()=>ih(t,i)),t.eme={setupEmeListeners(){ih(t,i)},initializeMediaKeys(s={},r=function(){},n=!1){const a=xc(t.currentSource(),e,s),o={initDataType:"cenc",initData:null,target:t.tech_.el_};if(th(t),p.MediaKeys)Jc(t,o,a,t.eme.sessions,t.tech_,i).then(()=>r()).catch(e=>{r(e),n||i(e)});else if(p.MSMediaKeys){const e=s=>{t.tech_.off("mskeyadded",e),t.tech_.off("mskeyerror",e),"mskeyerror"===s.type?(r(s.target.error),n||i(s.message)):r()};t.tech_.one("mskeyadded",e),t.tech_.one("mskeyerror",e);try{Zc(o,a,t.eme.sessions,t.tech_,i)}catch(s){t.tech_.off("mskeyadded",e),t.tech_.off("mskeyerror",e),r(s),n||i(s)}}},initLegacyFairplay(){const e=e=>{Fo.log.debug("eme","Received a 'webkitneedkey' event"),th(t),((e,t,i,s)=>t.keySystems&&t.keySystems[Mc]&&e.initData?Fc({video:e.target,initData:e.initData,options:t,eventBus:i,emeError:s}):Promise.resolve())(e,eh(t),t.tech_,i).catch(e=>{i(e)})},s=i=>{const s=eh(t).firstWebkitneedkeyTimeout||1e3,r=t.src();t.eme.webkitneedkey_=t.eme.webkitneedkey_||{},t.eme.webkitneedkey_.src!==r&&(t.eme.webkitneedkey_={handledFirstEvent:!1,src:r}),t.eme.webkitneedkey_.handledFirstEvent?e(i):(t.clearTimeout(t.eme.webkitneedkey_.timeout),t.eme.webkitneedkey_.timeout=t.setTimeout(()=>{t.eme.webkitneedkey_.handledFirstEvent=!0,t.eme.webkitneedkey_.timeout=null,e(i)},s))};t.eme.legacyFairplayIsUsed=!0;let r=t.tech_.el_;r.addEventListener("webkitneedkey",s);const n=()=>{t.off("dispose",n),null!==r&&r.removeEventListener("webkitneedkey",s),t.eme.legacyFairplayIsUsed=!1,r=null};return t.on("dispose",n),n},detectSupportedCDMs:Yc,legacyFairplayIsUsed:!1,options:e}};Fo.registerPlugin("eme",sh),sh.Error=Oc,sh.VERSION="5.5.2";const rh=Fo.getComponent("player");class nh extends rh{constructor(e,t,i){super(e,t=Fo.obj.merge(t,{plugins:{eme:!0}}),i)}audioTrack(e){const t=Array.from(this.player().audioTracks());if(!e)return t.find(e=>e.enabled);const{kind:i,language:s}=e,r=t.find(e=>e.language===s&&e.kind===i)||t.find(e=>e.language===s);return r&&(r.enabled=!0),r}bufferedRanges(){const e=[];for(let t=0;t<this.buffered().length;t++){const i=this.buffered().start(t),s=this.buffered().end(t);e.push({start:i,end:s})}return e}playedPercent(){if(!Number.isFinite(this.duration()))return NaN;let e=0;for(let t=0;t!=this.played().length;t++)e+=this.played().end(t)-this.played().start(t);return e/this.duration()}playedRanges(){const e=[];for(let t=0;t<this.played().length;t++){const i=this.played().start(t),s=this.played().end(t);e.push({start:i,end:s})}return e}seekableRanges(){const e=[];for(let t=0;t<this.seekable().length;t++){const i=this.seekable().start(t),s=this.seekable().end(t);e.push({start:i,end:s})}return e}textTrack(e){const t=Array.from(this.player().textTracks()).filter(e=>!["chapters","metadata"].includes(e.kind));if(!e)return t.find(e=>"showing"===e.mode);t.forEach(e=>e.mode="disabled");const{kind:i,language:s}=e;return t.find(e=>(e.language===s&&e.kind===i&&(e.mode="showing"),"showing"===e.mode))||t.find(e=>(e.language===s&&(e.mode="showing"),"showing"===e.mode))}}Fo.registerComponent("player",nh);const ah=Fo;ah.VERSION={pillarbox:"1.25.0",videojs:Fo.VERSION,[Fo.VhsSourceHandler.name]:Fo.VhsSourceHandler.VERSION,eme:Fo.getPlugin("eme").VERSION},ah.options.enableSmoothSeeking=!0,ah.options.fill=!0,ah.options.html5={vhs:{useForcedSubtitles:!0}},ah.options.liveTracker={trackingThreshold:120,liveTolerance:15},ah.options.liveui=!0,ah.options.playsinline=!0,ah.options.responsive=!0,ah.options.trackers={};class oh{constructor(e="il.srgssr.ch"){this.setIlHost(e)}setIlHost(e){this.baseUrl=`${e}/integrationlayer/2.1/`}handleRequest(e){var t=this;return function(){var s=i(function*(i){const s="function"==typeof e?e(i):t.mediaCompositionUrlHandler(i),r=yield fetch(s);if(!r.ok)throw r;return yield r.json()});return function(e){return s.apply(this,arguments)}}()}mediaCompositionUrlHandler(e){return`https://${this.baseUrl}mediaComposition/byUrn/${e}?onlyChapters=true&vector=portalplay`}}const lh="240",dh="320",uh="480",ch="960",hh="1920",ph="jpg",mh="webp",gh="png";class fh{static scale({url:e,width:t=ch,format:i=ph}={},s="https://il.srgssr.ch/images/"){if(!e)return;const r=new URL(s);return r.searchParams.set("imageUrl",e),r.searchParams.set("format",i),r.searchParams.set("width",t),decodeURIComponent(r.href)}static get JPG(){return ph}static get PNG(){return gh}static get WEBP(){return mh}static get WIDTH_240(){return lh}static get WIDTH_320(){return dh}static get WIDTH_480(){return uh}static get WIDTH_960(){return ch}static get WIDTH_1920(){return hh}}const yh={WIDEVINE:"com.widevine.alpha",FAIRPLAY:"com.apple.fps.1_0",PLAYREADY:"com.microsoft.playready"};class _h{static buildKeySystems(e=[]){const t={};return e.forEach(e=>{const i=_h.vendors[e.type];if(_h.vendors.FAIRPLAY===i){const{certificateUrl:s,licenseUrl:r}=e;t[i]={certificateUri:s,licenseUri:r}}else t[i]=e.licenseUrl}),{keySystems:t}}static hasDrm(e){return e.some(({drmList:e})=>e&&e.length>0)}static get vendors(){return yh}}const bh="AKAMAI",vh="NONE";class Th{static aclPath(e){const t=e.pathname;return`${t.substring(0,t.lastIndexOf("/")+1)}*`}static get AKAMAI(){return bh}static hasToken(e){return e.some(e=>Th.isAkamai(e.tokenType))}static isAkamai(e){return bh===e}static isNone(e){return vh===e}static get NONE(){return vh}static tokenize(e,t){const i=new URL(`${e.url}`),s=Th.aclPath(i),r=`${t}${encodeURIComponent(s)}`;return fetch(r).then(e=>e.ok?e.json():Promise.reject({status:e.status,statusText:e.statusText})).then(({token:{authparams:t}})=>(new URLSearchParams(t).forEach((e,t)=>i.searchParams.set(t,e)),Object.assign({},e,{url:i.toString()}))).catch(e=>Promise.reject(e))}static tokenizeSources(e,t="https://tp.srgssr.ch/akahd/token?acl="){const i=[];return e.forEach(e=>{const s=Th.tokenize(e,t);i.push(s)}),Promise.all(i).then(e=>e).catch(e=>Promise.reject(e))}}const Sh="emptied",Eh="ended",wh="loadeddata",kh="loadstart",Ch="pause",Ih="play",xh="playing",Ah="ratechange",Dh="seeking",Ph="timeupdate",Lh="waiting";class Oh{constructor(e,{debug:t=!1,environment:i="prod",playerVersion:s="none",tagCommanderScriptURL:r="//colibri-js.akamaized.net/penguin/tc_SRGGD_11.js"}={}){this.isDebugEnabled=t,this.elapsedPlaybackTime=0,this.environment=i,this.hasStarted=!1,this.heartBeatIntervalId=void 0,this.initialized=!1,this.isSeeking=!1,this.isWaiting=!1,this.mediaSession=0,this.pendingQueue=[],this.pendingTagCommanderReload=!1,this.player=e,this.playerVersion=s,this.srcMediaData=void 0,this.startPlaybackSession=0,this.tagCommanderScriptURL=r,this.trackedCurrentTime=0,this.uptimeIntervalId=void 0,this.initScript(),this.initListeners()}beforeunload(){this.notify("stop")}clearTimers(){clearInterval(this.heartBeatIntervalId),clearInterval(this.uptimeIntervalId),clearTimeout(this.uptimeTimeoutId)}currentTime(){return Math.round(this.trackedCurrentTime)}debug(e){if(void 0===e)return this.isDebugEnabled||this.player.debug();this.isDebugEnabled=Boolean(e)}destroy(){this.clearTimers(),window.tc_vars||(window.tc_vars={}),this.elapsedPlaybackTime=0,this.hasStarted=!1,this.heartBeatIntervalId=void 0,this.initialized=!1,this.isWaiting=!1,this.mediaSession=0,this.pendingQueue=[],this.srcMediaData=void 0,this.startPlaybackSession=0,this.trackedCurrentTime=0,this.uptimeIntervalId=void 0}dispose(){this.beforeunload(),this.clearTimers(),window.removeEventListener("beforeunload",this.beforeunloadListener),this.player.off(Sh,this.emptiedListener),this.player.off(Eh,this.endedListener),this.player.off(kh,this.loadstartListener),this.player.off(wh,this.loadeddataListener),this.player.off(xh,this.playListener),this.player.off(Ch,this.pauseListener),this.player.off(Ah,this.rateChangeListener),this.player.off(Dh,this.seekingListener),this.player.off(Ph,this.timeUpdateListener),this.player.off(Lh,this.waitingListener)}emptied(){this.player.ended()||this.notify("stop")}ended(){this.notify("eof"),this.mediaSession=0,this.clearTimers()}flush(){this.isTrackerDisabled()||(this.pendingTagCommanderReload&&window.tC&&(window.tC.container.reload(),this.pendingTagCommanderReload=!1),window.tc_events_11&&this.pendingQueue.length>0&&(this.pendingQueue.forEach(e=>{window.tc_events_11(this.player.el(),e.action,e.labels)}),this.pendingQueue=[]))}getCurrentAudioTrack(){const e=Array.from(this.player.audioTracks()).find(e=>e.enabled);let t="und";return e&&e.language&&(t=e.language),e?t.toUpperCase():""}getCurrentTextTrack(){const e=this.player.textTrack();let t="und";return e&&e.language&&(t=e.language),e?t.toUpperCase():""}getDvrWindowPosition(){const{liveTracker:e}=this.player,t=this.currentTime()-e.seekableStart()|0,i=e.liveWindow()-t;return i<0||i===1/0?0:1e3*i}getDvrWindowSize(){const e=this.player.liveTracker.liveWindow()===1/0,t=1e3*this.player.liveTracker.liveWindow();return e?0:t}getElapsedPlaybackTime(){return this.startPlaybackSession?this.getElapsedPlayingTime():this.elapsedPlaybackTime}getElapsedPlayingTime(){const e=Oh.now()-this.startPlaybackSession|0;return this.elapsedPlaybackTime+e}getEventLabels(e){const t={event_id:e,event_timestamp:Oh.now(),media_dvr_window_length:0,media_dvr_window_offset:0,media_is_dvr:!1,media_is_live:!1,media_mute:this.player.muted()?"1":"0",media_playback_rate:this.player.playbackRate(),media_position:this.currentTime(),media_quality:this.srcMediaData.mediaData.quality,media_subtitles_on:this.isTextTrackEnabled(),media_volume:(100*this.player.volume()).toFixed(0),navigation_environment:this.environment};return this.isAudioTrackEnabled()&&(t.media_audio_track=this.getCurrentAudioTrack(),t.media_audiodescription_on=this.isAudioDescriptionEnabled()),this.isTextTrackEnabled()&&(t.media_subtitle_selection=this.getCurrentTextTrack()),this.isMediaOnDemand()||(t.media_is_live=!0,t.media_position=this.getElapsedPlaybackTime()),this.isMediaDvr()&&(t.media_dvr_window_offset=0|this.getDvrWindowPosition(),t.media_dvr_window_length=0|this.getDvrWindowSize(),t.media_is_dvr=!0,t.media_timeshift=[Ih,Ch].includes(e)?this.timeShifted():0),t}getInternalLabels(){const e={media_bu_distributer:this.srcMediaData.mediaData.vendor,media_chromecast_selected:Boolean(this.player.tech(!0).isCasting),media_embedding_url:document.referrer,media_player_display:"default",media_player_name:"pillarbox-web",media_player_version:this.playerVersion,media_url:this.srcMediaData.src},t=this.srcMediaData.mediaData.analyticsMetadata||{};window.tc_vars=Object.assign({},window.tc_vars,e,t)}heartBeat(){this.heartBeatIntervalId=setInterval(()=>{this.player.paused()||this.notify("pos")},3e4)}initCallbacks(){this.beforeunloadListener=this.beforeunload.bind(this),this.emptiedListener=this.emptied.bind(this),this.endedListener=this.ended.bind(this),this.loadstartListener=this.loadstart.bind(this),this.loadeddataListener=this.loadeddata.bind(this),this.playListener=this.play.bind(this),this.pauseListener=this.pause.bind(this),this.rateChangeListener=this.rateChange.bind(this),this.seekingListener=this.seeking.bind(this),this.timeUpdateListener=this.timeUpdate.bind(this),this.waitingListener=this.waiting.bind(this)}initListeners(){this.initCallbacks(),window.addEventListener("beforeunload",this.beforeunloadListener),this.player.on(Sh,this.emptiedListener),this.player.on(Eh,this.endedListener),this.player.on(kh,this.loadstartListener),this.player.on(wh,this.loadeddataListener),this.player.on(xh,this.playListener),this.player.on(Ch,this.pauseListener),this.player.on(Ah,this.rateChangeListener),this.player.on(Dh,this.seekingListener),this.player.on(Ph,this.timeUpdateListener),this.player.on(Lh,this.waitingListener),this.player.one("dispose",this.dispose.bind(this))}initScript(){const e="tc_script__11";if(!document.querySelector(`#${e}`)){const t=document.createElement("script"),i=this.tagCommanderScriptURL;t.defer=!0,t.id=e,t.src=i,t.type="text/javascript",t.onload=e=>{this.flush()},document.body.appendChild(t)}}isAudioDescriptionEnabled(){const e=Array.from(this.player.audioTracks()).find(e=>e.enabled&&e.kind.includes("desc"));return Boolean(e)}isAudioTrackEnabled(){return!!this.getCurrentAudioTrack()}isMediaDvr(){const{trackingThreshold:e}=this.player.liveTracker.options();return!this.isMediaOnDemand()&&e<this.player.liveTracker.liveWindow()}isMediaLive(){const{trackingThreshold:e}=this.player.liveTracker.options();return!this.isMediaOnDemand()&&e>this.player.liveTracker.liveWindow()}isMediaOnDemand(){return Number.isFinite(this.player.duration())}isTextTrackEnabled(){return!!this.getCurrentTextTrack()}isTrackerDisabled(){return!this.srcMediaData||!this.srcMediaData.mediaData||(Array.isArray(this.srcMediaData.disableTrackers)?Boolean(this.srcMediaData.disableTrackers.find(e=>e.toLowerCase()===Oh.name.toLowerCase())):Boolean(this.srcMediaData.disableTrackers))}loadstart(){this.destroy(),this.updateSrcMediaData(this.player.currentSource()),this.isTrackerDisabled()||(this.getInternalLabels(),this.reloadTagCommanderContainer(),this.notify("buffer_start"),this.hasStarted=!1)}loadeddata(){this.notify("init"),this.initialized=!0,this.notify("buffer_stop")}log(e,t,i="log"){this.debug()&&console[i](`SRGAnalytics:${e}`,t,window.tc_vars)}notify(e,t){if(this.isTrackerDisabled())return;try{this.flush()}catch(t){this.log(e,t,"error")}const i=Object.assign({},this.getEventLabels(e),t);this.log(e,i);try{window.tc_events_11?window.tc_events_11(this.player.el(),e,i):this.pendingQueue.push({action:e,labels:i})}catch(t){this.log(e,t,"error")}}static now(){return(Date.now()/1e3).toFixed(0)}play(){this.hasStarted||(this.hasStarted=!0),this.startPlaybackSession||this.isMediaOnDemand()||(this.startPlaybackSession=Oh.now()),0===this.mediaSession&&(this.mediaSession=Oh.now(),this.heartBeat(),this.uptime()),this.timeUpdate(),this.notify("play"),this.isSeeking&&(this.isSeeking=!1)}pause(){this.isMediaOnDemand()||(this.elapsedPlaybackTime=this.getElapsedPlayingTime(),this.startPlaybackSession=0),!this.player.seeking()&&!this.isMediaLive()&&this.player.currentTime()<this.player.duration()?this.notify("pause"):this.hasStarted&&!this.isSeeking&&(this.notify("seek"),this.isSeeking=!0)}rateChange(){this.notify("change_playback_rate")}reloadTagCommanderContainer(){window.tC?(window.tC.container.reload(),this.pendingTagCommanderReload=!1):this.pendingTagCommanderReload=!0}seeking(){!this.hasStarted||this.player.paused()||this.isSeeking||(this.notify("seek"),this.isSeeking=!0)}timeUpdate(){this.player.paused()||(this.trackedCurrentTime=this.player.currentTime())}timeShifted(){const e=this.player.liveTracker.atLiveEdge(),t=this.player.liveTracker.liveCurrentTime(),i=this.player.currentTime();return e?0:(t-i).toFixed(0)}updateSrcMediaData(e){this.srcMediaData=e}uptime(){const e=()=>{this.player.paused()||this.isMediaOnDemand()||this.notify("uptime")};this.uptimeTimeoutId=setTimeout(()=>{e(),this.uptimeIntervalId=setInterval(()=>{e()},6e4)},3e4)}waiting(){if(!this.initialized||this.isWaiting)return;const e=()=>{this.isWaiting=!1,this.notify("buffer_stop")};this.isWaiting=!0,this.notify("buffer_start"),ah.browser.IS_ANY_SAFARI?this.player.one(Ph,e):this.player.one(xh,e)}}class Mh{constructor(e,{playerName:t="none",playerVersion:i="none",platform:s="Web",schemaVersion:r=1,heartbeatInterval:n=3e4,beaconUrl:a="https://monitoring.pillarbox.ch/api/events"}={}){this.player=e,this.playerName=t,this.playerVersion=i,this.platform=s,this.schemaVersion=r,this.heartbeatInterval=n,this.beaconUrl=a,this.currentSessionId=void 0,this.lastPlaybackDuration=0,this.lastPlaybackStartTimestamp=0,this.lastStallCount=0,this.lastStallDuration=0,this.loadStartTimestamp=void 0,this.metadataRequestTime=0,this.mediaAssetUrl=void 0,this.mediaId=void 0,this.mediaMetadataUrl=void 0,this.mediaOrigin=void 0,this.tokenRequestTime=0,this.addListeners()}addListeners(){this.bindCallBacks(),this.player.on("loadstart",this.loadStart),this.player.on("loadeddata",this.loadedData),this.player.on("playing",this.playbackStart),this.player.on("pause",this.playbackStop),this.player.on("error",this.error),this.player.on(["playerreset","dispose","ended"],this.sessionStop),this.player.on(["waiting","stalled"],this.stalled),window.addEventListener("beforeunload",this.sessionStop)}bandwidth(){const e=this.player.tech(!0).vhs?this.player.tech(!0).vhs.stats:void 0;return e?e.bandwidth:void 0}bindCallBacks(){this.error=this.error.bind(this),this.loadedData=this.loadedData.bind(this),this.loadStart=this.loadStart.bind(this),this.playbackStart=this.playbackStart.bind(this),this.playbackStop=this.playbackStop.bind(this),this.stalled=this.stalled.bind(this),this.sessionStop=this.sessionStop.bind(this)}bufferDuration(){const e=this.player.buffered();let t=0;for(let i=0;i<e.length;i++){const s=e.start(i);t+=e.end(i)-s}return Mh.secondsToMilliseconds(t)}currentAudioTrack(){const e=this.player.audioTrack();if(e&&e.language)return e.language}currentRepresentation(){const{activeCues:{cues_:[e]}={cues_:[]}}=Array.from(this.player.textTracks()).find(({label:e,kind:t})=>"metadata"===t&&"segment-metadata"===e)||{};return e?e.value:void 0}currentResource(){let{bandwidth:e,uri:t}=this.currentRepresentation()||{};if(ah.browser.IS_ANY_SAFARI){const{configuration:i}=Array.from(this.player.videoTracks()).find(e=>e.selected)||{};e=i?i.bitrate:void 0,t=this.player.currentSource().src}return{bitrate:e,url:t}}currentSourceMediaData(){return this.player.currentSource().mediaData?this.player.currentSource().mediaData:{}}currentTextTrack(){const e=this.player.textTrack();if(e&&e.language)return e.language}error(){const e=this.currentAudioTrack(),t=this.player.error(),i=this.playbackPosition(),s=this.currentRepresentation(),r=s?s.uri:this.player.currentSource().src,a=this.currentTextTrack();this.player.hasStarted()||this.sendEvent("START",this.startEventData()),this.sendEvent("ERROR",n(n({audio:e,log:JSON.stringify(t.metadata||ah.log.history().slice(-15)),message:t.message,name:Mh.errorKeyCode(t.code)},i),{},{subtitles:a,url:r})),this.reset()}getDrmRequestDuration(){const e=Object.values(this.player.currentSource().keySystems||{}).map(e=>e.url);if(!e.length)return;const t=performance.getEntriesByType("resource").filter(({initiatorType:t,name:i})=>"xmlhttprequest"===t&&e.includes(i)).pop();return t&&t.duration}getMetadataInfo(e){const t=performance.getEntriesByType("resource").filter(({initiatorType:t,name:i})=>"fetch"===t&&i.includes(e)).pop();return t?{name:t.name,duration:t.duration}:{}}getTokenRequestDuration(e){if(!e)return;const t=performance.getEntriesByType("resource").filter(({initiatorType:e,name:t})=>"fetch"===e&&t.includes("/akahd/token")).pop();return t&&t.duration}heartbeat(){this.heartbeatIntervalId=setInterval(()=>{this.sendEvent("HEARTBEAT",this.statusEventData())},this.heartbeatInterval)}isTrackerDisabled(){const e=this.player.currentSource();return Array.isArray(e.disableTrackers)?Boolean(e.disableTrackers.find(e=>e.toLowerCase()===Mh.name.toLowerCase())):Boolean(e.disableTrackers)}loadedData(){this.sendEvent("START",this.startEventData()),this.sendEvent("HEARTBEAT",this.statusEventData()),this.heartbeat()}loadStart(){!Object.keys(this.currentSourceMediaData()).length&&this.currentSessionId&&(this.sessionStop(),this.sessionStartTimestamp=Mh.timestamp()),this.loadStartTimestamp=Mh.timestamp()}mediaInfo(){return{asset_url:this.mediaAssetUrl,id:this.mediaId,metadata_url:this.mediaMetadataUrl,origin:this.mediaOrigin}}playbackDuration(){return this.lastPlaybackStartTimestamp?Mh.timestamp()+this.lastPlaybackDuration-this.lastPlaybackStartTimestamp:this.lastPlaybackDuration}playbackPosition(){const e=this.currentRepresentation(),t=Mh.secondsToMilliseconds(this.player.currentTime());let i;if(e&&(i=e.programDateTime),ah.browser.IS_ANY_SAFARI){const e=Date.parse(this.player.$("video").getStartDate());i=isNaN(e)?void 0:e+t}return{position:t,position_timestamp:i}}playbackStart(){this.lastPlaybackStartTimestamp=Mh.timestamp()}playbackStop(){this.lastPlaybackDuration+=Mh.timestamp()-this.lastPlaybackStartTimestamp,this.lastPlaybackStartTimestamp=0}playerCurrentDimensions(){return this.player.currentDimensions()}playerInfo(){return{name:this.playerName,version:this.playerVersion,platform:this.platform}}qoeTimings(e,t){return{metadata:this.metadataRequestTime,asset:e,total:t-this.sessionStartTimestamp}}qosTimings(e){return{asset:e,drm:this.getDrmRequestDuration(),metadata:this.metadataRequestTime,token:this.tokenRequestTime}}removeListeners(){this.player.off("loadstart",this.loadStart),this.player.off("loadeddata",this.loadedData),this.player.off("playing",this.playbackStart),this.player.off("pause",this.playbackStop),this.player.off("error",this.error),this.player.off(["playerreset","dispose","ended"],this.sessionStop),this.player.off(["waiting","stalled"],this.stalled),window.removeEventListener("beforeunload",this.sessionStop)}removeTokenFromAssetUrl(e){if(e)try{const t=new URL(e);return t.searchParams.delete("hdnts"),t.href}catch(e){return}}reset(e){this.currentSessionId=void 0,this.lastPlaybackDuration=0,this.lastPlaybackStartTimestamp=0,this.lastStallCount=0,this.lastStallDuration=0,this.loadStartTimestamp=0,this.metadataRequestTime=0,this.mediaAssetUrl=void 0,this.mediaId=void 0,this.mediaMetadataUrl=void 0,this.mediaOrigin=void 0,this.sessionStartTimestamp=void 0,this.tokenRequestTime=0,clearInterval(this.heartbeatIntervalId),e&&!["ended","playerreset"].includes(e.type)&&this.removeListeners()}sendEvent(e,t={}){if(this.isTrackerDisabled()&&!this.currentSessionId||!this.currentSessionId)return;const i=JSON.stringify({event_name:e,session_id:this.currentSessionId,timestamp:Mh.timestamp(),version:this.schemaVersion,data:t});navigator.sendBeacon(this.beaconUrl,i)}sessionStart(){this.sessionStartTimestamp&&this.sessionStop(),this.sessionStartTimestamp=Mh.timestamp(),this.mediaId=this.player.currentSource().src||void 0}sessionStop(e){this.sendEvent("STOP",this.statusEventData()),this.reset(e)}stalled(){if(!this.player.hasStarted()||this.player.seeking()||this.isStalled)return;this.isStalled=!0;const e=Mh.timestamp(),t=()=>{const t=Mh.timestamp();this.isStalled=!1,this.lastStallCount+=1,this.lastStallDuration+=t-e};ah.browser.IS_ANY_SAFARI?this.player.one("timeupdate",t):this.player.one("playing",t)}stallInfo(){return{count:this.lastStallCount,duration:this.lastStallDuration}}statusEventData(){const e=this.currentAudioTrack(),t=this.bandwidth(),i=this.bufferDuration(),{bitrate:s,url:r}=this.currentResource(),{droppedVideoFrames:n}=this.player.getVideoPlaybackQuality()||{},a=this.playbackDuration(),{position:o,position_timestamp:l}=this.playbackPosition(),d=isFinite(this.player.duration())?"On-demand":"Live";return{audio:e,bandwidth:t,bitrate:s,buffered_duration:i,frame_drops:n,playback_duration:a,position:o,position_timestamp:l,stall:this.stallInfo(),stream_type:d,subtitles:this.currentTextTrack(),url:r}}startEventData(){const e=Mh.timestamp(),t=this.loadStartTimestamp?e-this.loadStartTimestamp:0;return this.isTrackerDisabled()||(this.currentSessionId=Mh.sessionId()),this.mediaAssetUrl=this.removeTokenFromAssetUrl(this.player.currentSource().src),this.mediaMetadataUrl=this.getMetadataInfo(this.mediaId).name,this.metadataRequestTime=this.getMetadataInfo(this.mediaId).duration,this.mediaOrigin=window.location.href,this.tokenRequestTime=this.getTokenRequestDuration(this.currentSourceMediaData().tokenType),{browser:Mh.userAgent(),device:{id:Mh.deviceId()},media:this.mediaInfo(),player:this.playerInfo(),qoe_timings:this.qoeTimings(t,e),qos_timings:this.qosTimings(t),screen:this.playerCurrentDimensions()}}static errorKeyCode(e){return`${["MEDIA_ERR_CUSTOM",...Object.keys(window.MediaError),"MEDIA_ERR_ENCRYPTED"][e]}: ${e}`}static sessionId(){return Mh.randomUUID()}static deviceId(){if(!localStorage)return;const e="pillarbox_device_id";let t=localStorage.getItem(e);return t||(t=Mh.randomUUID(),localStorage.setItem(e,t)),t}static randomUUID(){return crypto.randomUUID?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+e/4).toString(16))}static secondsToMilliseconds(e){return parseInt(1e3*e)}static timestamp(){return Date.now()}static userAgent(){return{user_agent:navigator.userAgent}}}class Rh{findChapterByUrn(e){if(this.chapterList){const[t]=this.chapterList.filter(t=>t.urn===e);return t}}findMainSegment(){if(!this.segmentUrn)return;const e=this.getMainSegments(),[t]=e.filter(e=>e.urn===this.segmentUrn);return t}findResourceListByUrn(e){const t=this.findChapterByUrn(e);if(t)return t.resourceList||[]}getChapters(){const e="AUDIO";return this.getMainChapter().mediaType===e||"EPISODE"!==this.getMainChapter().type?[]:this.chapterList.filter(({mediaType:t})=>t!==e)}getFilteredExternalSubtitles(){const{subtitleList:e}=this.getMainChapter(),[{subtitleInformationList:t}={}]=this.getResourceList().filter(({subtitleInformationList:e})=>e),i=e&&!t;if(!e)return[];const s=e.filter(e=>"TTML"!==e.format);return i?s:s.filter(e=>!t.find(t=>t.locale===e.locale&&e.type===t.type))}getMainBlockReason(){const e=this.getMainChapter();if(!e)return;let{blockReason:t}=e;return!t&&new Date<this.getMainValidFromDate()&&(t="STARTDATE"),t}getMainBlockedSegments(){return this.getMainSegments().filter(e=>e.blockReason)}getMainChapter(){return this.mainChapter||(this.mainChapter=this.findChapterByUrn(this.chapterUrn)),!this.mainChapter&&this.chapterList&&this.chapterList.length>0&&([this.mainChapter]=this.chapterList),this.mainChapter}getMainChapterImageUrl(){const e=this.getMainChapter();if(e&&e.imageUrl)return e.imageUrl}getMainResources(){const e=this.getResourceList();if(e&&e.length)return e.map(e=>({analyticsData:this.getMergedAnalyticsData(e.analyticsData),analyticsMetadata:this.getMergedAnalyticsMetadata(e.analyticsMetadata),blockReason:this.getMainChapter().blockReason,blockedSegments:this.getMainBlockedSegments(),imageUrl:this.getMainChapterImageUrl(),chapters:this.getChapters(),description:this.getMainChapter().description,drmList:e.drmList,dvr:e.dvr,eventData:this.getMainChapter().eventData,id:this.getMainChapter().id,imageCopyright:this.getMainChapter().imageCopyright,intervals:this.getMainTimeIntervals(),live:e.live,mediaContainer:e.mediaContainer,mediaType:this.getMainChapter().mediaType,mimeType:e.mimeType,presentation:e.presentation,quality:e.quality,spriteSheet:this.getMainChapter().spriteSheet,streaming:e.streaming,streamOffset:e.streamOffset,subtitles:this.getFilteredExternalSubtitles(),title:this.getMainChapter().title,tokenType:e.tokenType,url:e.url,urn:this.chapterUrn,vendor:this.getMainChapter().vendor}))}getMainSegments(){const e=this.getMainChapter();return!this.mainSegments&&e&&e.segmentList&&(this.mainSegments=e.segmentList),this.mainSegments||[]}getMainTimeIntervals(){const{timeIntervalList:e=[]}=this.getMainChapter()||{};return e}getMainValidFromDate(){const e=this.getMainChapter();if(!e)return new Date(0);const{validFrom:t}=e;return t?new Date(t):void 0}getMergedAnalyticsData(e){return n(n(n({},this.analyticsData),this.getMainChapter().analyticsData),e)}getMergedAnalyticsMetadata(e){return n(n(n({},this.analyticsMetadata),this.getMainChapter().analyticsMetadata),e)}getResourceList(){const{resourceList:e}=this.getMainChapter();return e||[]}}const Nh={Play:"Wiedergabe",Pause:"Pause",Replay:"Erneut abspielen","Current Time":"Aktueller Zeitpunkt",Duration:"Dauer","Remaining Time":"Verbleibende Zeit","Stream Type":"Streamtyp",LIVE:"LIVE",Loaded:"Geladen",Progress:"Status",Fullscreen:"Vollbild","Exit Fullscreen":"Vollbildmodus beenden",Mute:"Stumm schalten",Unmute:"Ton einschalten","Playback Rate":"Wiedergabegeschwindigkeit",Subtitles:"Untertitel","subtitles off":"Untertitel aus",Captions:"Untertitel","captions off":"Untertitel aus",Chapters:"Kapitel","You aborted the media playback":"Sie haben die Videowiedergabe abgebrochen.","A network error caused the media download to fail part-way.":"Der Videodownload ist aufgrund eines Netzwerkfehlers fehlgeschlagen.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Das Video konnte nicht geladen werden, da entweder ein Server- oder Netzwerkfehler auftrat oder das Format nicht unterstützt wird.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Die Videowiedergabe wurde entweder wegen eines Problems mit einem beschädigten Video oder wegen verwendeten Funktionen, die vom Browser nicht unterstützt werden, abgebrochen.","No compatible source was found for this media.":"Für dieses Video wurde keine kompatible Quelle gefunden.","Play Video":"Video abspielen",Close:"Schließen","Modal Window":"Modales Fenster","This is a modal window":"Dies ist ein modales Fenster","This modal can be closed by pressing the Escape key or activating the close button.":'Durch Drücken der Esc-Taste bzw. Betätigung der Schaltfläche "Schließen" wird dieses modale Fenster geschlossen.',", opens captions settings dialog":", öffnet Einstellungen für Untertitel",", opens subtitles settings dialog":", öffnet Einstellungen für Untertitel",", selected":", ausgewählt","captions settings":"Untertiteleinstellungen","subtitles settings":"Untertiteleinstellungen","descriptions settings":"Einstellungen für Beschreibungen","Close Modal Dialog":"Modales Fenster schließen",Descriptions:"Beschreibungen","descriptions off":"Beschreibungen aus","The media is encrypted and we do not have the keys to decrypt it.":"Die Entschlüsselungsschlüssel für den verschlüsselten Medieninhalt sind nicht verfügbar.",", opens descriptions settings dialog":", öffnet Einstellungen für Beschreibungen","Audio Track":"Tonspur",Text:"Schrift",White:"Weiß",Black:"Schwarz",Red:"Rot",Green:"Grün",Blue:"Blau",Yellow:"Gelb",Magenta:"Magenta",Cyan:"Türkis",Background:"Hintergrund",Window:"Fenster",Transparent:"Durchsichtig","Semi-Transparent":"Halbdurchsichtig",Opaque:"Undurchsichtig","Font Size":"Schriftgröße","Text Edge Style":"Textkantenstil",None:"Kein",Raised:"Erhoben",Depressed:"Gedrückt",Uniform:"Uniform","Drop shadow":"Schlagschatten","Font Family":"Schriftfamilie","Proportional Sans-Serif":"Proportionale Sans-Serif","Monospace Sans-Serif":"Monospace Sans-Serif","Proportional Serif":"Proportionale Serif","Monospace Serif":"Monospace Serif",Casual:"Zwanglos",Script:"Schreibschrift","Small Caps":"Small-Caps",Reset:"Zurücksetzen","restore all settings to the default values":"Alle Einstellungen auf die Standardwerte zurücksetzen",Done:"Fertig","Caption Settings Dialog":"Einstellungsdialog für Untertitel","Beginning of dialog window. Escape will cancel and close the window.":"Anfang des Dialogfensters. Esc bricht ab und schließt das Fenster.","End of dialog window.":"Ende des Dialogfensters.","Audio Player":"Audio-Player","Video Player":"Video-Player","Progress Bar":"Fortschrittsbalken","progress bar timing: currentTime={1} duration={2}":"{1} von {2}","Volume Level":"Lautstärke","{1} is loading.":"{1} wird geladen.","Seek to live, currently behind live":"Zur Live-Übertragung wechseln. Aktuell wird es nicht live abgespielt.","Seek to live, currently playing live":"Zur Live-Übertragung wechseln. Es wird aktuell live abgespielt.","Exit Picture-in-Picture":"Bild-im-Bild-Modus beenden","Picture-in-Picture":"Bild-im-Bild-Modus","No content":"Kein Inhalt",Color:"Farbe",Opacity:"Deckkraft","Text Background":"Texthintergrund","Caption Area Background":"Hintergrund des Untertitelbereichs","Playing in Picture-in-Picture":"Wird im Bild-im-Bild-Modus wiedergegeben","Skip forward {1} seconds":"{1} Sekunden vorwärts","Skip backward {1} seconds":"{1} Sekunden zurück"},Uh={AGERATING12:"Aus Gründen des Jugendschutzes steht dieser Inhalt nur zwischen 20:00 und 06:00 Uhr zur Verfügung.",AGERATING18:"Aus Gründen des Jugendschutzes steht dieser Inhalt nur zwischen 23:00 und 05:00 Uhr zur Verfügung.",COMMERCIAL:"Die Werbung wurde übersprungen.",ENDDATE:"Dieser Inhalt ist nicht mehr verfügbar.",GEOBLOCK:"Dieser Inhalt ist ausserhalb der Schweiz nicht verfügbar.",JOURNALISTIC:"Dieser Inhalt steht aus publizistischen Gründen vorübergehend nicht zur Verfügung.",LEGAL:"Dieser Inhalt ist aus rechtlichen Gründen nicht verfügbar.",STARTDATE:"Dieser Inhalt ist noch nicht verfügbar. Bitte probieren Sie es später noch einmal.",VPNORPROXYDETECTED:"Dieser Inhalt ist mit VPN oder Proxy nicht abspielbar.",UNKNOWN:"Dieser Inhalt ist nicht verfügbar."};ah.addLanguage("de",n(n({},Nh),Uh));const Bh={"Audio Player":"Audio Player","Video Player":"Video Player",Play:"Play",Pause:"Pause",Replay:"Replay","Current Time":"Current Time",Duration:"Duration","Remaining Time":"Remaining Time","Stream Type":"Stream Type",LIVE:"LIVE","Seek to live, currently behind live":"Seek to live, currently behind live","Seek to live, currently playing live":"Seek to live, currently playing live",Loaded:"Loaded",Progress:"Progress","Progress Bar":"Progress Bar","progress bar timing: currentTime={1} duration={2}":"{1} of {2}",Fullscreen:"Fullscreen","Exit Fullscreen":"Exit Fullscreen",Mute:"Mute",Unmute:"Unmute","Playback Rate":"Playback Rate",Subtitles:"Subtitles","subtitles off":"subtitles off",Captions:"Captions","captions off":"captions off",Chapters:"Chapters",Descriptions:"Descriptions","descriptions off":"descriptions off","Audio Track":"Audio Track","Volume Level":"Volume Level","You aborted the media playback":"You aborted the media playback","A network error caused the media download to fail part-way.":"A network error caused the media download to fail part-way.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"The media could not be loaded, either because the server or network failed or because the format is not supported.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"The media playback was aborted due to a corruption problem or because the media used features your browser did not support.","No compatible source was found for this media.":"No compatible source was found for this media.","The media is encrypted and we do not have the keys to decrypt it.":"The media is encrypted and we do not have the keys to decrypt it.","Play Video":"Play Video",Close:"Close","Close Modal Dialog":"Close Modal Dialog","Modal Window":"Modal Window","This is a modal window":"This is a modal window","This modal can be closed by pressing the Escape key or activating the close button.":"This modal can be closed by pressing the Escape key or activating the close button.",", opens captions settings dialog":", opens captions settings dialog",", opens subtitles settings dialog":", opens subtitles settings dialog",", opens descriptions settings dialog":", opens descriptions settings dialog",", selected":", selected","captions settings":"captions settings","subtitles settings":"subtitles settings","descriptions settings":"descriptions settings",Text:"Text",White:"White",Black:"Black",Red:"Red",Green:"Green",Blue:"Blue",Yellow:"Yellow",Magenta:"Magenta",Cyan:"Cyan",Background:"Background",Window:"Window",Transparent:"Transparent","Semi-Transparent":"Semi-Transparent",Opaque:"Opaque","Font Size":"Font Size","Text Edge Style":"Text Edge Style",None:"None",Raised:"Raised",Depressed:"Depressed",Uniform:"Uniform","Drop shadow":"Drop shadow","Font Family":"Font Family","Proportional Sans-Serif":"Proportional Sans-Serif","Monospace Sans-Serif":"Monospace Sans-Serif","Proportional Serif":"Proportional Serif","Monospace Serif":"Monospace Serif",Casual:"Casual",Script:"Script","Small Caps":"Small Caps",Reset:"Reset","restore all settings to the default values":"restore all settings to the default values",Done:"Done","Caption Settings Dialog":"Caption Settings Dialog","Beginning of dialog window. Escape will cancel and close the window.":"Beginning of dialog window. Escape will cancel and close the window.","End of dialog window.":"End of dialog window.","{1} is loading.":"{1} is loading.","Exit Picture-in-Picture":"Exit Picture-in-Picture","Picture-in-Picture":"Picture-in-Picture","No content":"No content",Color:"Color",Opacity:"Opacity","Text Background":"Text Background","Caption Area Background":"Caption Area Background","Playing in Picture-in-Picture":"Playing in Picture-in-Picture","Skip backward {1} seconds":"Skip backward {1} seconds","Skip forward {1} seconds":"Skip forward {1} seconds"},Fh={AGERATING12:"To protect children this content is only available between 8PM and 6AM.",AGERATING18:"To protect children this content is only available between 10PM and 5AM.",COMMERCIAL:"This commercial content is not available.",ENDDATE:"This content is not available anymore.",GEOBLOCK:"This content is not available outside Switzerland.",JOURNALISTIC:"This content is temporarily unavailable for journalistic reasons.",LEGAL:"This content is not available due to legal restrictions.",STARTDATE:"This content is not available yet.",VPNORPROXYDETECTED:"This content cannot be played while using a VPN or a proxy.",UNKNOWN:"This content is not available."};ah.addLanguage("en",n(n({},Bh),Fh));const qh={"Audio Player":"Lecteur audio","Video Player":"Lecteur vidéo",Play:"Lecture",Pause:"Pause",Replay:"Revoir","Current Time":"Temps actuel",Duration:"Durée","Remaining Time":"Temps restant","Stream Type":"Type de flux",LIVE:"EN DIRECT","Seek to live, currently behind live":"Rechercher le direct, actuellement après le direct","Seek to live, currently playing live":"Rechercher le direct, le direct actuellement en cours de lecture",Loaded:"Chargé",Progress:"Progression","Progress Bar":"Barre de progression","progress bar timing: currentTime={1} duration={2}":"{1} de {2}",Fullscreen:"Plein écran","Exit Fullscreen":"Fenêtré",Mute:"Mettre en sourdine",Unmute:"Activer le son","Playback Rate":"Vitesse de lecture",Subtitles:"Sous-titres","subtitles off":"Sous-titres désactivés",Captions:"Sous-titres transcrits","captions off":"Sous-titres transcrits désactivés",Chapters:"Chapitres",Descriptions:"Descriptions","descriptions off":"descriptions désactivées","Audio Track":"Piste audio","Volume Level":"Niveau de volume","You aborted the media playback":"Vous avez interrompu la lecture de la vidéo.","A network error caused the media download to fail part-way.":"Une erreur de réseau a interrompu le téléchargement de la vidéo.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Cette vidéo n'a pas pu être chargée, soit parce que le serveur ou le réseau a échoué ou parce que le format n'est pas reconnu.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"La lecture de la vidéo a été interrompue à cause d'un problème de corruption ou parce que la vidéo utilise des fonctionnalités non prises en charge par votre navigateur.","No compatible source was found for this media.":"Aucune source compatible n'a été trouvée pour cette vidéo.","The media is encrypted and we do not have the keys to decrypt it.":"Le média est chiffré et nous n'avons pas les clés pour le déchiffrer.","Play Video":"Lire la vidéo",Close:"Fermer","Close Modal Dialog":"Fermer la boîte de dialogue modale","Modal Window":"Fenêtre modale","This is a modal window":"Ceci est une fenêtre modale","This modal can be closed by pressing the Escape key or activating the close button.":"Ce modal peut être fermé en appuyant sur la touche Échap ou activer le bouton de fermeture.",", opens captions settings dialog":", ouvrir les paramètres des sous-titres transcrits",", opens subtitles settings dialog":", ouvrir les paramètres des sous-titres",", opens descriptions settings dialog":", ouvrir les paramètres des descriptions",", selected":", sélectionné","captions settings":"Paramètres des sous-titres transcrits","subtitles settings":"Paramètres des sous-titres","descriptions settings":"Paramètres des descriptions",Text:"Texte",White:"Blanc",Black:"Noir",Red:"Rouge",Green:"Vert",Blue:"Bleu",Yellow:"Jaune",Magenta:"Magenta",Cyan:"Cyan",Background:"Arrière-plan",Window:"Fenêtre",Transparent:"Transparent","Semi-Transparent":"Semi-transparent",Opaque:"Opaque","Font Size":"Taille des caractères","Text Edge Style":"Style des contours du texte",None:"Aucun",Raised:"Élevé",Depressed:"Enfoncé",Uniform:"Uniforme","Drop shadow":"Ombre portée","Font Family":"Famille de polices","Proportional Sans-Serif":"Polices à chasse variable sans empattement (Proportional Sans-Serif)","Monospace Sans-Serif":"Polices à chasse fixe sans empattement (Monospace Sans-Serif)","Proportional Serif":"Polices à chasse variable avec empattement (Proportional Serif)","Monospace Serif":"Polices à chasse fixe avec empattement (Monospace Serif)",Casual:"Manuscrite",Script:"Scripte","Small Caps":"Petites capitales",Reset:"Réinitialiser","restore all settings to the default values":"Restaurer tous les paramètres aux valeurs par défaut",Done:"Terminé","Caption Settings Dialog":"Boîte de dialogue des paramètres des sous-titres transcrits","Beginning of dialog window. Escape will cancel and close the window.":"Début de la fenêtre de dialogue. La touche d'échappement annulera et fermera la fenêtre.","End of dialog window.":"Fin de la fenêtre de dialogue.","Exit Picture-in-Picture":"Quitter le mode image dans l'image","Picture-in-Picture":"Image dans l'image","{1} is loading.":"{1} en cours de chargement.","No content":"Aucun contenu",Color:"Couleur",Opacity:"Opacité","Text Background":"Arrière-plan du texte","Caption Area Background":"Arrière-plan de la zone de sous-titre","Skip backward {1} seconds":"Reculer de {1} secondes","Skip forward {1} seconds":"Avancer de {1} secondes"},jh={AGERATING12:"Pour protéger les enfants, ce contenu est accessible entre 20h et 6h.",AGERATING18:"Pour protéger les enfants, ce contenu est accessible entre 23h et 5h.",COMMERCIAL:"Ce contenu n'est actuellement pas disponible.",ENDDATE:"Ce contenu n'est plus disponible.",GEOBLOCK:"La RTS ne dispose pas des droits de diffusion en dehors de la Suisse.",JOURNALISTIC:"Ce contenu est temporairement indisponible pour des raisons éditoriales.",LEGAL:"Pour des raisons juridiques, ce contenu n'est pas disponible.",STARTDATE:"Ce contenu n'est pas encore disponible. Veuillez réessayer plus tard.",VPNORPROXYDETECTED:"Ce contenu ne peut pas être lu avec un VPN ou un proxy.",UNKNOWN:"Ce contenu n'est actuellement pas disponible."};ah.addLanguage("fr",n(n({},qh),jh));const Vh={"Audio Player":"Lettore audio","Video Player":"Lettore video",Play:"Play",Pause:"Pausa",Replay:"Replay","Current Time":"Orario attuale",Duration:"Durata","Remaining Time":"Tempo rimanente","Stream Type":"Tipo di streaming",LIVE:"LIVE",Loaded:"Caricato",Progress:"Stato","Progress Bar":"Barra di avanzamento","progress bar timing: currentTime={1} duration={2}":"{1} di {2}",Fullscreen:"Schermo intero","Exit Fullscreen":"Chiudi Schermo intero",Mute:"Disattiva l’audio",Unmute:"Attiva l’audio","Playback Rate":"Velocità di riproduzione",Subtitles:"Sottotitoli","subtitles off":"Senza sottotitoli",Captions:"Didascalie","captions off":"Senza didascalie",Chapters:"Capitolo",Descriptions:"Descrizioni","descriptions off":"Descrizioni disattivate","Audio Track":"Traccia audio","Volume Level":"Livello del volume","You aborted the media playback":"La riproduzione del contenuto multimediale è stata interrotta.","A network error caused the media download to fail part-way.":"Il download del contenuto multimediale è stato interrotto a causa di un problema rete.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Il contenuto multimediale non può essere caricato a causa di un errore nel server o nella rete o perché il formato non viene supportato.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"La riproduzione del contenuto multimediale è stata interrotta a causa di un file danneggiato o per l’utilizzo di impostazioni non supportate dal browser.","No compatible source was found for this media.":"Non ci sono fonti compatibili per questo contenuto multimediale.","The media is encrypted and we do not have the keys to decrypt it.":"Il contenuto multimediale è criptato e non disponiamo delle chiavi per decifrarlo.","Play Video":"Riproduci il video",Close:"Chiudi","Close Modal Dialog":"Chiudi la finestra di dialogo","Modal Window":"Finestra di dialogo","This is a modal window":"Questa è una finestra di dialogo","This modal can be closed by pressing the Escape key or activating the close button.":"Questa finestra di dialogo può essere chiusa premendo sul tasto Esc o attivando il pulsante di chiusura.",", opens captions settings dialog":", aprire le impostazioni delle didascalie",", opens subtitles settings dialog":", aprire le impostazioni dei sottotitoli",", opens descriptions settings dialog":", aprire le impostazioni delle descrizioni",", selected":", selezionato","captions settings":"Impostazioni didascalie","subtitles settings":"Impostazioni sottotitoli","descriptions settings":"Impostazioni descrizioni",Text:"Testo",White:"Bianco",Black:"Nero",Red:"Rosso",Green:"Verde",Blue:"Blu",Yellow:"Giallo",Magenta:"Magenta",Cyan:"Ciano",Background:"Sfondo",Window:"Finestra",Transparent:"Trasparente","Semi-Transparent":"Semi-Trasparente",Opaque:"Opaco","Font Size":"Dimensione dei caratteri","Text Edge Style":"Stile dei bordi del testo",None:"Nessuno",Uniform:"Uniforme","Drop shadow":"Ombra","Font Family":"Carattere","Proportional Sans-Serif":"Sans-Serif proporzionale","Monospace Sans-Serif":"Sans-Serif monospaziato","Proportional Serif":"Serif proporzionale","Monospace Serif":"Serif monospaziato","Small Caps":"Maiuscoletto",Reset:"Reinizializza","restore all settings to the default values":"Ripristina i valori predefiniti per tutti i parametri",Done:"Fatto","Caption Settings Dialog":"Finestra di dialogo dei parametri della trascrizione dei sottotitoli","Beginning of dialog window. Escape will cancel and close the window.":"Inizio della finestra di dialogo. Il tasto Esc annullerà l’operazione e chiuderà la finestra.","End of dialog window.":"Fine della finestra di dialogo.","{1} is loading.":"{1} in fase di caricamento.","Exit Picture-in-Picture":"Esci dalla modalità Picture-in-Picture","Picture-in-Picture":"Picture-in-Picture",Color:"Colore",Opacity:"Opacità","Text Background":"Sfondo testo","Caption Area Background":"Sfondo area sottotitoli","Skip forward {1} seconds":"Avanti {1} secondi","Skip backward {1} seconds":"Indietro {1} secondi"},$h={AGERATING12:"Per proteggere i bambini, questo media è disponibile solo fra le 20 e le 6.",AGERATING18:"Per proteggere i bambini, questo media è disponibile solo fra le 23 le 5.",COMMERCIAL:"Questo contenuto commerciale non è disponibile.",ENDDATE:"Questo media non è più disponibile.",GEOBLOCK:"Questo media non è disponibile fuori dalla Svizzera.",JOURNALISTIC:"Questo contenuto è temporaneamente non disponibile per motivi editoriali.",LEGAL:"Il contenuto non è fruibile a causa di restrizioni legali.",STARTDATE:"Il contenuto non è ancora disponibile. Per cortesia prova più tardi.",VPNORPROXYDETECTED:"Questo contenuto non può essere riprodotto con VPN o proxy.",UNKNOWN:"Questo media non è disponibile."};ah.addLanguage("it",n(n({},Vh),$h));const Hh={"Audio Player":"Audio-Player","Video Player":"Video-Player",Play:"Start",Pause:"Pausa",Replay:"Mussar danovamain","Current Time":"Temp actual",Duration:"Durada","Remaining Time":"Temp restant","Stream Type":"Tip dal stream",LIVE:"LIVE",Loaded:"Chargià",Progress:"Progress","Progress Bar":"Bar da progessiun","progress bar timing: currentTime={1} duration={2}":"{1} da {2}",Fullscreen:"Entir visur","Non-Fullscreen":"Betg entir visur",Mute:"Senza tun",Unmute:"Cun tun","Playback Rate":"Tempo ",Subtitles:"Suttitels","subtitles off":"senza suttitels",Captions:"Suttitels","captions off":"senza suttitels",Chapters:"Chapitels",Descriptions:"Descripziuns","descriptions off":"senza descripziuns","Audio Track":"Piese audio","Volume Level":"Nivel dal volumen","You aborted the media playback":"Vus avais interrut la reproducziun","A network error caused the media download to fail part-way.":"In sbagl en la rait ha impedì il download","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Il medium n'ha betg pudì vegnir chargià u pervia d'in sbagl da server u da la rait, u perquai ch'il format n'è betg cumpatibel.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"La reproducziun è vegnida interrutta u perquai ch'il cuntegn è donnegià, u perquai ch’il medium dovra funcziuns che voss navigatur na sustegna betg.","No compatible source was found for this media.":"Chattà nagina funtauna cumpatibla per quest medium.","The media is encrypted and we do not have the keys to decrypt it.":"Il medium è codà e nus n’avain naginas clavs per al decodar.","Play Video":"Aviar video",Close:"Serrar","Close Modal Dialog":"Serrar la fanestra modala","Modal Window":"Fanestra modala","This is a modal window":"Quai è ina fanestra modala","This modal can be closed by pressing the Escape key or activating the close button.":'Questa fanestra modala pudais serrar cun la tasta "Escape" ubain cun il buttun.',", opens captions settings dialog":", avra opziuns per ils suttitels",", opens subtitles settings dialog":", avra opziuns per ils suttitels",", opens descriptions settings dialog":", avra opziuns per la descripziun",", selected":", selecziunà","captions settings":"opziuns per ils suttitels","subtitles settings":"opziuns per ils suttitels","descriptions settings":"opziuns per la descripziun",Text:"Text",White:"Alv",Black:"Nair",Red:"Cotschn",Green:"Verd",Blue:"Blau",Yellow:"Mellen",Magenta:"Magenta",Cyan:"Cyan",Background:"Fund",Window:"Fanestra",Transparent:"Transparent","Semi-Transparent":"Mez transparent",Opaque:"Betg transparent","Font Size":"Grandezza dal text","Text Edge Style":"Stil dal text",None:"Nagin",Raised:"Auzà",Depressed:"Sbassà",Uniform:"Uniform",Dropshadow:"Sumbriva","Font Family":"Scrittira","Proportional Sans-Serif":"Proportionale Sans-Serif","Monospace Sans-Serif":"Monospace Sans-Serif","Proportional Serif":"Proportionale Serif","Monospace Serif":"Monospace Serif",Casual:"Casual",Script:"Script","Small Caps":"Bustabs pitschens",Reset:"Da nov","restore all settings to the default values":"Enavos tar las opziuns da standard",Done:"Fatg","Caption Settings Dialog":"Opziuns per suttitels","Beginning of dialog window. Escape will cancel and close the window.":"Entschatta da la fanestra da dialog. Escape stizza e serra la fanestra.","End of dialog window.":"Fin da la fanestra da dialog.",AGERATING12:"Per proteger uffants, è quest cuntegn disponibel mo tranter las 20.00 e las 06.00.",AGERATING18:"Per proteger uffants, è quest cuntegn disponibel mo tranter las 23.00 e las 05.00.",COMMERCIAL:"Quest medium commerzial n'è betg disponibel.",ENDDATE:"Quest cuntegn n'è betg pli disponibel.",GEOBLOCK:"Quest cuntegn n'è betg disponibel ordaifer la Svizra.",JOURNALISTIC:"Quest cuntegn na stat ad interim betg a disposiziun per motivs publicistics.",LEGAL:"Quest cuntegn n'è betg disponibel perquai ch'el è scadì.",STARTDATE:"Quest cuntegn n'è betg anc disponibel. Empruvai pli tard.",VPNORPROXYDETECTED:"Quest cuntegn na po betg vegnir reproducì cun VPN ni proxy activà.",UNKNOWN:"Quest cuntegn n'è betg disponibel."};ah.addLanguage("rm",n({},Hh));const zh=["url","mimeType","keySystems"],Wh=["src"];class Gh{static addBlockedSegments(e,t=[]){const i="srgssr-blocked-segments",s=e.textTracks().getTrackById(i);if(s&&e.textTracks().removeTrack(s),!Array.isArray(t)||!t.length)return;const r=t.filter(e=>e.blockReason);r.length&&Gh.createTextTrack(e,i).then(t=>{r.forEach(e=>{Gh.addTextTrackCue(t,e)}),e.textTracks().addTrack(t)})}static addRemoteTextTracks(e,t=[]){Array.isArray(t)&&t.forEach(({type:t,language:i,locale:s,url:r})=>{e.addRemoteTextTrack({kind:"SDH"===t?"captions":"subtitles",label:i,language:s,src:r})})}static addTextTrackCue(e,t){const i=(Number.isFinite(t.markIn)?t.markIn:t.fullLengthMarkIn)/1e3,s=(Number.isFinite(t.markOut)?t.markOut:t.fullLengthMarkOut)/1e3;e.addCue(new VTTCue(i,s,JSON.stringify(t)))}static addTextTracks(e,{mediaData:t}){Gh.addRemoteTextTracks(e,t.subtitles),Gh.addChapters(e,t.urn,t.chapters),Gh.addBlockedSegments(e,t.blockedSegments),Gh.addIntervals(e,t.intervals)}static addChapters(e,t,i=[]){const s="srgssr-chapters",r=e.textTracks().getTrackById(s);r&&e.textTracks().removeTrack(r),Array.isArray(i)&&i.length&&Gh.createTextTrack(e,s).then(s=>{i.forEach(e=>{t===e.fullLengthUrn&&Gh.addTextTrackCue(s,e)}),e.textTracks().addTrack(s)})}static addIntervals(e,t=[]){const i="srgssr-intervals",s=e.textTracks().getTrackById(i);s&&e.textTracks().removeTrack(s),Array.isArray(t)&&t.length&&Gh.createTextTrack(e,i).then(i=>{t.forEach(e=>{Gh.addTextTrackCue(i,e)}),e.textTracks().addTrack(i)})}static blockingReason(e,t){if(!t.mediaData.blockReason)return;const i=e.localize(t.mediaData.blockReason);return Gh.error(e,{code:MediaError.MEDIA_ERR_ABORTED,message:i,metadata:{errorType:t.mediaData.blockReason,src:t}}),!0}static composeAkamaiResources(){return i(function*(e=[]){return Th.hasToken(e)?Th.tokenizeSources(e):Promise.resolve(e)}).apply(this,arguments)}static composeKeySystemsResources(e=[]){if(!_h.hasDrm(e))return e;return e.map(e=>n(n({},e),_h.buildKeySystems(e.drmList)))}static composeMainResources(e){return Gh.composeAkamaiResources(Gh.composeKeySystemsResources(Gh.filterIncompatibleResources(e.getMainResources())))}static composeSrcMediaData({mediaData:e,disableTrackers:t},i){const s=ah.obj.merge(i,e),{url:r,mimeType:n,keySystems:o}=s;return{src:r,type:n,keySystems:o,disableTrackers:t,mediaData:a(s,zh)}}static createTextTrack(e,t){return new Promise(i=>{setTimeout(()=>{i(new ah.TextTrack({id:t,kind:"metadata",label:t,tech:e.tech(!0)}))},100)})}static cuechangeEventProxy(e){e.textTracks().on("addtrack",({track:t})=>{["srgssr-chapters","srgssr-intervals"].includes(t.id)&&t.on("cuechange",()=>{const[i]=Array.from(t.activeCues),s=t.id.includes("srgssr-chapters")?"srgssr/chapter":"srgssr/interval";e.trigger({type:s,data:i})})})}static dataProvider(e){if(!e.options().srgOptions.dataProvider){const{dataProviderHost:t,dataProviderUrlHandler:i}=e.options().srgOptions,s=new oh(t).handleRequest(i);e.options({srgOptions:{dataProvider:s}})}return e.options().srgOptions.dataProvider}static dataProviderError(e,t){if(!t)return;const i=t.statusText?t.statusText:t.message;return Gh.error(e,{code:0,message:e.localize("UNKNOWN"),metadata:{errorType:"UNKNOWN",urn:e.src(),status:t.status,statusText:i,url:t.url}}),!0}static error(e,{code:t,message:i,metadata:s}){e.error(null),e.error({code:t,message:i,metadata:s})}static filterIncompatibleResources(e=[]){return e.filter(e=>!["RTMP","HDS"].includes(e.streaming))}static getBlockedSegment(e){const t=e.textTracks().getTrackById("srgssr-blocked-segments");if(!t)return;const[i]=Array.from(t.activeCues);return i}static getBlockedSegmentByTime(e,t){const i=Gh.getBlockedSegment(e);if(!i)return;return t>=i.startTime&&t<i.endTime?i:void 0}static getMediaComposition(e){return i(function*(e,t=(new oh).handleRequest()){const i=yield t(e);return Object.assign(new Rh,i)}).apply(this,arguments)}static getMediaData(e=[]){if(Th.hasToken(e))return e[0];const t=ah.browser.IS_ANY_SAFARI?"HLS":"DASH";return e.find(({streaming:e})=>e===t)||e[0]}static getSrcMediaObj(e,t){return i(function*(){Gh.pillarboxMonitoring(e)&&Gh.pillarboxMonitoring(e).sessionStart();const{src:i}=t,s=a(t,Wh),r=yield Gh.getMediaComposition(i,Gh.dataProvider(e)),n=yield Gh.composeMainResources(r);let o=Gh.getMediaData(n);return o||(o={blockReason:r.getMainChapter().blockReason,imageUrl:r.getMainChapterImageUrl()}),Gh.composeSrcMediaData(s,o)})()}static handleCurrentTime(e,t){const i=Gh.getBlockedSegmentByTime(e,t);if(!i||!Number.isFinite(i.endTime))return t;const s=i.endTime+.1;return e.trigger({type:"srgssr/blocked-segment",data:i}),e.currentTime(s),s}static handleSetCurrentTime(e,t){const{endTime:i}=Gh.getBlockedSegmentByTime(e,t)||{};return Number.isFinite(i)?i:t}static handleSetSource(e,t,s){return i(function*(){try{const i=yield Gh.getSrcMediaObj(e,t);if(Gh.srgAnalytics(e),Gh.updateTitleBar(e,i),Gh.updatePoster(e,i),Gh.blockingReason(e,i))return;return Gh.addTextTracks(e,i),s(null,i)}catch(t){if(Gh.dataProviderError(e,t))return;return s(t)}})()}static srgAnalytics(e){if(!1!==e.options().trackers.srgAnalytics&&!e.options().trackers.srgAnalytics){const t=new Oh(e,{debug:e.debug(),playerVersion:ah.VERSION.pillarbox,tagCommanderScriptURL:e.options().srgOptions.tagCommanderScriptURL});e.options({trackers:{srgAnalytics:t}})}}static pillarboxMonitoring(e){if(!1!==e.options().trackers.pillarboxMonitoring){if(!e.options().trackers.pillarboxMonitoring){const t=new Mh(e,{debug:e.debug(),playerVersion:ah.VERSION.pillarbox,playerName:"Pillarbox"});e.options({trackers:{pillarboxMonitoring:t}})}return e.options().trackers.pillarboxMonitoring}}static updatePoster(e,t,i=fh){e.poster(i.scale({url:t.mediaData.imageUrl}))}static updateTitleBar(e,t){e.titleBar&&e.titleBar.update({title:t.mediaData.vendor,description:t.mediaData.title})}static middleware(e){return Gh.pillarboxMonitoring(e),Gh.cuechangeEventProxy(e),{currentTime:t=>Gh.handleCurrentTime(e,t),setCurrentTime:t=>Gh.handleSetCurrentTime(e,t),setSource:(t=i(function*(t,i){return Gh.handleSetSource(e,t,i)}),function(e,i){return t.apply(this,arguments)})};var t}}ah.use("srgssr/urn",Gh.middleware),ah.options.srgOptions={dataProvider:void 0,dataProviderHost:void 0,dataProviderUrlHandler:void 0,tagCommanderScriptURL:void 0},e.DataProvider=oh,e.MediaComposition=Rh,e.PillarboxMonitoring=Mh,e.Player=nh,e.SRGAnalytics=Oh,e.SrgSsr=Gh,e.default=ah,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),window.pillarbox=ah,window.videojs=window.pillarbox});
30
30
  //# sourceMappingURL=pillarbox.umd.min.js.map