var ud=Object.defineProperty;var dd=Object.getPrototypeOf;var hd=Reflect.get;var fd=(s,e,t)=>e in s?ud(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var te=(s,e,t)=>(fd(s,typeof e!="symbol"?e+"":e,t),t),Wr=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var S=(s,e,t)=>(Wr(s,e,"read from private field"),t?t.call(s):e.get(s)),F=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)},G=(s,e,t,i)=>(Wr(s,e,"write to private field"),i?i.call(s,t):e.set(s,t),t);var ce=(s,e,t)=>(Wr(s,e,"access private method"),t),Ts=(s,e,t)=>hd(dd(s),t,e);var ai=class{addEventListener(){}removeEventListener(){}dispatchEvent(e){return!0}};if(typeof DocumentFragment=="undefined"){class s extends ai{}globalThis.DocumentFragment=s}var Pi=class extends ai{},Yr=class extends ai{},md={get(s){},define(s,e,t){},getName(s){return null},upgrade(s){},whenDefined(s){return Promise.resolve(Pi)}},Oi,jr=class{constructor(e,t={}){F(this,Oi,void 0);G(this,Oi,t==null?void 0:t.detail)}get detail(){return S(this,Oi)}initCustomEvent(){}};Oi=new WeakMap;function gd(s,e){return new Pi}var Io={document:{createElement:gd},DocumentFragment,customElements:md,CustomEvent:jr,EventTarget:ai,HTMLElement:Pi,HTMLVideoElement:Yr},Do=typeof window=="undefined"||typeof globalThis.customElements=="undefined",xs=Do?Io:globalThis,oy=Do?Io.document:globalThis.document;var pd=Object.create,Fo=Object.defineProperty,yd=Object.getOwnPropertyDescriptor,vd=Object.getOwnPropertyNames,Ed=Object.getPrototypeOf,Td=Object.prototype.hasOwnProperty,Uo=function(s,e){return function(){return s&&(e=s(s=0)),e}},Oe=function(s,e){return function(){return e||s((e={exports:{}}).exports,e),e.exports}},xd=function(s,e,t,i){if(e&&typeof e=="object"||typeof e=="function")for(var r=vd(e),n=0,a=r.length,o;n";default:return r(h)}}function r(h){var f=[],m=h.tagName;return h.namespaceURI==="http://www.w3.org/1999/xhtml"&&(m=m.toLowerCase()),f.push("<"+m+c(h)+o(h)),t.indexOf(m)>-1?f.push(" />"):(f.push(">"),h.childNodes.length?f.push.apply(f,h.childNodes.map(i)):h.textContent||h.innerText?f.push(u(h.textContent||h.innerText)):h.innerHTML&&f.push(h.innerHTML),f.push("")),f.join("")}function n(h,f){var m=an(h[f]);return f==="style"&&Object.keys(h.style).length>0?!0:h.hasOwnProperty(f)&&(m==="string"||m==="boolean"||m==="number")&&f!=="nodeName"&&f!=="className"&&f!=="tagName"&&f!=="textContent"&&f!=="innerText"&&f!=="namespaceURI"&&f!=="innerHTML"}function a(h){if(typeof h=="string")return h;var f="";return Object.keys(h).forEach(function(m){var g=h[m];m=m.replace(/[A-Z]/g,function(p){return"-"+p.toLowerCase()}),f+=m+":"+g+";"}),f}function o(h){var f=h.dataset,m=[];for(var g in f)m.push({name:"data-"+g,value:f[g]});return m.length?l(m):""}function l(h){var f=[];return h.forEach(function(m){var g=m.name,p=m.value;g==="style"&&(p=a(p)),f.push(g+'="'+d(p)+'"')}),f.length?" "+f.join(" "):""}function c(h){var f=[];for(var m in h)n(h,m)&&f.push({name:m,value:h[m]});for(var g in h._attributes)for(var p in h._attributes[g]){var v=h._attributes[g][p],E=(v.prefix?v.prefix+":":"")+p;f.push({name:E,value:v.value})}return h.className&&f.push({name:"class",value:h.className}),f.length?l(f):""}function u(h){var f="";return typeof h=="string"?f=h:h&&(f=h.toString()),f.replace(/&/g,"&").replace(//g,">")}function d(h){return u(h).replace(/"/g,""")}}),Ho=Oe(function(s,e){Ht();var t=Bo(),i=$o(),r=Go(),n=Ko(),a=bd(),o="http://www.w3.org/1999/xhtml";e.exports=l;function l(c,u,d){if(!Kt(this,l))return new l(c);var h=d===void 0?o:d||null;this.tagName=h===o?String(c).toUpperCase():c,this.nodeName=this.tagName,this.className="",this.dataset={},this.childNodes=[],this.parentNode=null,this.style={},this.ownerDocument=u||null,this.namespaceURI=h,this._attributes={},this.tagName==="INPUT"&&(this.type="text")}l.prototype.type="DOMElement",l.prototype.nodeType=1,l.prototype.appendChild=function(c){return c.parentNode&&c.parentNode.removeChild(c),this.childNodes.push(c),c.parentNode=this,c},l.prototype.replaceChild=function(c,u){c.parentNode&&c.parentNode.removeChild(c);var d=this.childNodes.indexOf(u);return u.parentNode=null,this.childNodes[d]=c,c.parentNode=this,u},l.prototype.removeChild=function(c){var u=this.childNodes.indexOf(c);return this.childNodes.splice(u,1),c.parentNode=null,c},l.prototype.insertBefore=function(c,u){c.parentNode&&c.parentNode.removeChild(c);var d=u==null?-1:this.childNodes.indexOf(u);return d>-1?this.childNodes.splice(d,0,c):this.childNodes.push(c),c.parentNode=this,c},l.prototype.setAttributeNS=function(c,u,d){var h=null,f=u,m=u.indexOf(":");if(m>-1&&(h=u.substr(0,m),f=u.substr(m+1)),this.tagName==="INPUT"&&u==="type")this.type=d;else{var g=this._attributes[c]||(this._attributes[c]={});g[f]={value:d,prefix:h}}},l.prototype.getAttributeNS=function(c,u){var d=this._attributes[c],h=d&&d[u]&&d[u].value;return this.tagName==="INPUT"&&u==="type"?this.type:typeof h!="string"?null:h},l.prototype.removeAttributeNS=function(c,u){var d=this._attributes[c];d&&delete d[u]},l.prototype.hasAttributeNS=function(c,u){var d=this._attributes[c];return!!d&&u in d},l.prototype.setAttribute=function(c,u){return this.setAttributeNS(null,c,u)},l.prototype.getAttribute=function(c){return this.getAttributeNS(null,c)},l.prototype.removeAttribute=function(c){return this.removeAttributeNS(null,c)},l.prototype.hasAttribute=function(c){return this.hasAttributeNS(null,c)},l.prototype.removeEventListener=n,l.prototype.addEventListener=r,l.prototype.dispatchEvent=i,l.prototype.focus=function(){},l.prototype.toString=function(){return a(this)},l.prototype.getElementsByClassName=function(c){var u=c.split(" "),d=[];return t(this,function(h){if(h.nodeType===1){var f=h.className||"",m=f.split(" ");u.every(function(g){return m.indexOf(g)!==-1})&&d.push(h)}}),d},l.prototype.getElementsByTagName=function(c){c=c.toLowerCase();var u=[];return t(this.childNodes,function(d){d.nodeType===1&&(c==="*"||d.tagName.toLowerCase()===c)&&u.push(d)}),u},l.prototype.contains=function(c){return t(this,function(u){return c===u})||!1}}),Ad=Oe(function(s,e){Ht();var t=Ho();e.exports=i;function i(r){if(!Kt(this,i))return new i;this.childNodes=[],this.parentNode=null,this.ownerDocument=r||null}i.prototype.type="DocumentFragment",i.prototype.nodeType=11,i.prototype.nodeName="#document-fragment",i.prototype.appendChild=t.prototype.appendChild,i.prototype.replaceChild=t.prototype.replaceChild,i.prototype.removeChild=t.prototype.removeChild,i.prototype.toString=function(){return this.childNodes.map(function(r){return String(r)}).join("")}}),Rd=Oe(function(s,e){e.exports=t;function t(i){}t.prototype.initEvent=function(i,r,n){this.type=i,this.bubbles=r,this.cancelable=n},t.prototype.preventDefault=function(){}}),Ld=Oe(function(s,e){Ht();var t=Bo(),i=_d(),r=Sd(),n=Ho(),a=Ad(),o=Rd(),l=$o(),c=Go(),u=Ko();e.exports=d;function d(){if(!Kt(this,d))return new d;this.head=this.createElement("head"),this.body=this.createElement("body"),this.documentElement=this.createElement("html"),this.documentElement.appendChild(this.head),this.documentElement.appendChild(this.body),this.childNodes=[this.documentElement],this.nodeType=9}var h=d.prototype;h.createTextNode=function(f){return new r(f,this)},h.createElementNS=function(f,m){var g=f===null?null:String(f);return new n(m,this,g)},h.createElement=function(f){return new n(f,this)},h.createDocumentFragment=function(){return new a(this)},h.createEvent=function(f){return new o(f)},h.createComment=function(f){return new i(f,this)},h.getElementById=function(f){f=String(f);var m=t(this.childNodes,function(g){if(String(g.id)===f)return g});return m||null},h.getElementsByClassName=n.prototype.getElementsByClassName,h.getElementsByTagName=n.prototype.getElementsByTagName,h.contains=n.prototype.contains,h.removeEventListener=u,h.addEventListener=c,h.dispatchEvent=l}),Id=Oe(function(s,e){var t=Ld();e.exports=new t}),Dd=Oe(function(s,e){var t=typeof global!="undefined"?global:typeof window!="undefined"?window:{},i=Id(),r;typeof document!="undefined"?r=document:(r=t["__GLOBAL_DOCUMENT_CACHE@4"],r||(r=t["__GLOBAL_DOCUMENT_CACHE@4"]=i)),e.exports=r});function kd(s){if(Array.isArray(s))return s}function wd(s,e){var t=s==null?null:typeof Symbol!="undefined"&&s[Symbol.iterator]||s["@@iterator"];if(t!=null){var i=[],r=!0,n=!1,a,o;try{for(t=t.call(s);!(r=(a=t.next()).done)&&(i.push(a.value),!(e&&i.length===e));r=!0);}catch(l){n=!0,o=l}finally{try{!r&&t.return!=null&&t.return()}finally{if(n)throw o}}return i}}function Cd(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function en(s,e){(e==null||e>s.length)&&(e=s.length);for(var t=0,i=new Array(e);t1&&arguments[1]!==void 0?arguments[1]:3,t,i,r,n,a,o=s?[console,s]:[console],l=(t=console.trace).bind.apply(t,Qe(o)),c=(i=console.info).bind.apply(i,Qe(o)),u=(r=console.debug).bind.apply(r,Qe(o)),d=(n=console.warn).bind.apply(n,Qe(o)),h=(a=console.error).bind.apply(a,Qe(o)),f=e;return{trace:function(){for(var m=arguments.length,g=new Array(m),p=0;p$t.TRACE))return l.apply(void 0,Qe(g))},debug:function(){for(var m=arguments.length,g=new Array(m),p=0;p$t.DEBUG))return u.apply(void 0,Qe(g))},info:function(){for(var m=arguments.length,g=new Array(m),p=0;p$t.INFO))return c.apply(void 0,Qe(g))},warn:function(){for(var m=arguments.length,g=new Array(m),p=0;p$t.WARN))return d.apply(void 0,Qe(g))},error:function(){for(var m=arguments.length,g=new Array(m),p=0;p$t.ERROR))return h.apply(void 0,Qe(g))},get level(){return f},set level(m){m!==this.level&&(f=m!=null?m:e)}}},ge=Nd("[mux]"),zr=qe(Je());function sn(){var s=zr.default.doNotTrack||zr.default.navigator&&zr.default.navigator.doNotTrack;return s==="1"}var Fd=qe(Je()),Ud={now:function(){var s=Fd.default.performance,e=s&&s.timing,t=e&&e.navigationStart,i=typeof t=="number"&&typeof s.now=="function"?t+s.now():Date.now();return Math.round(i)}},Se=Ud;function Q(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}Ht();function Le(s,e){if(!Kt(s,e))throw new TypeError("Cannot call a class as a function")}function ko(s,e){for(var t=0;t=0||n.toLowerCase().indexOf("x-litix-")===0)&&(e[n]=r.join(": "))}}),e}function Rs(s){if(s){var e=Wo.find(function(t){return s[t]!==void 0});return e?s[e]:void 0}}var Yd=function(s){var e={};for(var t in s){var i=s[t],r=i["DATA-ID"].search("io.litix.data.");if(r!==-1){var n=i["DATA-ID"].replace("io.litix.data.","");e[n]=i.VALUE}}return e},Yo=Yd,_s=function(s){if(!s)return{};var e=bs.navigationStart(),t=s.loading,i=t?t.start:s.trequest,r=t?t.first:s.tfirst,n=t?t.end:s.tload;return{bytesLoaded:s.total,requestStart:Math.round(e+i),responseStart:Math.round(e+r),responseEnd:Math.round(e+n)}},Mi=function(s){if(!(!s||typeof s.getAllResponseHeaders!="function"))return cn(s.getAllResponseHeaders())},jd=function(s,e,t){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=arguments.length>4?arguments[4]:void 0,n=s.log,a=s.utils.secondsToMs,o=function(v){var E=parseInt(r.version),T;return E===1&&v.programDateTime!==null&&(T=v.programDateTime),E===0&&v.pdt!==null&&(T=v.pdt),T};if(!bs.exists()){n.warn("performance timing not supported. Not tracking HLS.js.");return}var l=function(v,E){return s.emit(e,v,E)},c=function(v,E){var T=E.levels,x=E.audioTracks,_=E.url,I=E.stats,b=E.networkDetails,R=E.sessionData,k={},L={};T.forEach(function($,Z){k[Z]={width:$.width,height:$.height,bitrate:$.bitrate,attrs:$.attrs}}),x.forEach(function($,Z){L[Z]={name:$.name,language:$.lang,bitrate:$.bitrate}});var w=_s(I),P=w.bytesLoaded,O=w.requestStart,W=w.responseStart,q=w.responseEnd;l("requestcompleted",ln(As({},Yo(R)),{request_event_type:v,request_bytes_loaded:P,request_start:O,request_response_start:W,request_response_end:q,request_type:"manifest",request_hostname:Ve(_),request_response_headers:Mi(b),request_rendition_lists:{media:k,audio:L,video:{}}}))};t.on(r.Events.MANIFEST_LOADED,c);var u=function(v,E){var T=E.details,x=E.level,_=E.networkDetails,I=E.stats,b=_s(I),R=b.bytesLoaded,k=b.requestStart,L=b.responseStart,w=b.responseEnd,P=T.fragments[T.fragments.length-1],O=o(P)+a(P.duration);l("requestcompleted",{request_event_type:v,request_bytes_loaded:R,request_start:k,request_response_start:L,request_response_end:w,request_current_level:x,request_type:"manifest",request_hostname:Ve(T.url),request_response_headers:Mi(_),video_holdback:T.holdBack&&a(T.holdBack),video_part_holdback:T.partHoldBack&&a(T.partHoldBack),video_part_target_duration:T.partTarget&&a(T.partTarget),video_target_duration:T.targetduration&&a(T.targetduration),video_source_is_live:T.live,player_manifest_newest_program_time:isNaN(O)?void 0:O})};t.on(r.Events.LEVEL_LOADED,u);var d=function(v,E){var T=E.details,x=E.networkDetails,_=E.stats,I=_s(_),b=I.bytesLoaded,R=I.requestStart,k=I.responseStart,L=I.responseEnd;l("requestcompleted",{request_event_type:v,request_bytes_loaded:b,request_start:R,request_response_start:k,request_response_end:L,request_type:"manifest",request_hostname:Ve(T.url),request_response_headers:Mi(x)})};t.on(r.Events.AUDIO_TRACK_LOADED,d);var h=function(v,E){var T=E.stats,x=E.networkDetails,_=E.frag;T=T||_.stats;var I=_s(T),b=I.bytesLoaded,R=I.requestStart,k=I.responseStart,L=I.responseEnd,w=x?Mi(x):void 0,P={request_event_type:v,request_bytes_loaded:b,request_start:R,request_response_start:k,request_response_end:L,request_hostname:x?Ve(x.responseURL):void 0,request_id:w?Rs(w):void 0,request_response_headers:w,request_media_duration:_.duration,request_url:x==null?void 0:x.responseURL};_.type==="main"?(P.request_type="media",P.request_current_level=_.level,P.request_video_width=(t.levels[_.level]||{}).width,P.request_video_height=(t.levels[_.level]||{}).height,P.request_labeled_bitrate=(t.levels[_.level]||{}).bitrate):P.request_type=_.type,l("requestcompleted",P)};t.on(r.Events.FRAG_LOADED,h);var f=function(v,E){var T=E.frag,x=T.start,_=o(T),I={currentFragmentPDT:_,currentFragmentStart:a(x)};l("fragmentchange",I)};t.on(r.Events.FRAG_CHANGED,f);var m=function(v,E){var T=E.type,x=E.details,_=E.response,I=E.fatal,b=E.frag,R=E.networkDetails,k=(b==null?void 0:b.url)||E.url||"",L=R?Mi(R):void 0;if((x===r.ErrorDetails.MANIFEST_LOAD_ERROR||x===r.ErrorDetails.MANIFEST_LOAD_TIMEOUT||x===r.ErrorDetails.FRAG_LOAD_ERROR||x===r.ErrorDetails.FRAG_LOAD_TIMEOUT||x===r.ErrorDetails.LEVEL_LOAD_ERROR||x===r.ErrorDetails.LEVEL_LOAD_TIMEOUT||x===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||x===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT||x===r.ErrorDetails.SUBTITLE_LOAD_ERROR||x===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT||x===r.ErrorDetails.KEY_LOAD_ERROR||x===r.ErrorDetails.KEY_LOAD_TIMEOUT)&&l("requestfailed",{request_error:x,request_url:k,request_hostname:Ve(k),request_id:L?Rs(L):void 0,request_type:x===r.ErrorDetails.FRAG_LOAD_ERROR||x===r.ErrorDetails.FRAG_LOAD_TIMEOUT?"media":x===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||x===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT?"audio":x===r.ErrorDetails.SUBTITLE_LOAD_ERROR||x===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT?"subtitle":x===r.ErrorDetails.KEY_LOAD_ERROR||x===r.ErrorDetails.KEY_LOAD_TIMEOUT?"encryption":"manifest",request_error_code:_==null?void 0:_.code,request_error_text:_==null?void 0:_.text}),I){var w,P="".concat(k?"url: ".concat(k,` `):"")+"".concat(_&&(_.code||_.text)?"response: ".concat(_.code,", ").concat(_.text,` `):"")+"".concat(E.reason?"failure reason: ".concat(E.reason,` `):"")+"".concat(E.level?"level: ".concat(E.level,` `):"")+"".concat(E.parent?"parent stream controller: ".concat(E.parent,` `):"")+"".concat(E.buffer?"buffer length: ".concat(E.buffer,` `):"")+"".concat(E.error?"error: ".concat(E.error,` `):"")+"".concat(E.event?"event: ".concat(E.event,` `):"")+"".concat(E.err?"error message: ".concat((w=E.err)===null||w===void 0?void 0:w.message,` `):"");l("error",{player_error_code:T,player_error_message:x,player_error_context:P})}};t.on(r.Events.ERROR,m);var g=function(v,E){var T=E.frag,x=T&&T._url||"";l("requestcanceled",{request_event_type:v,request_url:x,request_type:"media",request_hostname:Ve(x)})};t.on(r.Events.FRAG_LOAD_EMERGENCY_ABORTED,g);var p=function(v,E){var T=E.level,x=t.levels[T];if(x&&x.attrs&&x.attrs.BANDWIDTH){var _=x.attrs.BANDWIDTH,I,b=parseFloat(x.attrs["FRAME-RATE"]);isNaN(b)||(I=b),_?l("renditionchange",{video_source_fps:I,video_source_bitrate:_,video_source_width:x.width,video_source_height:x.height,video_source_rendition_name:x.name,video_source_codec:x==null?void 0:x.videoCodec}):n.warn("missing BANDWIDTH from HLS manifest parsed by HLS.js")}};t.on(r.Events.LEVEL_SWITCHED,p),t._stopMuxMonitor=function(){t.off(r.Events.MANIFEST_LOADED,c),t.off(r.Events.LEVEL_LOADED,u),t.off(r.Events.AUDIO_TRACK_LOADED,d),t.off(r.Events.FRAG_LOADED,h),t.off(r.Events.FRAG_CHANGED,f),t.off(r.Events.ERROR,m),t.off(r.Events.FRAG_LOAD_EMERGENCY_ABORTED,g),t.off(r.Events.LEVEL_SWITCHED,p),t.off(r.Events.DESTROYING,t._stopMuxMonitor),delete t._stopMuxMonitor},t.on(r.Events.DESTROYING,t._stopMuxMonitor)},zd=function(s){s&&typeof s._stopMuxMonitor=="function"&&s._stopMuxMonitor()},wo=function(s,e){if(!s||!s.requestEndDate)return{};var t=Ve(s.url),i=s.url,r=s.bytesLoaded,n=new Date(s.requestStartDate).getTime(),a=new Date(s.firstByteDate).getTime(),o=new Date(s.requestEndDate).getTime(),l=isNaN(s.duration)?0:s.duration,c=typeof e.getMetricsFor=="function"?e.getMetricsFor(s.mediaType).HttpList:e.getDashMetrics().getHttpRequests(s.mediaType),u;c.length>0&&(u=cn(c[c.length-1]._responseHeaders||""));var d=u?Rs(u):void 0;return{requestStart:n,requestResponseStart:a,requestResponseEnd:o,requestBytesLoaded:r,requestResponseHeaders:u,requestMediaDuration:l,requestHostname:t,requestUrl:i,requestId:d}},Xd=function(s,e){var t=e.getQualityFor(s),i=e.getCurrentTrackFor(s).bitrateList;return i?{currentLevel:t,renditionWidth:i[t].width||null,renditionHeight:i[t].height||null,renditionBitrate:i[t].bandwidth}:{}},Qd=function(s){var e;return(e=s.match(/.*codecs\*?="(.*)"/))===null||e===void 0?void 0:e[1]},Jd=function(s){try{var e,t,i=(t=s.getVersion)===null||t===void 0||(e=t.call(s))===null||e===void 0?void 0:e.split(".").map(function(r){return parseInt(r)})[0];return i}catch{return!1}},Zd=function(s,e,t){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=s.log;if(!t||!t.on){r.warn("Invalid dash.js player reference. Monitoring blocked.");return}var n=Jd(t),a=function(T,x){return s.emit(e,T,x)},o=function(T){var x=T.type,_=T.data,I=(_||{}).url;a("requestcompleted",{request_event_type:x,request_start:0,request_response_start:0,request_response_end:0,request_bytes_loaded:-1,request_type:"manifest",request_hostname:Ve(I),request_url:I})};t.on("manifestLoaded",o);var l={},c=function(T){if(typeof T.getRequests!="function")return null;var x=T.getRequests({state:"executed"});return x.length===0?null:x[x.length-1]},u=function(T){var x=T.type,_=T.fragmentModel,I=T.chunk,b=c(_);d({type:x,request:b,chunk:I})},d=function(T){var x=T.type,_=T.chunk,I=T.request,b=(_||{}).mediaInfo,R=b||{},k=R.type,L=R.bitrateList;L=L||[];var w={};L.forEach(function(ee,X){w[X]={},w[X].width=ee.width,w[X].height=ee.height,w[X].bitrate=ee.bandwidth,w[X].attrs={}}),k==="video"?l.video=w:k==="audio"?l.audio=w:l.media=w;var P=wo(I,t),O=P.requestStart,W=P.requestResponseStart,q=P.requestResponseEnd,$=P.requestResponseHeaders,Z=P.requestMediaDuration,ne=P.requestHostname,H=P.requestUrl,B=P.requestId;a("requestcompleted",{request_event_type:x,request_start:O,request_response_start:W,request_response_end:q,request_bytes_loaded:-1,request_type:k+"_init",request_response_headers:$,request_hostname:ne,request_id:B,request_url:H,request_media_duration:Z,request_rendition_lists:l})};n>=4?t.on("initFragmentLoaded",d):t.on("initFragmentLoaded",u);var h=function(T){var x=T.type,_=T.fragmentModel,I=T.chunk,b=c(_);f({type:x,request:b,chunk:I})},f=function(T){var x=T.type,_=T.chunk,I=T.request,b=_||{},R=b.mediaInfo,k=b.start,L=R||{},w=L.type,P=wo(I,t),O=P.requestStart,W=P.requestResponseStart,q=P.requestResponseEnd,$=P.requestBytesLoaded,Z=P.requestResponseHeaders,ne=P.requestMediaDuration,H=P.requestHostname,B=P.requestUrl,ee=P.requestId,X=Xd(w,t),ae=X.currentLevel,ye=X.renditionWidth,ve=X.renditionHeight,_e=X.renditionBitrate;a("requestcompleted",{request_event_type:x,request_start:O,request_response_start:W,request_response_end:q,request_bytes_loaded:$,request_type:w,request_response_headers:Z,request_hostname:H,request_id:ee,request_url:B,request_media_start_time:k,request_media_duration:ne,request_current_level:ae,request_labeled_bitrate:_e,request_video_width:ye,request_video_height:ve})};n>=4?t.on("mediaFragmentLoaded",f):t.on("mediaFragmentLoaded",h);var m={video:void 0,audio:void 0,totalBitrate:void 0},g=function(){if(m.video&&typeof m.video.bitrate=="number"){if(!(m.video.width&&m.video.height)){r.warn("have bitrate info for video but missing width/height");return}var T=m.video.bitrate;if(m.audio&&typeof m.audio.bitrate=="number"&&(T+=m.audio.bitrate),T!==m.totalBitrate)return m.totalBitrate=T,{video_source_bitrate:T,video_source_height:m.video.height,video_source_width:m.video.width,video_source_codec:Qd(m.video.codec)}}},p=function(T,x,_){if(typeof T.newQuality!="number"){r.warn("missing evt.newQuality in qualityChangeRendered event",T);return}var I=T.mediaType;if(I==="audio"||I==="video"){var b=t.getBitrateInfoListFor(I).find(function(k){var L=k.qualityIndex;return L===T.newQuality});if(!(b&&typeof b.bitrate=="number")){r.warn("missing bitrate info for ".concat(I));return}m[I]=ln(As({},b),{codec:t.getCurrentTrackFor(I).codec});var R=g();R&&a("renditionchange",R)}};t.on("qualityChangeRendered",p);var v=function(T){var x=T.request,_=T.mediaType;x=x||{},a("requestcanceled",{request_event_type:x.type+"_"+x.action,request_url:x.url,request_type:_,request_hostname:Ve(x.url)})};t.on("fragmentLoadingAbandoned",v);var E=function(T){var x=T.error,_,I,b=(x==null||(_=x.data)===null||_===void 0?void 0:_.request)||{},R=(x==null||(I=x.data)===null||I===void 0?void 0:I.response)||{};(x==null?void 0:x.code)===27&&a("requestfailed",{request_error:b.type+"_"+b.action,request_url:b.url,request_hostname:Ve(b.url),request_type:b.mediaType,request_error_code:R.status,request_error_text:R.statusText});var k="".concat(b!=null&&b.url?"url: ".concat(b.url,` `):"")+"".concat(R!=null&&R.status||R!=null&&R.statusText?"response: ".concat(R==null?void 0:R.status,", ").concat(R==null?void 0:R.statusText,` `):"");a("error",{player_error_code:x==null?void 0:x.code,player_error_message:x==null?void 0:x.message,player_error_context:k})};t.on("error",E),t._stopMuxMonitor=function(){t.off("manifestLoaded",o),t.off("initFragmentLoaded",d),t.off("mediaFragmentLoaded",f),t.off("qualityChangeRendered",p),t.off("error",E),t.off("fragmentLoadingAbandoned",v),delete t._stopMuxMonitor}},eh=function(s){s&&typeof s._stopMuxMonitor=="function"&&s._stopMuxMonitor()},Co=0,th=function(){"use strict";function s(){Le(this,s),N(this,"_listeners",void 0)}return Ze(s,[{key:"on",value:function(e,t,i){return t._eventEmitterGuid=t._eventEmitterGuid||++Co,this._listeners=this._listeners||{},this._listeners[e]=this._listeners[e]||[],i&&(t=t.bind(i)),this._listeners[e].push(t),t}},{key:"off",value:function(e,t){var i=this._listeners&&this._listeners[e];i&&i.forEach(function(r,n){r._eventEmitterGuid===t._eventEmitterGuid&&i.splice(n,1)})}},{key:"one",value:function(e,t,i){var r=this;t._eventEmitterGuid=t._eventEmitterGuid||++Co;var n=function(){r.off(e,n),t.apply(i||this,arguments)};n._eventEmitterGuid=t._eventEmitterGuid,this.on(e,n)}},{key:"emit",value:function(e,t){var i=this;if(this._listeners){t=t||{};var r=this._listeners["before*"]||[],n=this._listeners[e]||[],a=this._listeners["after"+e]||[],o=function(l,c){l=l.slice(),l.forEach(function(u){u.call(i,{type:e},c)})};o(r,t),o(n,t),o(a,t)}}}]),s}(),ih=th,Qr=qe(Je()),sh=function(){"use strict";function s(e){var t=this;Le(this,s),N(this,"_playbackHeartbeatInterval",void 0),N(this,"_playheadShouldBeProgressing",void 0),N(this,"pm",void 0),this.pm=e,this._playbackHeartbeatInterval=null,this._playheadShouldBeProgressing=!1,e.on("playing",function(){t._playheadShouldBeProgressing=!0}),e.on("play",this._startPlaybackHeartbeatInterval.bind(this)),e.on("playing",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adbreakstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplay",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplaying",this._startPlaybackHeartbeatInterval.bind(this)),e.on("devicewake",this._startPlaybackHeartbeatInterval.bind(this)),e.on("viewstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("rebufferstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("pause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("ended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("viewend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("error",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("aderror",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adpause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adbreakend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("seeked",function(){e.data.player_is_paused?t._stopPlaybackHeartbeatInterval():t._startPlaybackHeartbeatInterval()}),e.on("timeupdate",function(){t._playbackHeartbeatInterval!==null&&e.emit("playbackheartbeat")}),e.on("devicesleep",function(i,r){t._playbackHeartbeatInterval!==null&&(Qr.default.clearInterval(t._playbackHeartbeatInterval),e.emit("playbackheartbeatend",{viewer_time:r.viewer_time}),t._playbackHeartbeatInterval=null)})}return Ze(s,[{key:"_startPlaybackHeartbeatInterval",value:function(){var e=this;this._playbackHeartbeatInterval===null&&(this.pm.emit("playbackheartbeat"),this._playbackHeartbeatInterval=Qr.default.setInterval(function(){e.pm.emit("playbackheartbeat")},this.pm.playbackHeartbeatTime))}},{key:"_stopPlaybackHeartbeatInterval",value:function(){this._playheadShouldBeProgressing=!1,this._playbackHeartbeatInterval!==null&&(Qr.default.clearInterval(this._playbackHeartbeatInterval),this.pm.emit("playbackheartbeatend"),this._playbackHeartbeatInterval=null)}}]),s}(),rh=sh,nh=function s(e){"use strict";var t=this;Le(this,s),N(this,"viewErrored",void 0),e.on("viewinit",function(){t.viewErrored=!1}),e.on("error",function(i,r){try{var n=e.errorTranslator({player_error_code:r.player_error_code,player_error_message:r.player_error_message,player_error_context:r.player_error_context,player_error_severity:r.player_error_severity,player_error_business_exception:r.player_error_business_exception});n&&(e.data.player_error_code=n.player_error_code||r.player_error_code,e.data.player_error_message=n.player_error_message||r.player_error_message,e.data.player_error_context=n.player_error_context||r.player_error_context,e.data.player_error_severity=n.player_error_severity||r.player_error_severity,e.data.player_error_business_exception=n.player_error_business_exception||r.player_error_business_exception,t.viewErrored=!0)}catch(a){e.mux.log.warn("Exception in error translator callback.",a),t.viewErrored=!0}}),e.on("aftererror",function(){var i,r,n,a,o;(i=e.data)===null||i===void 0||delete i.player_error_code,(r=e.data)===null||r===void 0||delete r.player_error_message,(n=e.data)===null||n===void 0||delete n.player_error_context,(a=e.data)===null||a===void 0||delete a.player_error_severity,(o=e.data)===null||o===void 0||delete o.player_error_business_exception})},ah=nh,oh=function(){"use strict";function s(e){Le(this,s),N(this,"_watchTimeTrackerLastCheckedTime",void 0),N(this,"pm",void 0),this.pm=e,this._watchTimeTrackerLastCheckedTime=null,e.on("playbackheartbeat",this._updateWatchTime.bind(this)),e.on("playbackheartbeatend",this._clearWatchTimeState.bind(this))}return Ze(s,[{key:"_updateWatchTime",value:function(e,t){var i=t.viewer_time;this._watchTimeTrackerLastCheckedTime===null&&(this._watchTimeTrackerLastCheckedTime=i),Ee(this.pm.data,"view_watch_time",i-this._watchTimeTrackerLastCheckedTime),this._watchTimeTrackerLastCheckedTime=i}},{key:"_clearWatchTimeState",value:function(e,t){this._updateWatchTime(e,t),this._watchTimeTrackerLastCheckedTime=null}}]),s}(),lh=oh,ch=function(){"use strict";function s(e){var t=this;Le(this,s),N(this,"_playbackTimeTrackerLastPlayheadPosition",void 0),N(this,"_lastTime",void 0),N(this,"_isAdPlaying",void 0),N(this,"_callbackUpdatePlaybackTime",void 0),N(this,"pm",void 0),this.pm=e,this._playbackTimeTrackerLastPlayheadPosition=-1,this._lastTime=Se.now(),this._isAdPlaying=!1,this._callbackUpdatePlaybackTime=null;var i=this._startPlaybackTimeTracking.bind(this);e.on("playing",i),e.on("adplaying",i),e.on("seeked",i);var r=this._stopPlaybackTimeTracking.bind(this);e.on("playbackheartbeatend",r),e.on("seeking",r),e.on("adplaying",function(){t._isAdPlaying=!0}),e.on("adended",function(){t._isAdPlaying=!1}),e.on("adpause",function(){t._isAdPlaying=!1}),e.on("adbreakstart",function(){t._isAdPlaying=!1}),e.on("adbreakend",function(){t._isAdPlaying=!1}),e.on("adplay",function(){t._isAdPlaying=!1}),e.on("viewinit",function(){t._playbackTimeTrackerLastPlayheadPosition=-1,t._lastTime=Se.now(),t._isAdPlaying=!1,t._callbackUpdatePlaybackTime=null})}return Ze(s,[{key:"_startPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime===null&&(this._callbackUpdatePlaybackTime=this._updatePlaybackTime.bind(this),this._playbackTimeTrackerLastPlayheadPosition=this.pm.data.player_playhead_time,this.pm.on("playbackheartbeat",this._callbackUpdatePlaybackTime))}},{key:"_stopPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime&&(this._updatePlaybackTime(),this.pm.off("playbackheartbeat",this._callbackUpdatePlaybackTime),this._callbackUpdatePlaybackTime=null,this._playbackTimeTrackerLastPlayheadPosition=-1)}},{key:"_updatePlaybackTime",value:function(){var e=this.pm.data.player_playhead_time,t=Se.now(),i=-1;this._playbackTimeTrackerLastPlayheadPosition>=0&&e>this._playbackTimeTrackerLastPlayheadPosition?i=e-this._playbackTimeTrackerLastPlayheadPosition:this._isAdPlaying&&(i=t-this._lastTime),i>0&&i<=1e3&&Ee(this.pm.data,"view_content_playback_time",i),this._playbackTimeTrackerLastPlayheadPosition=e,this._lastTime=t}}]),s}(),uh=ch,dh=function(){"use strict";function s(e){Le(this,s),N(this,"pm",void 0),this.pm=e;var t=this._updatePlayheadTime.bind(this);e.on("playbackheartbeat",t),e.on("playbackheartbeatend",t),e.on("timeupdate",t),e.on("destroy",function(){e.off("timeupdate",t)})}return Ze(s,[{key:"_updateMaxPlayheadPosition",value:function(){this.pm.data.view_max_playhead_position=typeof this.pm.data.view_max_playhead_position=="undefined"?this.pm.data.player_playhead_time:Math.max(this.pm.data.view_max_playhead_position,this.pm.data.player_playhead_time)}},{key:"_updatePlayheadTime",value:function(e,t){var i=this,r=function(){i.pm.currentFragmentPDT&&i.pm.currentFragmentStart&&(i.pm.data.player_program_time=i.pm.currentFragmentPDT+i.pm.data.player_playhead_time-i.pm.currentFragmentStart)};if(t&&t.player_playhead_time)this.pm.data.player_playhead_time=t.player_playhead_time,r(),this._updateMaxPlayheadPosition();else if(this.pm.getPlayheadTime){var n=this.pm.getPlayheadTime();typeof n!="undefined"&&(this.pm.data.player_playhead_time=n,r(),this._updateMaxPlayheadPosition())}}}]),s}(),hh=dh,Po=5*60*1e3,fh=function s(e){"use strict";if(Le(this,s),!e.disableRebufferTracking){var t,i=function(n,a){r(a),t=void 0},r=function(n){if(t){var a=n.viewer_time-t;Ee(e.data,"view_rebuffer_duration",a),t=n.viewer_time,e.data.view_rebuffer_duration>Po&&(e.emit("viewend"),e.send("viewend"),e.mux.log.warn("Ending view after rebuffering for longer than ".concat(Po,"ms, future events will be ignored unless a programchange or videochange occurs.")))}e.data.view_watch_time>=0&&e.data.view_rebuffer_count>0&&(e.data.view_rebuffer_frequency=e.data.view_rebuffer_count/e.data.view_watch_time,e.data.view_rebuffer_percentage=e.data.view_rebuffer_duration/e.data.view_watch_time)};e.on("playbackheartbeat",function(n,a){return r(a)}),e.on("rebufferstart",function(n,a){t||(Ee(e.data,"view_rebuffer_count",1),t=a.viewer_time,e.one("rebufferend",i))}),e.on("viewinit",function(){t=void 0,e.off("rebufferend",i)})}},mh=fh,gh=function(){"use strict";function s(e){var t=this;Le(this,s),N(this,"_lastCheckedTime",void 0),N(this,"_lastPlayheadTime",void 0),N(this,"_lastPlayheadTimeUpdatedTime",void 0),N(this,"_rebuffering",void 0),N(this,"pm",void 0),this.pm=e,!(e.disableRebufferTracking||e.disablePlayheadRebufferTracking)&&(this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null,e.on("playbackheartbeat",this._checkIfRebuffering.bind(this)),e.on("playbackheartbeatend",this._cleanupRebufferTracker.bind(this)),e.on("seeking",function(){t._cleanupRebufferTracker(null,{viewer_time:Se.now()})}))}return Ze(s,[{key:"_checkIfRebuffering",value:function(e,t){if(this.pm.seekingTracker.isSeeking||this.pm.adTracker.isAdBreak||!this.pm.playbackHeartbeat._playheadShouldBeProgressing){this._cleanupRebufferTracker(e,t);return}if(this._lastCheckedTime===null){this._prepareRebufferTrackerState(t.viewer_time);return}if(this._lastPlayheadTime!==this.pm.data.player_playhead_time){this._cleanupRebufferTracker(e,t,!0);return}var i=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.sustainedRebufferThreshold=="number"&&i>=this.pm.sustainedRebufferThreshold&&(this._rebuffering||(this._rebuffering=!0,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}))),this._lastCheckedTime=t.viewer_time}},{key:"_clearRebufferTrackerState",value:function(){this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null}},{key:"_prepareRebufferTrackerState",value:function(e){this._lastCheckedTime=e,this._lastPlayheadTime=this.pm.data.player_playhead_time,this._lastPlayheadTimeUpdatedTime=e}},{key:"_cleanupRebufferTracker",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(this._rebuffering)this._rebuffering=!1,this.pm.emit("rebufferend",{viewer_time:t.viewer_time});else{if(this._lastCheckedTime===null)return;var r=this.pm.data.player_playhead_time-this._lastPlayheadTime,n=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.minimumRebufferDuration=="number"&&r>0&&n-r>this.pm.minimumRebufferDuration&&(this._lastCheckedTime=null,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}),this.pm.emit("rebufferend",{viewer_time:this._lastPlayheadTimeUpdatedTime+n-r}))}i?this._prepareRebufferTrackerState(t.viewer_time):this._clearRebufferTrackerState()}}]),s}(),ph=gh,yh=function(){"use strict";function s(e){var t=this;Le(this,s),N(this,"NAVIGATION_START",void 0),N(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){var i=e.data,r=i.view_id;if(!i.view_program_changed){var n=function(a,o){var l=o.viewer_time;(a.type==="playing"&&typeof e.data.view_time_to_first_frame=="undefined"||a.type==="adplaying"&&(typeof e.data.view_time_to_first_frame=="undefined"||t._inPrerollPosition()))&&t.calculateTimeToFirstFrame(l||Se.now(),r)};e.one("playing",n),e.one("adplaying",n),e.one("viewend",function(){e.off("playing",n),e.off("adplaying",n)})}})}return Ze(s,[{key:"_inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time=="undefined"||this.pm.data.view_content_playback_time<=1e3}},{key:"calculateTimeToFirstFrame",value:function(e,t){t===this.pm.data.view_id&&(this.pm.watchTimeTracker._updateWatchTime(null,{viewer_time:e}),this.pm.data.view_time_to_first_frame=this.pm.data.view_watch_time,(this.pm.data.player_autoplay_on||this.pm.data.video_is_autoplay)&&this.NAVIGATION_START&&(this.pm.data.view_aggregate_startup_time=this.pm.data.view_start+this.pm.data.view_watch_time-this.NAVIGATION_START))}}]),s}(),vh=yh,Eh=function s(e){"use strict";var t=this;Le(this,s),N(this,"_lastPlayerHeight",void 0),N(this,"_lastPlayerWidth",void 0),N(this,"_lastPlayheadPosition",void 0),N(this,"_lastSourceHeight",void 0),N(this,"_lastSourceWidth",void 0),e.on("viewinit",function(){t._lastPlayheadPosition=-1});var i=["pause","rebufferstart","seeking","error","adbreakstart","hb"],r=["playing","hb"];i.forEach(function(n){e.on(n,function(){if(t._lastPlayheadPosition>=0&&e.data.player_playhead_time>=0&&t._lastPlayerWidth>=0&&t._lastSourceWidth>0&&t._lastPlayerHeight>=0&&t._lastSourceHeight>0){var a=e.data.player_playhead_time-t._lastPlayheadPosition;if(a<0){t._lastPlayheadPosition=-1;return}var o=Math.min(t._lastPlayerWidth/t._lastSourceWidth,t._lastPlayerHeight/t._lastSourceHeight),l=Math.max(0,o-1),c=Math.max(0,1-o);e.data.view_max_upscale_percentage=Math.max(e.data.view_max_upscale_percentage||0,l),e.data.view_max_downscale_percentage=Math.max(e.data.view_max_downscale_percentage||0,c),Ee(e.data,"view_total_content_playback_time",a),Ee(e.data,"view_total_upscaling",l*a),Ee(e.data,"view_total_downscaling",c*a)}t._lastPlayheadPosition=-1})}),r.forEach(function(n){e.on(n,function(){t._lastPlayheadPosition=e.data.player_playhead_time,t._lastPlayerWidth=e.data.player_width,t._lastPlayerHeight=e.data.player_height,t._lastSourceWidth=e.data.video_source_width,t._lastSourceHeight=e.data.video_source_height})})},Th=Eh,xh=2e3,_h=function s(e){"use strict";var t=this;Le(this,s),N(this,"isSeeking",void 0),this.isSeeking=!1;var i=-1,r=function(){var n=Se.now(),a=(e.data.viewer_time||n)-(i||n);Ee(e.data,"view_seek_duration",a),e.data.view_max_seek_time=Math.max(e.data.view_max_seek_time||0,a),t.isSeeking=!1,i=-1};e.on("seeking",function(n,a){if(Object.assign(e.data,a),t.isSeeking&&a.viewer_time-i<=xh){i=a.viewer_time;return}t.isSeeking&&r(),t.isSeeking=!0,i=a.viewer_time,Ee(e.data,"view_seek_count",1),e.send("seeking")}),e.on("seeked",function(){r()}),e.on("viewend",function(){t.isSeeking&&(r(),e.send("seeked")),t.isSeeking=!1,i=-1})},Sh=_h,Oo=function(s,e){s.push(e),s.sort(function(t,i){return t.viewer_time-i.viewer_time})},bh=["adbreakstart","adrequest","adresponse","adplay","adplaying","adpause","adended","adbreakend","aderror","adclicked","adskipped"],Ah=function(){"use strict";function s(e){var t=this;Le(this,s),N(this,"_adHasPlayed",void 0),N(this,"_adRequests",void 0),N(this,"_adResponses",void 0),N(this,"_currentAdRequestNumber",void 0),N(this,"_currentAdResponseNumber",void 0),N(this,"_prerollPlayTime",void 0),N(this,"_wouldBeNewAdPlay",void 0),N(this,"isAdBreak",void 0),N(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){t.isAdBreak=!1,t._currentAdRequestNumber=0,t._currentAdResponseNumber=0,t._adRequests=[],t._adResponses=[],t._adHasPlayed=!1,t._wouldBeNewAdPlay=!0,t._prerollPlayTime=void 0}),bh.forEach(function(r){return e.on(r,t._updateAdData.bind(t))});var i=function(){t.isAdBreak=!1};e.on("adbreakstart",function(){t.isAdBreak=!0}),e.on("play",i),e.on("playing",i),e.on("viewend",i),e.on("adrequest",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdRequestNumber++},n),Oo(t._adRequests,n),Ee(e.data,"view_ad_request_count"),t.inPrerollPosition()&&(e.data.view_preroll_requested=!0,t._adHasPlayed||Ee(e.data,"view_preroll_request_count"))}),e.on("adresponse",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdResponseNumber++},n),Oo(t._adResponses,n);var a=t.findAdRequest(n.ad_request_id);a&&Ee(e.data,"view_ad_request_time",Math.max(0,n.viewer_time-a.viewer_time))}),e.on("adplay",function(r,n){t._adHasPlayed=!0,t._wouldBeNewAdPlay&&(t._wouldBeNewAdPlay=!1,Ee(e.data,"view_ad_played_count")),t.inPrerollPosition()&&!e.data.view_preroll_played&&(e.data.view_preroll_played=!0,t._adRequests.length>0&&(e.data.view_preroll_request_time=Math.max(0,n.viewer_time-t._adRequests[0].viewer_time)),e.data.view_start&&(e.data.view_startup_preroll_request_time=Math.max(0,n.viewer_time-e.data.view_start)),t._prerollPlayTime=n.viewer_time)}),e.on("adplaying",function(r,n){t.inPrerollPosition()&&typeof e.data.view_preroll_load_time=="undefined"&&typeof t._prerollPlayTime!="undefined"&&(e.data.view_preroll_load_time=n.viewer_time-t._prerollPlayTime,e.data.view_startup_preroll_load_time=n.viewer_time-t._prerollPlayTime)}),e.on("adclicked",function(r,n){t._wouldBeNewAdPlay||Ee(e.data,"view_ad_clicked_count")}),e.on("adskipped",function(r,n){t._wouldBeNewAdPlay||Ee(e.data,"view_ad_skipped_count")}),e.on("adended",function(){t._wouldBeNewAdPlay=!0}),e.on("aderror",function(){t._wouldBeNewAdPlay=!0})}return Ze(s,[{key:"inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time=="undefined"||this.pm.data.view_content_playback_time<=1e3}},{key:"findAdRequest",value:function(e){for(var t=0;t3e4&&(e.emit("devicesleep",{viewer_time:o}),Object.assign(e.data,{viewer_time:o}),e.send("devicesleep"),e.emit("devicewake",{viewer_time:a}),Object.assign(e.data,{viewer_time:a}),e.send("devicewake"))};e.one("playbackheartbeat",i),e.on("playbackheartbeatend",function(){e.off("before*",r),e.one("playbackheartbeat",i)})},kh=Dh,Jr=qe(Je()),jo=function(s){return s()}(function(){var s=function(){for(var t=0,i={};t1){if(a=s({path:"/"},i.defaults,a),typeof a.expires=="number"){var l=new Date;l.setMilliseconds(l.getMilliseconds()+a.expires*864e5),a.expires=l}try{o=JSON.stringify(n),/^[\{\[]/.test(o)&&(n=o)}catch{}return t.write?n=t.write(n,r):n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),r=encodeURIComponent(String(r)),r=r.replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent),r=r.replace(/[\(\)]/g,escape),document.cookie=[r,"=",n,a.expires?"; expires="+a.expires.toUTCString():"",a.path?"; path="+a.path:"",a.domain?"; domain="+a.domain:"",a.secure?"; secure":""].join("")}r||(o={});for(var c=document.cookie?document.cookie.split("; "):[],u=/(%[0-9A-Z]{2})+/g,d=0;d1&&arguments[1]!==void 0?arguments[1]:{};this._beaconUrl=s||Vh,this._eventQueue=[],this._postInFlight=!1,this._failureCount=0,this._sendTimeout=!1,this._options=Object.assign({},Gh,e)};ot.prototype.queueEvent=function(s,e){var t=Object.assign({},e);return this._eventQueue.length<=this._options.maxQueueLength||s==="eventrateexceeded"?(this._eventQueue.push(t),this._sendTimeout||this._startBeaconSending(),this._eventQueue.length<=this._options.maxQueueLength):!1};ot.prototype.flushEvents=function(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(s&&this._eventQueue.length===1){this._eventQueue.pop();return}this._eventQueue.length&&this._sendBeaconQueue(),this._startBeaconSending()};ot.prototype.destroy=function(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.destroyed=!0,s?this._clearBeaconQueue():this.flushEvents(),Gt.default.clearTimeout(this._sendTimeout)};ot.prototype._clearBeaconQueue=function(){var s=this._eventQueue.length>this._options.maxBeaconSize?this._eventQueue.length-this._options.maxBeaconSize:0,e=this._eventQueue.slice(s);s>0&&Object.assign(e[e.length-1],nn({mux_view_message:"event queue truncated"}));var t=this._createPayload(e);tl(this._beaconUrl,t,!0,function(){})};ot.prototype._sendBeaconQueue=function(){var s=this;if(!this._postInFlight){var e=this._eventQueue.slice(0,this._options.maxBeaconSize);this._eventQueue=this._eventQueue.slice(this._options.maxBeaconSize),this._postInFlight=!0;var t=this._createPayload(e),i=Se.now();tl(this._beaconUrl,t,!1,function(r,n){n?(s._eventQueue=e.concat(s._eventQueue),s._failureCount+=1,ge.info("Error sending beacon: "+n)):s._failureCount=0,s._roundTripTime=Se.now()-i,s._postInFlight=!1})}};ot.prototype._getNextBeaconTime=function(){if(!this._failureCount)return this._options.baseTimeBetweenBeacons;var s=Math.pow(2,this._failureCount-1);return s=s*Math.random(),(1+s)*this._options.baseTimeBetweenBeacons};ot.prototype._startBeaconSending=function(){var s=this;Gt.default.clearTimeout(this._sendTimeout),!this.destroyed&&(this._sendTimeout=Gt.default.setTimeout(function(){s._eventQueue.length&&s._sendBeaconQueue(),s._startBeaconSending()},this._getNextBeaconTime()))};ot.prototype._createPayload=function(s){var e=this,t={transmission_timestamp:Math.round(Se.now())};this._roundTripTime&&(t.rtt_ms=Math.round(this._roundTripTime));var i,r,n,a=function(){i=JSON.stringify({metadata:t,events:r||s}),n=i.length/1024},o=function(){return n<=e._options.maxPayloadKBSize};return a(),o()||(ge.info("Payload size is too big ("+n+" kb). Removing unnecessary events."),r=s.filter(function(l){return Hh.indexOf(l.e)===-1}),a()),o()||(ge.info("Payload size still too big ("+n+" kb). Cropping fields.."),r.forEach(function(l){for(var c in l){var u=l[c],d=50*1024;typeof u=="string"&&u.length>d&&(l[c]=u.substring(0,d))}}),a()),i};var qh=function(s){return s.length<=Kh},tl=function(s,e,t,i){if(t&&navigator&&navigator.sendBeacon&&navigator.sendBeacon(s,e)){i();return}if(Gt.default.fetch){Gt.default.fetch(s,{method:"POST",body:e,headers:{"Content-Type":"text/plain"},keepalive:qh(e)}).then(function(n){return i(null,n.ok?null:"Error")}).catch(function(n){return i(null,n)});return}if(Gt.default.XMLHttpRequest){var r=new Gt.default.XMLHttpRequest;r.onreadystatechange=function(){if(r.readyState===4)return i(null,r.status!==200?"error":void 0)},r.open("POST",s),r.setRequestHeader("Content-Type","text/plain"),r.send(e);return}i()},Wh=ot,Yh=["env_key","view_id","view_sequence_number","player_sequence_number","beacon_domain","player_playhead_time","viewer_time","mux_api_version","event","video_id","player_instance_id","player_error_code","player_error_message","player_error_context","player_error_severity","player_error_business_exception"],jh=["adplay","adplaying","adpause","adfirstquartile","admidpoint","adthirdquartile","adended","adresponse","adrequest"],zh=["ad_id","ad_creative_id","ad_universal_id"],Xh=["viewstart","error","ended","viewend"],Qh=10*60*1e3,Jh=function(){"use strict";function s(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Le(this,s);var r,n,a,o,l,c,u,d,h,f,m,g;N(this,"mux",void 0),N(this,"envKey",void 0),N(this,"options",void 0),N(this,"eventQueue",void 0),N(this,"sampleRate",void 0),N(this,"disableCookies",void 0),N(this,"respectDoNotTrack",void 0),N(this,"previousBeaconData",void 0),N(this,"lastEventTime",void 0),N(this,"rateLimited",void 0),N(this,"pageLevelData",void 0),N(this,"viewerData",void 0),this.mux=e,this.envKey=t,this.options=i,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.eventQueue=new Wh(Mh(this.envKey,this.options));var p;this.sampleRate=(p=this.options.sampleRate)!==null&&p!==void 0?p:1;var v;this.disableCookies=(v=this.options.disableCookies)!==null&&v!==void 0?v:!1;var E;this.respectDoNotTrack=(E=this.options.respectDoNotTrack)!==null&&E!==void 0?E:!1,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.pageLevelData={mux_api_version:this.mux.API_VERSION,mux_embed:this.mux.NAME,mux_embed_version:this.mux.VERSION,viewer_application_name:(r=this.options.platform)===null||r===void 0?void 0:r.name,viewer_application_version:(n=this.options.platform)===null||n===void 0?void 0:n.version,viewer_application_engine:(a=this.options.platform)===null||a===void 0?void 0:a.layout,viewer_device_name:(o=this.options.platform)===null||o===void 0?void 0:o.product,viewer_device_category:"",viewer_device_manufacturer:(l=this.options.platform)===null||l===void 0?void 0:l.manufacturer,viewer_os_family:(u=this.options.platform)===null||u===void 0||(c=u.os)===null||c===void 0?void 0:c.family,viewer_os_architecture:(h=this.options.platform)===null||h===void 0||(d=h.os)===null||d===void 0?void 0:d.architecture,viewer_os_version:(m=this.options.platform)===null||m===void 0||(f=m.os)===null||f===void 0?void 0:f.version,viewer_connection_type:Fh(),page_url:Jr.default===null||Jr.default===void 0||(g=Jr.default.location)===null||g===void 0?void 0:g.href},this.viewerData=this.disableCookies?{}:Ph()}return Ze(s,[{key:"send",value:function(e,t){if(!(!e||!(t!=null&&t.view_id))){if(this.respectDoNotTrack&&sn())return ge.info("Not sending `"+e+"` because Do Not Track is enabled");if(!t||typeof t!="object")return ge.error("A data object was expected in send() but was not provided");var i=this.disableCookies?{}:Oh(),r=ln(As({},this.pageLevelData,t,i,this.viewerData),{event:e,env_key:this.envKey});r.user_id&&(r.viewer_user_id=r.user_id,delete r.user_id);var n,a=((n=r.mux_sample_number)!==null&&n!==void 0?n:0)>=this.sampleRate,o=this._deduplicateBeaconData(e,r),l=nn(o);if(this.lastEventTime=this.mux.utils.now(),a)return ge.info("Not sending event due to sample rate restriction",e,r,l);if(this.envKey||ge.info("Missing environment key (envKey) - beacons will be dropped if the video source is not a valid mux video URL",e,r,l),!this.rateLimited){if(ge.info("Sending event",e,r,l),this.rateLimited=!this.eventQueue.queueEvent(e,l),this.mux.WINDOW_UNLOADING&&e==="viewend")this.eventQueue.destroy(!0);else if(this.mux.WINDOW_HIDDEN&&e==="hb"?this.eventQueue.flushEvents(!0):Xh.indexOf(e)>=0&&this.eventQueue.flushEvents(),this.rateLimited)return r.event="eventrateexceeded",l=nn(r),this.eventQueue.queueEvent(r.event,l),ge.error("Beaconing disabled due to rate limit.")}}}},{key:"destroy",value:function(){this.eventQueue.destroy(!1)}},{key:"_deduplicateBeaconData",value:function(e,t){var i=this,r={},n=t.view_id;if(n==="-1"||e==="viewstart"||e==="viewend"||!this.previousBeaconData||this.mux.utils.now()-this.lastEventTime>=Qh)r=As({},t),n&&(this.previousBeaconData=r),n&&e==="viewend"&&(this.previousBeaconData=null);else{var a=e.indexOf("request")===0;Object.entries(t).forEach(function(o){var l=at(o,2),c=l[0],u=l[1];i.previousBeaconData&&(u!==i.previousBeaconData[c]||Yh.indexOf(c)>-1||i.objectHasChanged(a,c,u,i.previousBeaconData[c])||i.eventRequiresKey(e,c))&&(r[c]=u,i.previousBeaconData[c]=u)})}return r}},{key:"objectHasChanged",value:function(e,t,i,r){return!e||t.indexOf("request_")!==0?!1:t==="request_response_headers"||typeof i!="object"||typeof r!="object"?!0:Object.keys(i||{}).length!==Object.keys(r||{}).length}},{key:"eventRequiresKey",value:function(e,t){return!!(e==="renditionchange"&&t.indexOf("video_source_")===0||zh.includes(t)&&jh.includes(e))}}]),s}(),Zh=function s(e){"use strict";Le(this,s);var t=0,i=0,r=0,n=0,a=0,o=0,l=0,c=function(h,f){var m=f.request_start,g=f.request_response_start,p=f.request_response_end,v=f.request_bytes_loaded;n++;var E,T;if(g?(E=g-(m!=null?m:0),T=(p!=null?p:0)-g):T=(p!=null?p:0)-(m!=null?m:0),T>0&&v&&v>0){var x=v/T*8e3;a++,i+=v,r+=T,e.data.view_min_request_throughput=Math.min(e.data.view_min_request_throughput||1/0,x),e.data.view_average_request_throughput=i/r*8e3,e.data.view_request_count=n,E>0&&(t+=E,e.data.view_max_request_latency=Math.max(e.data.view_max_request_latency||0,E),e.data.view_average_request_latency=t/a)}},u=function(h,f){n++,o++,e.data.view_request_count=n,e.data.view_request_failed_count=o},d=function(h,f){n++,l++,e.data.view_request_count=n,e.data.view_request_canceled_count=l};e.on("requestcompleted",c),e.on("requestfailed",u),e.on("requestcanceled",d)},ef=Zh,tf=60*60*1e3,sf=function s(e){"use strict";var t=this;Le(this,s),N(this,"_lastEventTime",void 0),e.on("before*",function(i,r){var n=r.viewer_time,a=Se.now(),o=t._lastEventTime;if(t._lastEventTime=a,o&&a-o>tf){var l=Object.keys(e.data).reduce(function(c,u){return u.indexOf("video_")===0?Object.assign(c,N({},u,e.data[u])):c},{});e.mux.log.info("Received event after at least an hour inactivity, creating a new view"),e.emit("viewinit",Object.assign({viewer_time:n},l)),e.playbackHeartbeat._playheadShouldBeProgressing&&i.type!=="play"&&i.type!=="adbreakstart"&&(e.emit("play",{viewer_time:n}),i.type!=="playing"&&e.emit("playing",{viewer_time:n}))}})},rf=sf,nf=["viewstart","ended","loadstart","pause","play","playing","ratechange","waiting","adplay","adpause","adended","aderror","adplaying","adrequest","adresponse","adbreakstart","adbreakend","adfirstquartile","admidpoint","adthirdquartile","rebufferstart","rebufferend","seeked","error","hb","requestcompleted","requestfailed","requestcanceled","renditionchange"],af=new Set(["requestcompleted","requestfailed","requestcanceled"]),of=function(s){"use strict";Bd(t,s);var e=Kd(t);function t(i,r,n){Le(this,t);var a;a=e.call(this),N(Q(a),"DOM_CONTENT_LOADED_EVENT_END",void 0),N(Q(a),"NAVIGATION_START",void 0),N(Q(a),"_destroyed",void 0),N(Q(a),"_heartBeatTimeout",void 0),N(Q(a),"adTracker",void 0),N(Q(a),"dashjs",void 0),N(Q(a),"data",void 0),N(Q(a),"disablePlayheadRebufferTracking",void 0),N(Q(a),"disableRebufferTracking",void 0),N(Q(a),"errorTracker",void 0),N(Q(a),"errorTranslator",void 0),N(Q(a),"getAdData",void 0),N(Q(a),"getPlayheadTime",void 0),N(Q(a),"getStateData",void 0),N(Q(a),"hlsjs",void 0),N(Q(a),"id",void 0),N(Q(a),"longResumeTracker",void 0),N(Q(a),"minimumRebufferDuration",void 0),N(Q(a),"mux",void 0),N(Q(a),"oldEmit",void 0),N(Q(a),"playbackEventDispatcher",void 0),N(Q(a),"playbackHeartbeat",void 0),N(Q(a),"playbackHeartbeatTime",void 0),N(Q(a),"playheadTime",void 0),N(Q(a),"seekingTracker",void 0),N(Q(a),"sustainedRebufferThreshold",void 0),N(Q(a),"watchTimeTracker",void 0),N(Q(a),"currentFragmentPDT",void 0),N(Q(a),"currentFragmentStart",void 0),a.DOM_CONTENT_LOADED_EVENT_END=bs.domContentLoadedEventEnd(),a.NAVIGATION_START=bs.navigationStart();var o={debug:!1,minimumRebufferDuration:250,sustainedRebufferThreshold:1e3,playbackHeartbeatTime:25,beaconDomain:"litix.io",sampleRate:1,disableCookies:!1,respectDoNotTrack:!1,disableRebufferTracking:!1,disablePlayheadRebufferTracking:!1,errorTranslator:function(f){return f}};a.mux=i,a.id=r,n!=null&&n.beaconDomain&&a.mux.log.warn("The `beaconDomain` setting has been deprecated in favor of `beaconCollectionDomain`. Please change your integration to use `beaconCollectionDomain` instead of `beaconDomain`."),n=Object.assign(o,n),n.data=n.data||{},n.data.property_key&&(n.data.env_key=n.data.property_key,delete n.data.property_key),ge.level=n.debug?$t.DEBUG:$t.WARN,a.getPlayheadTime=n.getPlayheadTime,a.getStateData=n.getStateData||function(){return{}},a.getAdData=n.getAdData||function(){},a.minimumRebufferDuration=n.minimumRebufferDuration,a.sustainedRebufferThreshold=n.sustainedRebufferThreshold,a.playbackHeartbeatTime=n.playbackHeartbeatTime,a.disableRebufferTracking=n.disableRebufferTracking,a.disableRebufferTracking&&a.mux.log.warn("Disabling rebuffer tracking. This should only be used in specific circumstances as a last resort when your player is known to unreliably track rebuffering."),a.disablePlayheadRebufferTracking=n.disablePlayheadRebufferTracking,a.errorTranslator=n.errorTranslator,a.playbackEventDispatcher=new Jh(i,n.data.env_key,n),a.data={player_instance_id:Bi(),mux_sample_rate:n.sampleRate,beacon_domain:n.beaconCollectionDomain||n.beaconDomain},a.data.view_sequence_number=1,a.data.player_sequence_number=1,a.oldEmit=a.emit,a.emit=function(f,m){m=Object.assign({viewer_time:this.mux.utils.now()},m),this.oldEmit(f,m)};var l=function(){typeof this.data.view_start=="undefined"&&(this.data.view_start=this.mux.utils.now(),this.emit("viewstart"))}.bind(Q(a));a.on("viewinit",function(f,m){this._resetVideoData(),this._resetViewData(),this._resetErrorData(),this._updateStateData(),Object.assign(this.data,m),this._initializeViewData(),this.one("play",l),this.one("adbreakstart",l)});var c=function(f){this.emit("viewend"),this.send("viewend"),this.emit("viewinit",f)}.bind(Q(a));if(a.on("videochange",function(f,m){c(m)}),a.on("programchange",function(f,m){this.data.player_is_paused&&this.mux.log.warn("The `programchange` event is intended to be used when the content changes mid playback without the video source changing, however the video is not currently playing. If the video source is changing please use the videochange event otherwise you will lose startup time information."),c(Object.assign(m,{view_program_changed:!0})),l(),this.emit("play"),this.emit("playing")}),a.on("fragmentchange",function(f,m){this.currentFragmentPDT=m.currentFragmentPDT,this.currentFragmentStart=m.currentFragmentStart}),a.on("destroy",a.destroy),typeof window!="undefined"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"){var u=function(){var f=typeof a.data.view_start!="undefined";a.mux.WINDOW_HIDDEN=document.visibilityState==="hidden",f&&a.mux.WINDOW_HIDDEN&&(a.data.player_is_paused||a.emit("hb"))};window.addEventListener("visibilitychange",u,!1);var d=function(f){f.persisted||a.destroy()};window.addEventListener("pagehide",d,!1),a.on("destroy",function(){window.removeEventListener("visibilitychange",u),window.removeEventListener("pagehide",d)})}a.on("playerready",function(f,m){Object.assign(this.data,m)}),nf.forEach(function(f){a.on(f,function(m,g){f.indexOf("ad")!==0&&this._updateStateData(),Object.assign(this.data,g),this._sanitizeData()}),a.on("after"+f,function(){(f!=="error"||this.errorTracker.viewErrored)&&this.send(f)})}),a.on("viewend",function(f,m){Object.assign(a.data,m)});var h=function(f){var m=this.mux.utils.now();this.data.player_init_time&&(this.data.player_startup_time=m-this.data.player_init_time),!this.mux.PLAYER_TRACKED&&this.NAVIGATION_START&&(this.mux.PLAYER_TRACKED=!0,(this.data.player_init_time||this.DOM_CONTENT_LOADED_EVENT_END)&&(this.data.page_load_time=Math.min(this.data.player_init_time||1/0,this.DOM_CONTENT_LOADED_EVENT_END||1/0)-this.NAVIGATION_START)),this.send("playerready"),delete this.data.player_startup_time,delete this.data.page_load_time};return a.one("playerready",h),a.longResumeTracker=new rf(Q(a)),a.errorTracker=new ah(Q(a)),new kh(Q(a)),a.seekingTracker=new Sh(Q(a)),a.playheadTime=new hh(Q(a)),a.playbackHeartbeat=new rh(Q(a)),new Th(Q(a)),a.watchTimeTracker=new lh(Q(a)),new uh(Q(a)),a.adTracker=new Rh(Q(a)),new ph(Q(a)),new mh(Q(a)),new vh(Q(a)),new Ih(Q(a)),new ef(Q(a)),n.hlsjs&&a.addHLSJS(n),n.dashjs&&a.addDashJS(n),a.emit("viewinit",n.data),a}return Ze(t,[{key:"destroy",value:function(){this._destroyed||(this._destroyed=!0,typeof this.data.view_start!="undefined"&&(this.emit("viewend"),this.send("viewend")),this.playbackEventDispatcher.destroy(),this.removeHLSJS(),this.removeDashJS(),window.clearTimeout(this._heartBeatTimeout))}},{key:"send",value:function(i){if(this.data.view_id){var r=Object.assign({},this.data),n=["player_program_time","player_manifest_newest_program_time","player_live_edge_program_time","player_program_time","video_holdback","video_part_holdback","video_target_duration","video_part_target_duration"];if(r.video_source_is_live===void 0&&(r.player_source_duration===1/0||r.video_source_duration===1/0?r.video_source_is_live=!0:(r.player_source_duration>0||r.video_source_duration>0)&&(r.video_source_is_live=!1)),r.video_source_is_live||n.forEach(function(c){r[c]=void 0}),r.video_source_url=r.video_source_url||r.player_source_url,r.video_source_url){var a=at($i(r.video_source_url),2),o=a[0],l=a[1];r.video_source_domain=l,r.video_source_hostname=o}delete r.ad_request_id,this.playbackEventDispatcher.send(i,r),this.data.view_sequence_number++,this.data.player_sequence_number++,af.has(i)||this._restartHeartBeat(),i==="viewend"&&delete this.data.view_id}}},{key:"_updateStateData",value:function(){Object.assign(this.data,this.getStateData()),this.playheadTime._updatePlayheadTime(),this._sanitizeData()}},{key:"_sanitizeData",value:function(){var i=this,r=["player_width","player_height","video_source_width","video_source_height","player_playhead_time","video_source_bitrate"];r.forEach(function(a){var o=parseInt(i.data[a],10);i.data[a]=isNaN(o)?void 0:o});var n=["player_source_url","video_source_url"];n.forEach(function(a){if(i.data[a]){var o=i.data[a].toLowerCase();(o.indexOf("data:")===0||o.indexOf("blob:")===0)&&(i.data[a]="MSE style URL")}})}},{key:"_resetVideoData",value:function(){var i=this;Object.keys(this.data).forEach(function(r){r.indexOf("video_")===0&&delete i.data[r]})}},{key:"_resetViewData",value:function(){var i=this;Object.keys(this.data).forEach(function(r){r.indexOf("view_")===0&&delete i.data[r]}),this.data.view_sequence_number=1}},{key:"_resetErrorData",value:function(){delete this.data.player_error_code,delete this.data.player_error_message,delete this.data.player_error_context,delete this.data.player_error_severity,delete this.data.player_error_business_exception}},{key:"_initializeViewData",value:function(){var i=this,r=this.data.view_id=Bi(),n=function(){r===i.data.view_id&&Ee(i.data,"player_view_count",1)};this.data.player_is_paused?this.one("play",n):n()}},{key:"_restartHeartBeat",value:function(){var i=this;window.clearTimeout(this._heartBeatTimeout),this._heartBeatTimeout=window.setTimeout(function(){i.data.player_is_paused||i.emit("hb")},1e4)}},{key:"addHLSJS",value:function(i){if(!i.hlsjs){this.mux.log.warn("You must pass a valid hlsjs instance in order to track it.");return}if(this.hlsjs){this.mux.log.warn("An instance of HLS.js is already being monitored for this player.");return}this.hlsjs=i.hlsjs,jd(this.mux,this.id,i.hlsjs,{},i.Hls||window.Hls)}},{key:"removeHLSJS",value:function(){this.hlsjs&&(zd(this.hlsjs),this.hlsjs=void 0)}},{key:"addDashJS",value:function(i){if(!i.dashjs){this.mux.log.warn("You must pass a valid dashjs instance in order to track it.");return}if(this.dashjs){this.mux.log.warn("An instance of Dash.js is already being monitored for this player.");return}this.dashjs=i.dashjs,Zd(this.mux,this.id,i.dashjs)}},{key:"removeDashJS",value:function(){this.dashjs&&(eh(this.dashjs),this.dashjs=void 0)}}]),t}(ih),lf=of;on();var Ni=qe(Dd());function cf(){return Ni.default&&!!(Ni.default.fullscreenElement||Ni.default.webkitFullscreenElement||Ni.default.mozFullScreenElement||Ni.default.msFullscreenElement)}var uf=["loadstart","pause","play","playing","seeking","seeked","timeupdate","ratechange","stalled","waiting","error","ended"],df={1:"MEDIA_ERR_ABORTED",2:"MEDIA_ERR_NETWORK",3:"MEDIA_ERR_DECODE",4:"MEDIA_ERR_SRC_NOT_SUPPORTED"};function hf(s,e,t){var i=at(tn(e),3),r=i[0],n=i[1],a=i[2],o=s.log,l=s.utils.getComputedStyle,c=s.utils.secondsToMs,u={automaticErrorTracking:!0};if(r){if(a!=="video"&&a!=="audio")return o.error("The element of `"+n+"` was not a media element.")}else return o.error("No element was found with the `"+n+"` query selector.");r.mux&&(r.mux.destroy(),delete r.mux,o.warn("Already monitoring this video element, replacing existing event listeners")),t=Object.assign(u,t),t.data=Object.assign({player_software:"HTML5 Video Element",player_mux_plugin_name:"VideoElementMonitor",player_mux_plugin_version:s.VERSION},t.data),t.getPlayheadTime=function(){return c(r.currentTime)},t.getStateData=function(){var h,f=this.hlsjs&&this.hlsjs.url,m=this.dashjs&&an(this.dashjs.getSource==="function")&&this.dashjs.getSource(),g={player_is_paused:r.paused,player_playhead_time:c(r.currentTime),player_width:parseInt(l(r,"width")),player_height:parseInt(l(r,"height")),player_autoplay_on:r.autoplay,player_preload_on:r.preload,player_language_code:r.lang,player_is_fullscreen:cf(),video_poster_url:r.poster,video_source_url:f||m||r.currentSrc,video_source_duration:c(r.duration),video_source_height:r.videoHeight,video_source_width:r.videoWidth,view_dropped_frame_count:r==null||(h=r.getVideoPlaybackQuality)===null||h===void 0?void 0:h.call(r).droppedVideoFrames},p=t.getPlayheadTime();if(r.getStartDate&&p>0){var v=r.getStartDate();if(v&&typeof v.getTime=="function"&&v.getTime()){var E=v.getTime();if(g.player_program_time=E+p,r.seekable.length>0){var T=E+r.seekable.end(r.seekable.length-1);g.player_live_edge_program_time=T}}}return g},r.mux=r.mux||{},r.mux.deleted=!1,r.mux.emit=function(h,f){s.emit(n,h,f)};var d=function(){o.error("The monitor for this video element has already been destroyed.")};r.mux.destroy=function(){Object.keys(r.mux.listeners).forEach(function(h){r.removeEventListener(h,r.mux.listeners[h],!1)}),delete r.mux.listeners,r.mux.destroy=d,r.mux.swapElement=d,r.mux.emit=d,r.mux.addHLSJS=d,r.mux.addDashJS=d,r.mux.removeHLSJS=d,r.mux.removeDashJS=d,r.mux.deleted=!0,s.emit(n,"destroy")},r.mux.swapElement=function(h){var f=at(tn(h),3),m=f[0],g=f[1],p=f[2];if(m){if(p!=="video"&&p!=="audio")return s.log.error("The element of `"+g+"` was not a media element.")}else return s.log.error("No element was found with the `"+g+"` query selector.");m.muxId=r.muxId,delete r.muxId,m.mux=m.mux||{},m.mux.listeners=Object.assign({},r.mux.listeners),delete r.mux.listeners,Object.keys(m.mux.listeners).forEach(function(v){r.removeEventListener(v,m.mux.listeners[v],!1),m.addEventListener(v,m.mux.listeners[v],!1)}),m.mux.swapElement=r.mux.swapElement,m.mux.destroy=r.mux.destroy,delete r.mux,r=m},r.mux.addHLSJS=function(h){s.addHLSJS(n,h)},r.mux.addDashJS=function(h){s.addDashJS(n,h)},r.mux.removeHLSJS=function(){s.removeHLSJS(n)},r.mux.removeDashJS=function(){s.removeDashJS(n)},s.init(n,t),s.emit(n,"playerready"),r.paused||(s.emit(n,"play"),r.readyState>2&&s.emit(n,"playing")),r.mux.listeners={},uf.forEach(function(h){h==="error"&&!t.automaticErrorTracking||(r.mux.listeners[h]=function(){var f={};if(h==="error"){if(!r.error||r.error.code===1)return;f.player_error_code=r.error.code,f.player_error_message=df[r.error.code]||r.error.message}s.emit(n,h,f)},r.addEventListener(h,r.mux.listeners[h],!1))})}function ff(s,e,t,i){var r=i;if(s&&typeof s[e]=="function")try{r=s[e].apply(s,t)}catch(n){ge.info("safeCall error",n)}return r}var Ui=qe(Je()),oi;Ui.default&&Ui.default.WeakMap&&(oi=new WeakMap);function mf(s,e){if(!s||!e||!Ui.default||typeof Ui.default.getComputedStyle!="function")return"";var t;return oi&&oi.has(s)&&(t=oi.get(s)),t||(t=Ui.default.getComputedStyle(s,null),oi&&oi.set(s,t)),t.getPropertyValue(e)}function gf(s){return Math.floor(s*1e3)}var Ut={TARGET_DURATION:"#EXT-X-TARGETDURATION",PART_INF:"#EXT-X-PART-INF",SERVER_CONTROL:"#EXT-X-SERVER-CONTROL",INF:"#EXTINF",PROGRAM_DATE_TIME:"#EXT-X-PROGRAM-DATE-TIME",VERSION:"#EXT-X-VERSION",SESSION_DATA:"#EXT-X-SESSION-DATA"},Ls=function(s){return this.buffer="",this.manifest={segments:[],serverControl:{},sessionData:{}},this.currentUri={},this.process(s),this.manifest};Ls.prototype.process=function(s){var e;for(this.buffer+=s,e=this.buffer.indexOf(` `);e>-1;e=this.buffer.indexOf(` `))this.processLine(this.buffer.substring(0,e)),this.buffer=this.buffer.substring(e+1)};Ls.prototype.processLine=function(s){var e=s.indexOf(":"),t=Ef(s,e),i=t[0],r=t.length===2?un(t[1]):void 0;if(i[0]!=="#")this.currentUri.uri=i,this.manifest.segments.push(this.currentUri),this.manifest.targetDuration&&!("duration"in this.currentUri)&&(this.currentUri.duration=this.manifest.targetDuration),this.currentUri={};else switch(i){case Ut.TARGET_DURATION:{if(!isFinite(r)||r<0)return;this.manifest.targetDuration=r,this.setHoldBack();break}case Ut.PART_INF:{Zr(this.manifest,t),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),this.setHoldBack();break}case Ut.SERVER_CONTROL:{Zr(this.manifest,t),this.setHoldBack();break}case Ut.INF:{r===0?this.currentUri.duration=.01:r>0&&(this.currentUri.duration=r);break}case Ut.PROGRAM_DATE_TIME:{var n=r,a=new Date(n);this.manifest.dateTimeString||(this.manifest.dateTimeString=n,this.manifest.dateTimeObject=a),this.currentUri.dateTimeString=n,this.currentUri.dateTimeObject=a;break}case Ut.VERSION:{Zr(this.manifest,t);break}case Ut.SESSION_DATA:{var o=Tf(t[1]),l=Yo(o);Object.assign(this.manifest.sessionData,l)}}};Ls.prototype.setHoldBack=function(){var s=this.manifest,e=s.serverControl,t=s.targetDuration,i=s.partTargetDuration;if(e){var r="holdBack",n="partHoldBack",a=t&&t*3,o=i&&i*2;t&&!e.hasOwnProperty(r)&&(e[r]=a),a&&e[r]1){var i=il(t[0]);e[i]=un(t[1])}return e},yf=function(s){for(var e=s.split(","),t={},i=0;e.length>i;i++){var r=e[i],n=pf(r);t=Object.assign(n,t)}return t},vf=function(s){return s.indexOf("=")>-1},Ef=function(s,e){return e===-1?[s]:[s.substring(0,e),s.substring(e+1)]},Tf=function(s){var e={};if(s){var t=s.search(","),i=s.slice(0,t),r=s.slice(t+1),n=[i,r];return n.forEach(function(a,o){for(var l=a.replace(/['"]+/g,"").split("="),c=0;c`):qt}function Ff(s,...e){e.forEach(function(t){Hi[t]=s[t]?s[t].bind(s):Nf(t)})}function Uf(s,e){if(typeof console=="object"&&s===!0||typeof s=="object"){Ff(s,"debug","log","info","warn","error");try{Hi.log(`Debug logs enabled for "${e}" in hls.js version 1.5.15`)}catch{Hi=kn}}else Hi=kn}var A=Hi,Bf=/^(\d+)x(\d+)$/,rl=/(.+?)=(".*?"|.*?)(?:,|$)/g,pe=class s{constructor(e){typeof e=="string"&&(e=s.parseAttrList(e)),Te(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;let i=new Uint8Array(t.length/2);for(let r=0;rNumber.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){let t=Bf.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,i={},r='"';for(rl.lastIndex=0;(t=rl.exec(e))!==null;){let n=t[2];n.indexOf(r)===0&&n.lastIndexOf(r)===n.length-1&&(n=n.slice(1,-1));let a=t[1].trim();i[a]=n}return i}};function $f(s){return s!=="ID"&&s!=="CLASS"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function Gf(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"}var Ws=class{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){let i=t.attr;for(let r in i)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==i[r]){A.warn(`DATERANGE tag attribute: "${r}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=r;break}e=Te(new pe({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){let i=new Date(this.attr["END-DATE"]);K(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;let e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(K(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&K(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}},pi=class{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},le={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Ys=class{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[le.AUDIO]:null,[le.VIDEO]:null,[le.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){let i=e.split("@",2),r;i.length===1?r=(t==null?void 0:t.byteRangeEndOffset)||0:r=parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ba.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}},Vi=class extends Ys{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new pi,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get decryptdata(){let{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){let t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{let i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!K(this.programDateTime))return null;let e=K(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){let t=Object.keys(this.levelkeys),i=t.length;if(i>1||i===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){let t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,r,n,a=!1){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n)}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[le.AUDIO]=null,e[le.VIDEO]=null,e[le.AUDIOVIDEO]=null}},wn=class extends Ys{constructor(e,t,i,r,n){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new pi,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}},Kf=10,Cn=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?K(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Kf}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}};function $a(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Hf(s){let e=Pn(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Vf(s){let e=function(i,r,n){let a=i[r];i[r]=i[n],i[n]=a};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function qf(s){let e=s.split(":"),t=null;if(e[0]==="data"&&e.length===2){let i=e[1].split(";"),r=i[i.length-1].split(",");if(r.length===2){let n=r[0]==="base64",a=r[1];n?(i.splice(-1,1),t=$a(a)):t=Hf(a)}}return t}function Pn(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}var yi=typeof self!="undefined"?self:void 0,de={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Fe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function nl(s){switch(s){case Fe.FAIRPLAY:return de.FAIRPLAY;case Fe.PLAYREADY:return de.PLAYREADY;case Fe.WIDEVINE:return de.WIDEVINE;case Fe.CLEARKEY:return de.CLEARKEY}}var Ki={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",FAIRPLAY:"94ce86fb07ff4f43adb893d2fa968ca2",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function al(s){if(s===Ki.WIDEVINE)return de.WIDEVINE;if(s===Ki.PLAYREADY)return de.PLAYREADY;if(s===Ki.CENC||s===Ki.CLEARKEY)return de.CLEARKEY}function ol(s){switch(s){case de.FAIRPLAY:return Fe.FAIRPLAY;case de.PLAYREADY:return Fe.PLAYREADY;case de.WIDEVINE:return Fe.WIDEVINE;case de.CLEARKEY:return Fe.CLEARKEY}}function dn(s){let{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[de.FAIRPLAY,de.WIDEVINE,de.PLAYREADY,de.CLEARKEY].filter(r=>!!e[r]):[];return!i[de.WIDEVINE]&&t&&i.push(de.WIDEVINE),i}var Zl=function(s){return yi!=null&&(s=yi.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Wf(s,e,t,i){let r;switch(s){case de.FAIRPLAY:r=["cenc","sinf"];break;case de.WIDEVINE:case de.PLAYREADY:r=["cenc"];break;case de.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return Yf(r,e,t,i)}function Yf(s,e,t,i){return[{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs="${n}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs="${n}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function jt(s,e,t){return Uint8Array.prototype.slice?s.slice(e,t):new Uint8Array(Array.prototype.slice.call(s,e,t))}var Ga=(s,e)=>e+10<=s.length&&s[e]===73&&s[e+1]===68&&s[e+2]===51&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128,ec=(s,e)=>e+10<=s.length&&s[e]===51&&s[e+1]===68&&s[e+2]===73&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128,Wi=(s,e)=>{let t=e,i=0;for(;Ga(s,e);){i+=10;let r=Er(s,e+6);i+=r,ec(s,e+10)&&(i+=10),e+=i}if(i>0)return s.subarray(t,t+i)},Er=(s,e)=>{let t=0;return t=(s[e]&127)<<21,t|=(s[e+1]&127)<<14,t|=(s[e+2]&127)<<7,t|=s[e+3]&127,t},jf=(s,e)=>Ga(s,e)&&Er(s,e+6)+10<=s.length-e,Ka=s=>{let e=ic(s);for(let t=0;ts&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp",zf=s=>{let e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=Er(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}},ic=s=>{let e=0,t=[];for(;Ga(s,e);){let i=Er(s,e+6);e+=10;let r=e+i;for(;e+8s.type==="PRIV"?Qf(s):s.type[0]==="W"?Zf(s):Jf(s),Qf=s=>{if(s.size<2)return;let e=rt(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}},Jf=s=>{if(s.size<2)return;if(s.type==="TXXX"){let t=1,i=rt(s.data.subarray(t),!0);t+=i.length+1;let r=rt(s.data.subarray(t));return{key:s.type,info:i,data:r}}let e=rt(s.data.subarray(1));return{key:s.type,data:e}},Zf=s=>{if(s.type==="WXXX"){if(s.size<2)return;let t=1,i=rt(s.data.subarray(t),!0);t+=i.length+1;let r=rt(s.data.subarray(t));return{key:s.type,info:i,data:r}}let e=rt(s.data);return{key:s.type,data:e}},em=s=>{if(s.data.byteLength===8){let e=new Uint8Array(s.data),t=e[3]&1,i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}},rt=(s,e=!1)=>{let t=tm();if(t){let c=t.decode(s);if(e){let u=c.indexOf("\0");return u!==-1?c.substring(0,u):c}return c.replace(/\0/g,"")}let i=s.length,r,n,a,o="",l=0;for(;l>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:n=s[l++],o+=String.fromCharCode((r&31)<<6|n&63);break;case 14:n=s[l++],a=s[l++],o+=String.fromCharCode((r&15)<<12|(n&63)<<6|(a&63)<<0);break}}return o},hn;function tm(){if(!navigator.userAgent.includes("PlayStation 4"))return!hn&&typeof self.TextDecoder!="undefined"&&(hn=new self.TextDecoder("utf-8")),hn}var tt={hexDump:function(s){let e="";for(let t=0;t>24,s[e+1]=t>>16&255,s[e+2]=t>>8&255,s[e+3]=t&255}function sm(s){let e=s.byteLength;for(let t=0;t8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return!0;t=i>1?t+i:e}return!1}function J(s,e){let t=[];if(!e.length)return t;let i=s.byteLength;for(let r=0;r1?r+n:i;if(a===e[0])if(e.length===1)t.push(s.subarray(r+8,o));else{let l=J(s.subarray(r+8,o),e.slice(1));l.length&&im.apply(t,l)}r=o}return t}function rm(s){let e=[],t=s[0],i=8,r=Y(s,i);i+=4;let n=0,a=0;t===0?(n=Y(s,i),a=Y(s,i+4),i+=8):(n=ll(s,i),a=ll(s,i+8),i+=16),i+=2;let o=s.length+a,l=rc(s,i);i+=2;for(let c=0;c>>31===1)return A.warn("SIDX has hierarchical references (not supported)"),null;let m=Y(s,u);u+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+h-1}}),o+=h,u+=4,i=u}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function ac(s){let e=[],t=J(s,["moov","trak"]);for(let r=0;r{let n=Y(r,4),a=e[n];a&&(a.default={duration:Y(r,12),flags:Y(r,20)})}),e}function nm(s){let e=s.subarray(8),t=e.subarray(86),i=be(e.subarray(4,8)),r=i,n=i==="enca"||i==="encv";if(n){let o=J(e,[i])[0].subarray(i==="enca"?28:78);J(o,["sinf"]).forEach(c=>{let u=J(c,["schm"])[0];if(u){let d=be(u.subarray(4,8));if(d==="cbcs"||d==="cenc"){let h=J(c,["frma"])[0];h&&(r=be(h))}}})}switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{let a=J(t,["avcC"])[0];r+="."+Ds(a[1])+Ds(a[2])+Ds(a[3]);break}case"mp4a":{let a=J(e,[i])[0],o=J(a.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(o[l++]!==3)break;l=mn(o,l),l+=2;let c=o[l++];if(c&128&&(l+=2),c&64&&(l+=o[l++]),o[l++]!==4)break;l=mn(o,l);let u=o[l++];if(u===64)r+="."+Ds(u);else break;if(l+=12,o[l++]!==5)break;l=mn(o,l);let d=o[l++],h=(d&248)>>3;h===31&&(h+=1+((d&7)<<3)+((o[l]&224)>>5)),r+="."+h}break}case"hvc1":case"hev1":{let a=J(t,["hvcC"])[0],o=a[1],l=["","A","B","C"][o>>6],c=o&31,u=Y(a,2),d=(o&32)>>5?"H":"L",h=a[12],f=a.subarray(6,12);r+="."+l+c,r+="."+u.toString(16).toUpperCase(),r+="."+d+h;let m="";for(let g=f.length;g--;){let p=f[g];(p||m)&&(m="."+p.toString(16).toUpperCase()+m)}r+=m;break}case"dvh1":case"dvhe":{let a=J(t,["dvcC"])[0],o=a[2]>>1&127,l=a[2]<<5&32|a[3]>>3&31;r+="."+et(o)+"."+et(l);break}case"vp09":{let a=J(t,["vpcC"])[0],o=a[4],l=a[5],c=a[6]>>4&15;r+="."+et(o)+"."+et(l)+"."+et(c);break}case"av01":{let a=J(t,["av1C"])[0],o=a[1]>>>5,l=a[1]&31,c=a[2]>>>7?"H":"M",u=(a[2]&64)>>6,d=(a[2]&32)>>5,h=o===2&&u?d?12:10:u?10:8,f=(a[2]&16)>>4,m=(a[2]&8)>>3,g=(a[2]&4)>>2,p=a[2]&3;r+="."+o+"."+et(l)+c+"."+et(h)+"."+f+"."+m+g+p+"."+et(1)+"."+et(1)+"."+et(1)+"."+0;break}}return{codec:r,encrypted:n}}function mn(s,e){let t=e+5;for(;s[e++]&128&&e{let a=J(r,["mdia","minf","stbl","stsd"])[0].subarray(8),o=J(a,["enca"]),l=o.length>0;l||(o=J(a,["encv"])),o.forEach(c=>{let u=l?c.subarray(28):c.subarray(78);J(u,["sinf"]).forEach(h=>{let f=oc(h);if(f){let m=f.subarray(8,24);m.some(g=>g!==0)||(A.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${tt.hexDump(m)} -> ${tt.hexDump(t)}`),f.set(t,8))}})})}),s}function oc(s){let e=J(s,["schm"])[0];if(e){let t=be(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return J(s,["schi","tenc"])[0]}return null}function om(s,e){return J(e,["moof","traf"]).reduce((t,i)=>{let r=J(i,["tfdt"])[0],n=r[0],a=J(i,["tfhd"]).reduce((o,l)=>{let c=Y(l,4),u=s[c];if(u){let d=Y(r,4);if(n===1){if(d===js)return A.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;d*=js+1,d+=Y(r,8)}let h=u.timescale||9e4,f=d/h;if(K(f)&&(o===null||ff+m.info.duration||0,0);o=Math.max(o,h+d.earliestPresentationTime/d.timescale),l=o-a}}if(l&&K(l))return l}return i||r}function cm(s){let e=Y(s,0),t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0,r=Y(s,4);for(let n=0;n{J(i,["tfhd"]).forEach(r=>{let n=Y(r,4),a=s[n];if(!a)return;let o=a.timescale||9e4;J(i,["tfdt"]).forEach(l=>{let c=l[0],u=t*o;if(u){let d=Y(l,4);if(c===0)d-=u,d=Math.max(d,0),fn(l,4,d);else{d*=Math.pow(2,32),d+=Y(l,8),d-=u,d=Math.max(d,0);let h=Math.floor(d/(js+1)),f=Math.floor(d%(js+1));fn(l,4,h),fn(l,8,f)}}})})})}function dm(s){let e={valid:null,remainder:null},t=J(s,["moof"]);if(t.length<2)return e.remainder=s,e;let i=t[t.length-1];return e.valid=jt(s,0,i.byteOffset-8),e.remainder=jt(s,i.byteOffset-8),e}function He(s,e){let t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function cl(s,e){let t=[],i=e.samples,r=e.timescale,n=e.id,a=!1;return J(i,["moof"]).map(l=>{let c=l.byteOffset-8;J(l,["traf"]).map(d=>{let h=J(d,["tfdt"]).map(f=>{let m=f[0],g=Y(f,4);return m===1&&(g*=Math.pow(2,32),g+=Y(f,8)),g/r})[0];return h!==void 0&&(s=h),J(d,["tfhd"]).map(f=>{let m=Y(f,4),g=Y(f,0)&16777215,p=(g&1)!==0,v=(g&2)!==0,E=(g&8)!==0,T=0,x=(g&16)!==0,_=0,I=(g&32)!==0,b=8;m===n&&(p&&(b+=8),v&&(b+=4),E&&(T=Y(f,b),b+=4),x&&(_=Y(f,b),b+=4),I&&(b+=4),e.type==="video"&&(a=hm(e.codec)),J(d,["trun"]).map(R=>{let k=R[0],L=Y(R,0)&16777215,w=(L&1)!==0,P=0,O=(L&4)!==0,W=(L&256)!==0,q=0,$=(L&512)!==0,Z=0,ne=(L&1024)!==0,H=(L&2048)!==0,B=0,ee=Y(R,4),X=8;w&&(P=Y(R,X),X+=4),O&&(X+=4);let ae=P+c;for(let ye=0;ye>1&63;return t===39||t===40}else return(e&31)===6}function lc(s,e,t,i){let r=cc(s),n=0;n+=e;let a=0,o=0,l=0;for(;n=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);let c=r.length-n,u=n;if(oc){A.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(r[u++]===181){let h=rc(r,u);if(u+=2,h===49){let f=Y(r,u);if(u+=4,f===1195456820){let m=r[u++];if(m===3){let g=r[u++],p=31&g,v=64&g,E=v?2+p*3:0,T=new Uint8Array(E);if(v){T[0]=g;for(let x=1;x16){let d=[];for(let m=0;m<16;m++){let g=r[u++].toString(16);d.push(g.length==1?"0"+g:g),(m===3||m===5||m===7||m===9)&&d.push("-")}let h=o-16,f=new Uint8Array(h);for(let m=0;m>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(s,4),r=0,i=8;r0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;let a=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),gm([112,115,115,104],new Uint8Array([i,0,0,0]),s,n,r,a,t||new Uint8Array)}function ym(s){let e=[];if(s instanceof ArrayBuffer){let t=s.byteLength,i=0;for(;i+32>>24;if(n!==0&&n!==1)return{offset:t,size:e};let a=s.buffer,o=tt.hexDump(new Uint8Array(a,t+12,16)),l=s.getUint32(28),c=null,u=null;if(n===0){if(e-32=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Fe.PLAYREADY:{let i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=pm(i,null,t);let r=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),n=String.fromCharCode.apply(null,Array.from(r)),a=n.substring(n.indexOf("<"),n.length),c=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("KID")[0];if(c){let u=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(u){let d=$a(u).subarray(0,16);Vf(d),this.keyId=d}}break}default:{let i=t.subarray(0,16);if(i.length!==16){let r=new Uint8Array(16);r.set(i,16-i.length),i=r}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=ks[this.uri];if(!i){let r=Object.keys(ks).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,r),ks[this.uri]=i}this.keyId=i}return this}};function Em(s){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}var uc=/\{\$([a-zA-Z0-9-_]+)\}/g;function ul(s){return uc.test(s)}function Me(s,e,t){if(s.variableList!==null||s.hasVariableRefs)for(let i=t.length;i--;){let r=t[i],n=e[r];n&&(e[r]=On(s,n))}}function On(s,e){if(s.variableList!==null||s.hasVariableRefs){let t=s.variableList;return e.replace(uc,i=>{let r=i.substring(2,i.length-1),n=t==null?void 0:t[r];return n===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),i):n})}return e}function dl(s,e,t){let i=s.variableList;i||(s.variableList=i={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=e.NAME,n=e.VALUE;r in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):i[r]=n||""}function Tm(s,e,t){let i=e.IMPORT;if(t&&i in t){let r=s.variableList;r||(s.variableList=r={}),r[i]=t[i]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function zt(s=!0){return typeof self=="undefined"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function xm(s){return typeof self!="undefined"&&s===self.ManagedMediaSource}var zs={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function _m(s,e){let t=zs[e];return!!t&&!!t[s.slice(0,4)]}function gn(s,e,t=!0){return!s.split(",").some(i=>!dc(i,e,t))}function dc(s,e,t=!0){var i;let r=zt(t);return(i=r==null?void 0:r.isTypeSupported(ji(s,e)))!=null?i:!1}function ji(s,e){return`${e}/mp4;codecs="${s}"`}function hl(s){if(s){let e=s.substring(0,4);return zs.video[e]}return 2}function Xs(s){return s.split(",").reduce((e,t)=>{let i=zs.video[t];return i?(i*2+e)/(e?3:2):(zs.audio[t]+e)/(e?2:1)},0)}var pn={};function Sm(s,e=!0){if(pn[s])return pn[s];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[s];for(let i=0;iSm(t.toLowerCase(),e))}function fl(s,e){return s&&s!=="mp4a"?s:e&&e.split(",")[0]}function Am(s){let e=s.split(",");for(let t=0;t2){let r=i.shift()+".";r+=parseInt(i.shift()).toString(16),r+=("000"+parseInt(i.shift()).toString(16)).slice(-4),e[t]=r}}return e.join(",")}var ml=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,gl=/#EXT-X-MEDIA:(.*)/g,Rm=/^#EXT(?:INF|-X-TARGETDURATION):/m,pl=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Lm=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Wt=class s{static findGroup(e,t){for(let i=0;i0&&n.length({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(gl.lastIndex=0;(r=gl.exec(e))!==null;){let c=new pe(r[1]),u=c.TYPE;if(u){let d=o[u],h=n[u]||[];n[u]=h,Me(i,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);let f=c.LANGUAGE,m=c["ASSOC-LANGUAGE"],g=c.CHANNELS,p=c.CHARACTERISTICS,v=c["INSTREAM-ID"],E={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:u,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?s.resolve(c.URI,t):""};if(m&&(E.assocLang=m),g&&(E.channels=g),p&&(E.characteristics=p),v&&(E.instreamId=v),d!=null&&d.length){let T=s.findGroup(d,E.groupId)||d[0];El(E,T,"audioCodec"),El(E,T,"textCodec")}h.push(E)}}return n}static parseLevelPlaylist(e,t,i,r,n,a){let o=new Cn(t),l=o.fragments,c=null,u=0,d=0,h=0,f=0,m=null,g=new Vi(r,t),p,v,E,T=-1,x=!1,_=null;for(pl.lastIndex=0,o.m3u8=e,o.hasVariableRefs=ul(e);(p=pl.exec(e))!==null;){x&&(x=!1,g=new Vi(r,t),g.start=h,g.sn=u,g.cc=f,g.level=i,c&&(g.initSegment=c,g.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,_&&(g.setByteRange(_),_=null)));let k=p[1];if(k){g.duration=parseFloat(k);let L=(" "+p[2]).slice(1);g.title=L||null,g.tagList.push(L?["INF",k,L]:["INF",k])}else if(p[3]){if(K(g.duration)){g.start=h,E&&_l(g,E,o),g.sn=u,g.level=i,g.cc=f,l.push(g);let L=(" "+p[3]).slice(1);g.relurl=On(o,L),Tl(g,m),m=g,h+=g.duration,u++,d=0,x=!0}}else if(p[4]){let L=(" "+p[4]).slice(1);m?g.setByteRange(L,m):g.setByteRange(L)}else if(p[5])g.rawProgramDateTime=(" "+p[5]).slice(1),g.tagList.push(["PROGRAM-DATE-TIME",g.rawProgramDateTime]),T===-1&&(T=l.length);else{if(p=p[0].match(Lm),!p){A.warn("No matches on slow regex match for level playlist!");continue}for(v=1;v0&&O.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=O.optionalFloat("PART-HOLD-BACK",0),o.holdBack=O.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{let O=new pe(w);o.partTarget=O.decimalFloatingPoint("PART-TARGET");break}case"PART":{let O=o.partList;O||(O=o.partList=[]);let W=d>0?O[O.length-1]:void 0,q=d++,$=new pe(w);Me(o,$,["BYTERANGE","URI"]);let Z=new wn($,g,t,q,W);O.push(Z),g.duration+=Z.duration;break}case"PRELOAD-HINT":{let O=new pe(w);Me(o,O,["URI"]),o.preloadHint=O;break}case"RENDITION-REPORT":{let O=new pe(w);Me(o,O,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(O);break}default:A.warn(`line parsed but not handled: ${p}`);break}}}m&&!m.relurl?(l.pop(),h-=m.duration,o.partList&&(o.fragmentHint=m)):o.partList&&(Tl(g,m),g.cc=f,o.fragmentHint=g,E&&_l(g,E,o));let I=l.length,b=l[0],R=l[I-1];if(h+=o.skippedSegments*o.targetduration,h>0&&I&&R){o.averagetargetduration=h/I;let k=R.sn;o.endSN=k!=="initSegment"?k:0,o.live||(R.endList=!0),b&&(o.startCC=b.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(h+=o.fragmentHint.duration),o.totalduration=h,o.endCC=f,T>0&&Dm(l,T),o}};function yl(s,e,t){var i,r;let n=new pe(s);Me(t,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);let a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),c=n.KEYFORMATVERSIONS,u=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&A.error(`Invalid IV: ${n.IV}`);let d=o?Wt.resolve(o,e):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Yi(a,d,u,h,l)}function vl(s){let t=new pe(s).decimalFloatingPoint("TIME-OFFSET");return K(t)?t:null}function Im(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{let r=t.filter(n=>_m(n,i));r.length&&(e[`${i}Codec`]=r.join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function El(s,e,t){let i=e[t];i&&(s[t]=i)}function Dm(s,e){let t=s[e];for(let i=e;i--;){let r=s[i];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function Tl(s,e){s.rawProgramDateTime?s.programDateTime=Date.parse(s.rawProgramDateTime):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime),K(s.programDateTime)||(s.programDateTime=null,s.rawProgramDateTime=null)}function xl(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null}function _l(s,e,t){s.levelkeys=e;let{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&i.push(s)}var ie={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},z={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function Sl(s){let{type:e}=s;switch(e){case ie.AUDIO_TRACK:return z.AUDIO;case ie.SUBTITLE_TRACK:return z.SUBTITLE;default:return z.MAIN}}function yn(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Mn=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,r=t.loader,n=i||r,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ie.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(e,t){let{id:i,level:r,pathwayId:n,url:a,deliveryDirectives:o}=t;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:ie.LEVEL,url:a,deliveryDirectives:o})}onAudioTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ie.AUDIO_TRACK,url:n,deliveryDirectives:a})}onSubtitleTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ie.SUBTITLE_TRACK,url:n,deliveryDirectives:a})}load(e){var t;let i=this.hls.config,r=this.getInternalLoader(e);if(r){let c=r.context;if(c&&c.url===e.url&&c.level===e.level){A.trace("[playlist-loader]: playlist request ongoing");return}A.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let n;if(e.type===ie.MANIFEST?n=i.manifestLoadPolicy.default:n=Te({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),K((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===ie.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===ie.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===ie.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){let u=c.partTarget,d=c.targetduration;if(u&&d){let h=Math.max(u*3,d*.8)*1e3;n=Te({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)})}}}let a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,u,d,h)=>{let f=this.getInternalLoader(d);this.resetInternalLoader(d.type);let m=c.data;if(m.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,d,new Error("no EXTM3U delimiter"),h||null,u);return}u.parsing.start=performance.now(),Wt.isMediaPlaylist(m)?this.handleTrackOrLevelPlaylist(c,u,d,h||null,f):this.handleMasterPlaylist(c,u,d,h)},onError:(c,u,d,h)=>{this.handleNetworkError(u,d,!1,c,h)},onTimeout:(c,u,d)=>{this.handleNetworkError(u,d,!0,void 0,c)}};r.load(e,o,l)}handleMasterPlaylist(e,t,i,r){let n=this.hls,a=e.data,o=yn(e,i),l=Wt.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}let{contentSteering:c,levels:u,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m;let{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=Wt.parseMasterPlaylistMedia(a,o,l);g.length&&!g.some(T=>!T.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(A.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new pe({}),bitrate:0,url:""})),n.trigger(y.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:p,captions:v,contentSteering:c,url:o,stats:t,networkDetails:r,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,i,r,n){let a=this.hls,{id:o,level:l,type:c}=i,u=yn(e,i),d=0,h=K(l)?l:K(o)?o:0,f=Sl(i),m=Wt.parseLevelPlaylist(e.data,u,h,f,d,this.variableList);if(c===ie.MANIFEST){let g={attrs:new pe({}),bitrate:0,details:m,name:"",url:u};a.trigger(y.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=m,this.handlePlaylistLoaded(m,e,t,i,r,n)}handleManifestParsingError(e,t,i,r,n){this.hls.trigger(y.ERROR,{type:j.NETWORK_ERROR,details:D.MANIFEST_PARSING_ERROR,fatal:t.type===ie.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,i=!1,r,n){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===ie.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===ie.AUDIO_TRACK||e.type===ie.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);A.warn(`[playlist-loader]: ${a}`);let l=D.UNKNOWN,c=!1,u=this.getInternalLoader(e);switch(e.type){case ie.MANIFEST:l=i?D.MANIFEST_LOAD_TIMEOUT:D.MANIFEST_LOAD_ERROR,c=!0;break;case ie.LEVEL:l=i?D.LEVEL_LOAD_TIMEOUT:D.LEVEL_LOAD_ERROR,c=!1;break;case ie.AUDIO_TRACK:l=i?D.AUDIO_TRACK_LOAD_TIMEOUT:D.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case ie.SUBTITLE_TRACK:l=i?D.SUBTITLE_TRACK_LOAD_TIMEOUT:D.SUBTITLE_LOAD_ERROR,c=!1;break}u&&this.resetInternalLoader(e.type);let d={type:j.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(r){let h=(t==null?void 0:t.url)||e.url;d.response=we({url:h,data:void 0},r)}this.hls.trigger(y.ERROR,d)}handlePlaylistLoaded(e,t,i,r,n,a){let o=this.hls,{type:l,level:c,id:u,groupId:d,deliveryDirectives:h}=r,f=yn(t,r),m=Sl(r),g=typeof r.level=="number"&&m===z.MAIN?c:void 0;if(!e.fragments.length){let v=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:j.NETWORK_ERROR,details:D.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:r,level:g,parent:m,networkDetails:n,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));let p=e.playlistParsingError;if(p){o.trigger(y.ERROR,{type:j.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:r,level:g,parent:m,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case ie.MANIFEST:case ie.LEVEL:o.trigger(y.LEVEL_LOADED,{details:e,level:g||0,id:u||0,stats:i,networkDetails:n,deliveryDirectives:h});break;case ie.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:e,id:u||0,groupId:d||"",stats:i,networkDetails:n,deliveryDirectives:h});break;case ie.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,id:u||0,groupId:d||"",stats:i,networkDetails:n,deliveryDirectives:h});break}}};function hc(s,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=s,e.dispatchEvent(t)}function fc(s,e){let t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){A.debug(`[texttrack-utils]: ${i}`);try{let r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,s.addCue(r)}catch(r){A.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(s.mode=t)}function hi(s){let e=s.mode;if(e==="disabled"&&(s.mode="hidden"),s.cues)for(let t=s.cues.length;t--;)s.removeCue(s.cues[t]);e==="disabled"&&(s.mode=e)}function Nn(s,e,t,i){let r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){let n=wm(s.cues,e,t);for(let a=0;as[t].endTime)return-1;let i=0,r=t;for(;i<=r;){let n=Math.floor((r+i)/2);if(es[n].startTime&&i-1)for(let n=r,a=s.length;n=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function Bs(s){let e=[];for(let t=0;t{let s=Fn();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function vn(s,e){return s.getTime()/1e3-e}function Pm(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var Un=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(hi(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;tws&&(d=ws),d-u<=0&&(d=u+Cm);for(let f=0;fu.type===ze.audioId3&&l:r==="video"?c=u=>u.type===ze.emsg&&o:c=u=>u.type===ze.audioId3&&l||u.type===ze.emsg&&o,Nn(n,t,i,c)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;let{dateRangeCuesAppended:i,id3Track:r}=this,{dateRanges:n}=t,a=Object.keys(n);if(r){let u=Object.keys(i).filter(d=>!a.includes(d));for(let d=u.length;d--;){let h=u[d];Object.keys(i[h].cues).forEach(f=>{r.removeCue(i[h].cues[f])}),delete i[h]}}let o=t.fragments[t.fragments.length-1];if(a.length===0||!K(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));let l=o.programDateTime/1e3-o.start,c=Fn();for(let u=0;u{if(I!==h.id){let b=n[I];if(b.class===h.class&&b.startDate>h.startDate&&(!_||h.startDate<_.startDate))return b}return _},null);x&&(v=vn(x.startDate,l),p=!0)}let T=Object.keys(h.attr);for(let x=0;xthis.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){let{config:e,levelDetails:t}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let{levelDetails:e}=this;if(e===null)return null;let{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig,c=o&&i||t;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=n!==void 0?n:a*r);let u=r;return c+Math.min(this.stallCount*1,u)}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(e===null||t===null||i===null)return null;let r=i.edge,n=e-t-this.edgeStalled,a=r-i.totalduration,o=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){let{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){let{levelDetails:e}=this;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e,levelDetails:t}=this;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(y.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(y.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===D.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&A.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){let{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;let i=this.computeLatency();if(i===null)return;this._latency=i;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!t.live)return;let a=this.targetLatency;if(a===null)return;let o=i-a,l=Math.min(this.maxLatency,a+t.targetduration);if(o.05&&this.forwardBufferLength>1){let u=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(u,Math.max(1,d))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){let{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},$n=["NONE","TYPE-0","TYPE-1",null];function Om(s){return $n.indexOf(s)>-1}var Js=["SDR","PQ","HLG"];function Mm(s){return!!s&&Js.indexOf(s)>-1}var $s={No:"",Yes:"YES",v2:"v2"};function Al(s){let{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,r=i!!t).map(t=>t.substring(0,4)).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Rl(this._audioGroups,e)}hasSubtitleGroup(e){return Rl(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function Rl(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function En(s,e){let t=e.startPTS;if(K(t)){let i=0,r;e.sn>s.sn?(i=t-s.start,r=s):(i=s.start-t,r=e),r.duration!==i&&(r.duration=i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.start=s.start+(s.minEndPTS-s.start):e.start=s.start+s.duration:e.start=Math.max(s.start-e.duration,0)}function mc(s,e,t,i,r,n){i-t<=0&&(A.warn("Fragment should have a positive duration",e),i=t+e.duration,n=r+e.duration);let o=t,l=i,c=e.startPTS,u=e.endPTS;if(K(c)){let p=Math.abs(c-t);K(e.deltaPTS)?e.deltaPTS=Math.max(p,e.deltaPTS):e.deltaPTS=p,o=Math.max(t,c),t=Math.min(t,c),r=Math.min(r,e.startDTS),l=Math.min(i,u),i=Math.max(i,u),n=Math.max(n,e.endDTS)}let d=t-e.start;e.start!==0&&(e.start=t),e.duration=i-e.start,e.startPTS=t,e.maxStartPTS=o,e.startDTS=r,e.endPTS=i,e.minEndPTS=l,e.endDTS=n;let h=e.sn;if(!s||hs.endSN)return 0;let f,m=h-s.startSN,g=s.fragments;for(g[m]=e,f=m;f>0;f--)En(g[f],g[f-1]);for(f=m;f=0;l--){let c=i[l].initSegment;if(c){t=c;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let r=0,n;if(Bm(s,e,(l,c)=>{l.relurl&&(r=l.cc-c.cc),K(l.startPTS)&&K(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,l.initSegment&&(c.initSegment=l.initSegment,t=l.initSegment)}),t&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(c=>{var u;c&&(!c.initSegment||c.initSegment.relurl===((u=t)==null?void 0:u.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){A.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=Fm(s.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));let a=e.fragments;if(r){A.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),n?mc(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):gc(s,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;let o=e.advancedDateTime;if(e.advanced&&o){let l=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=l),e.driftEndTime=o,e.driftEnd=l}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime}function Fm(s,e,t){let i=Te({},s);return t&&t.forEach(r=>{delete i[r]}),Object.keys(e).forEach(r=>{let n=new Ws(e[r].attr,i[r]);n.isValid?i[r]=n:A.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[r].attr)}"`)}),i}function Um(s,e,t){if(s&&e){let i=0;for(let r=0,n=s.length;r<=n;r++){let a=s[r],o=e[r+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function Bm(s,e,t){let i=e.skippedSegments,r=Math.max(s.startSN,e.startSN)-e.startSN,n=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,a=e.startSN-s.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let c=r;c<=n;c++){let u=l[a+c],d=o[c];i&&!d&&c=i.length||Gn(e,i[t].start)}function Gn(s,e){if(e){let t=s.fragments;for(let i=s.skippedSegments;ie){let n=i[i.length-1].duration*1e3;n{let{details:i}=e;i!=null&&i.fragments&&i.fragments.forEach(r=>{r.level=t})})}function er(s){switch(s.details){case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_TIMEOUT:case D.LEVEL_LOAD_TIMEOUT:case D.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Il(s,e){let t=er(e);return s.default[`${t?"timeout":"error"}Retry`]}function Ha(s,e){let t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function Dl(s){return we(we({},s),{errorRetry:null,timeoutRetry:null})}function tr(s,e,t,i){if(!s)return!1;let r=i==null?void 0:i.code,n=e499)}var vc={search:function(s,e){let t=0,i=s.length-1,r=null,n=null;for(;t<=i;){r=(t+i)/2|0,n=s[r];let a=e(n);if(a>0)t=r+1;else if(a<0)i=r-1;else return n}return null}};function Hm(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!K(e))return null;let i=s[0].programDateTime;if(e<(i||0))return null;let r=s[s.length-1].endProgramDateTime;if(e>=(r||0))return null;t=t||0;for(let n=0;n0&&o<15e-7&&(t+=15e-7)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!s||s.level===n.level)&&Kn(t,i,n)===0||Vm(n,s,Math.min(r,i))))return n;let a=vc.search(e,Kn.bind(null,t,i));return a&&(a!==s||!n)?a:n}function Vm(s,e,t){if(e&&e.start===0&&e.level0){let i=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return s.start<=i}return!1}function Kn(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function qm(s,e,t){let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function Wm(s,e){return vc.search(s,t=>t.cce?-1:0)}var De={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},We={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4},Hn=class{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=A.log.bind(A,"[info]:"),this.warn=A.warn.bind(A,"[warning]:"),this.error=A.error.bind(A,"[error]:"),this.registerListeners()}registerListeners(){let e=this.hls;e.on(y.ERROR,this.onError,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(y.ERROR,this.onError,this),e.off(y.ERROR,this.onErrorOut,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===z.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,r;if(t.fatal)return;let n=this.hls,a=t.context;switch(t.details){case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case D.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction={action:De.DoNothing,flags:We.None};return}case D.FRAG_GAP:case D.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=De.SendAlternateToPenaltyBox;return}case D.LEVEL_EMPTY_ERROR:case D.LEVEL_PARSING_ERROR:{var o,l;let c=t.parent===z.MAIN?t.level:n.loadLevel;t.details===D.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(l=o.levelDetails)!=null&&l.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.level));return;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.SUBTITLE_LOAD_ERROR:case D.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){let c=n.levels[n.loadLevel];if(c&&(a.type===ie.AUDIO_TRACK&&c.hasAudioGroup(a.groupId)||a.type===ie.SUBTITLE_TRACK&&c.hasSubtitleGroup(a.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=De.SendAlternateToPenaltyBox,t.errorAction.flags=We.MoveAllAlternatesMatchingHost;return}}return;case D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{let c=n.levels[n.loadLevel],u=c==null?void 0:c.attrs["HDCP-LEVEL"];u?t.errorAction={action:De.SendAlternateToPenaltyBox,flags:We.MoveAllAlternatesMatchingHDCP,hdcpLevel:u}:this.keySystemError(t)}return;case D.BUFFER_ADD_CODEC_ERROR:case D.REMUX_ALLOC_ERROR:case D.BUFFER_APPEND_ERROR:t.errorAction=this.getLevelSwitchAction(t,(r=t.level)!=null?r:n.loadLevel);return;case D.INTERNAL_EXCEPTION:case D.BUFFER_APPENDING_ERROR:case D.BUFFER_FULL_ERROR:case D.LEVEL_SWITCH_ERROR:case D.BUFFER_STALLED_ERROR:case D.BUFFER_SEEK_OVER_HOLE:case D.BUFFER_NUDGE_ON_STALL:t.errorAction={action:De.DoNothing,flags:We.None};return}t.type===j.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){let t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){let i=this.hls,r=Il(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(tr(r,n,er(e),e.response))return{action:De.RetryRequest,flags:We.None,retryConfig:r,retryCount:n};let o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=n),o}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Il(e.details.startsWith("key")?a:n,e),l=t.levels.reduce((u,d)=>u+d.fragmentError,0);if(r&&(e.details!==D.FRAG_GAP&&r.fragmentError++,tr(o,l,er(e),e.response)))return{action:De.RetryRequest,flags:We.None,retryConfig:o,retryCount:l};let c=this.getLevelSwitchAction(e,i);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){let i=this.hls;t==null&&(t=i.loadLevel);let r=this.hls.levels[t];if(r){var n,a;let c=e.details;r.loadError++,c===D.BUFFER_APPEND_ERROR&&r.fragmentError++;let u=-1,{levels:d,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=i;i.autoLevelEnabled||(i.loadLevel=-1);let g=(n=e.frag)==null?void 0:n.type,v=(g===z.AUDIO&&c===D.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===D.BUFFER_ADD_CODEC_ERROR||c===D.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:I})=>r.audioCodec!==I),T=e.sourceBufferName==="video"&&(c===D.BUFFER_ADD_CODEC_ERROR||c===D.BUFFER_APPEND_ERROR)&&d.some(({codecSet:I,audioCodec:b})=>r.codecSet!==I&&r.audioCodec===b),{type:x,groupId:_}=(a=e.context)!=null?a:{};for(let I=d.length;I--;){let b=(I+h)%d.length;if(b!==h&&b>=f&&b<=m&&d[b].loadError===0){var o,l;let R=d[b];if(c===D.FRAG_GAP&&g===z.MAIN&&e.frag){let k=d[b].details;if(k){let L=ir(e.frag,k.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(x===ie.AUDIO_TRACK&&R.hasAudioGroup(_)||x===ie.SUBTITLE_TRACK&&R.hasSubtitleGroup(_))continue;if(g===z.AUDIO&&(o=r.audioGroups)!=null&&o.some(k=>R.hasAudioGroup(k))||g===z.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(k=>R.hasSubtitleGroup(k))||v&&r.audioCodec===R.audioCodec||!v&&r.audioCodec!==R.audioCodec||T&&r.codecSet===R.codecSet)continue}u=b;break}}if(u>-1&&i.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:De.SendAlternateToPenaltyBox,flags:We.None,nextAutoLevel:u}}return{action:De.SendAlternateToPenaltyBox,flags:We.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case De.DoNothing:break;case De.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==D.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case De.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:r,hdcpLevel:n,nextAutoLevel:a}=i;switch(r){case We.None:this.switchLevel(e,a);break;case We.MoveAllAlternatesMatchingHDCP:n&&(t.maxHdcpLevel=$n[$n.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,a)}switchLevel(e,t){t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},zi=class{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=A.log.bind(A,`${t}:`),this.warn=A.warn.bind(A,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){let r=t==null?void 0:t.renditionReports;if(r){let n=-1;for(let a=0;a=0&&u>t.partTarget&&(l+=1)}let c=i&&Al(i);return new Zs(o,l>=0?l:void 0,c)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){let{details:r,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;if(r.advancedDateTime=Date.now()-o,r.live||i!=null&&i.live){if(r.reloaded(i),i&&this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),i&&r.fragments.length>0&&Nm(i,r),!this.canLoad||!r.live)return;let l,c,u;if(r.canBlockReload&&r.endSN&&r.advanced){let p=this.hls.config.lowLatencyMode,v=r.lastPartSn,E=r.endSN,T=r.lastPartIndex,x=T!==-1,_=v===E,I=p?0:T;x?(c=_?E+1:v,u=_?I:T+1):c=E+1;let b=r.age,R=b+r.ageHeader,k=Math.min(R-r.partTarget,r.targetduration*1.5);if(k>0){if(i&&k>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${k} with playlist age: ${r.age}`),k=0;else{let L=Math.floor(k/r.targetduration);if(c+=L,u!==void 0){let w=Math.round(k%r.targetduration/r.partTarget);u+=w}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${b.toFixed(2)}s goal: ${k} skip sn ${L} to part ${u}`)}r.tuneInGoal=k}if(l=this.getDeliveryDirectives(r,t.deliveryDirectives,c,u),p||!_){this.loadPlaylist(l);return}}else(r.canBlockReload||r.canSkipUntil)&&(l=this.getDeliveryDirectives(r,t.deliveryDirectives,c,u));let d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,f=(r.edge-h)*1e3,m=$m(r,f);r.updated&&a>this.requestScheduled+m&&(this.requestScheduled=n.loading.start),c!==void 0&&r.canBlockReload?this.requestScheduled=n.loading.first+m-(r.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+mthis.loadPlaylist(l),g)}else this.clearTimer()}getDeliveryDirectives(e,t,i,r){let n=Al(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=$s.No),new Zs(i,r,n)}checkRetry(e){let t=e.details,i=er(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===De.RetryRequest||!r.resolved&&n===De.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(i&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let u=Ha(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,r.resolved=!0}return l}},vt=class{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},Vn=class{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new vt(e),this.fast_=new vt(t),this.defaultTTFB_=r,this.ttfb_=new vt(e)}update(e,t){let{slow_:i,fast_:r,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new vt(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new vt(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new vt(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let i=8*t,r=e/1e3,n=i/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){let t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}},Ec={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},kl={};function Ym(s,e,t,i,r,n){let a=s.audioCodec?s.audioGroups:null,o=n==null?void 0:n.audioCodec,l=n==null?void 0:n.channels,c=l?parseInt(l):o?1/0:2,u=null;if(a!=null&&a.length)try{a.length===1&&a[0]?u=e.groups[a[0]].channels:u=a.reduce((d,h)=>{if(h){let f=e.groups[h];if(!f)throw new Error(`Audio track group ${h} not found`);Object.keys(f.channels).forEach(m=>{d[m]=(d[m]||0)+f.channels[m]})}return d},{2:0})}catch{return!0}return s.videoCodec!==void 0&&(s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(r,8e6))||!!u&&K(c)&&Object.keys(u).some(d=>parseInt(d)>c)}function jm(s,e,t){let i=s.videoCodec,r=s.audioCodec;if(!i||!r||!t)return Promise.resolve(Ec);let n={width:s.width,height:s.height,bitrate:Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)),framerate:s.frameRate||30},a=s.videoRange;a!=="SDR"&&(n.transferFunction=a.toLowerCase());let o=i.split(",").map(l=>({type:"media-source",video:we(we({},n),{},{contentType:ji(l,"video")})}));return r&&s.audioGroups&&s.audioGroups.forEach(l=>{var c;l&&((c=e.groups[l])==null||c.tracks.forEach(u=>{if(u.groupId===l){let d=u.channels||"",h=parseFloat(d);K(h)&&h>2&&o.push.apply(o,r.split(",").map(f=>({type:"media-source",audio:{contentType:ji(f,"audio"),channels:""+h}})))}}))}),Promise.all(o.map(l=>{let c=zm(l);return kl[c]||(kl[c]=t.decodingInfo(l))})).then(l=>({supported:!l.some(c=>!c.supported),configurations:o,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:o,decodingInfoResults:[],error:l}))}function zm(s){let{audio:e,video:t}=s,i=t||e;if(i){let r=i.contentType.split('"')[1];if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${r}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${r}`}return""}function Xm(){if(typeof matchMedia=="function"){let s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===!0}return!1}function Qm(s,e){let t=!1,i=[];return s&&(t=s!=="SDR",i=[s]),e&&(i=e.allowedVideoRanges||Js.slice(0),t=e.preferHDR!==void 0?e.preferHDR:Xm(),t?i=i.filter(r=>r!=="SDR"):i=["SDR"]),{preferHDR:t,allowedVideoRanges:i}}function Jm(s,e,t,i,r){let n=Object.keys(s),a=i==null?void 0:i.channels,o=i==null?void 0:i.audioCodec,l=a&&parseInt(a)===2,c=!0,u=!1,d=1/0,h=1/0,f=1/0,m=0,g=[],{preferHDR:p,allowedVideoRanges:v}=Qm(e,r);for(let _=n.length;_--;){let I=s[n[_]];c=I.channels[2]>0,d=Math.min(d,I.minHeight),h=Math.min(h,I.minFramerate),f=Math.min(f,I.minBitrate);let b=v.filter(R=>I.videoRanges[R]>0);b.length>0&&(u=!0,g=b)}d=K(d)?d:0,h=K(h)?h:0;let E=Math.max(1080,d),T=Math.max(30,h);return f=K(f)?f:t,t=Math.max(f,t),u||(e=void 0,g=[]),{codecSet:n.reduce((_,I)=>{let b=s[I];if(I===_)return _;if(b.minBitrate>t)return lt(I,`min bitrate of ${b.minBitrate} > current estimate of ${t}`),_;if(!b.hasDefaultAudio)return lt(I,"no renditions with default or auto-select sound found"),_;if(o&&I.indexOf(o.substring(0,4))%5!==0)return lt(I,`audio codec preference "${o}" not found`),_;if(a&&!l){if(!b.channels[a])return lt(I,`no renditions with ${a} channel sound found (channels options: ${Object.keys(b.channels)})`),_}else if((!o||l)&&c&&b.channels[2]===0)return lt(I,"no renditions with stereo sound found"),_;return b.minHeight>E?(lt(I,`min resolution of ${b.minHeight} > maximum of ${E}`),_):b.minFramerate>T?(lt(I,`min framerate of ${b.minFramerate} > maximum of ${T}`),_):g.some(R=>b.videoRanges[R]>0)?b.maxScore=Xs(_)||b.fragmentError>s[_].fragmentError)?_:(m=b.maxScore,I):(lt(I,`no variants with VIDEO-RANGE of ${JSON.stringify(g)} found`),_)},void 0),videoRanges:g,preferHDR:p,minFramerate:h,minBitrate:f}}function lt(s,e){A.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function Zm(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);let r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function eg(s,e,t,i){return s.slice(t,i+1).reduce((r,n)=>{if(!n.codecSet)return r;let a=n.audioGroups,o=r[n.codecSet];o||(r[n.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,n.bitrate);let l=Math.min(n.height,n.width);return o.minHeight=Math.min(o.minHeight,l),o.minFramerate=Math.min(o.minFramerate,n.frameRate),o.maxScore=Math.max(o.maxScore,n.score),o.fragmentError+=n.fragmentError,o.videoRanges[n.videoRange]=(o.videoRanges[n.videoRange]||0)+1,a&&a.forEach(c=>{if(!c)return;let u=e.groups[c];u&&(o.hasDefaultAudio=o.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{o.channels[d]=(o.channels[d]||0)+u.channels[d]}))}),r},{})}function st(s,e,t){if("attrs"in s){let i=e.indexOf(s);if(i!==-1)return i}for(let i=0;ii.indexOf(r)===-1)}function li(s,e){let{audioCodec:t,channels:i}=s;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function ig(s,e,t,i,r){let n=e[i],o=e.reduce((h,f,m)=>{let g=f.uri;return(h[g]||(h[g]=[])).push(m),h},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));let l=n.videoRange,c=n.frameRate,u=n.codecSet.substring(0,4),d=wl(e,i,h=>{if(h.videoRange!==l||h.frameRate!==c||h.codecSet.substring(0,4)!==u)return!1;let f=h.audioGroups,m=t.filter(g=>!f||f.indexOf(g.groupId)!==-1);return st(s,m,r)>-1});return d>-1?d:wl(e,i,h=>{let f=h.audioGroups,m=t.filter(g=>!f||f.indexOf(g.groupId)!==-1);return st(s,m,r)>-1})}function wl(s,e,t){for(let i=e;i;i--)if(t(s[i]))return i;for(let i=e+1;i{let{fragCurrent:t,partCurrent:i,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!t||!a)return;let o=performance.now(),l=i?i.stats:t.stats,c=i?i.duration:t.duration,u=o-l.loading.start,d=r.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||t.level<=d){this.clearTimer(),this._nextAutoLevel=-1;return}if(!n||a.paused||!a.playbackRate||!a.readyState)return;let h=r.mainForwardBufferInfo;if(h===null)return;let f=this.bwEstimator.getEstimateTTFB(),m=Math.abs(a.playbackRate);if(u<=Math.max(f,1e3*(c/(m*2))))return;let g=h.len/m,p=l.loading.first?l.loading.first-l.loading.start:-1,v=l.loaded&&p>-1,E=this.getBwEstimate(),T=r.levels,x=T[t.level],_=l.total||Math.max(l.loaded,Math.round(c*x.averageBitrate/8)),I=v?u-p:u;I<1&&v&&(I=Math.min(u,l.loaded*8/E));let b=v?l.loaded*1e3/I:0,R=b?(_-l.loaded)/b:_*8/E+f/1e3;if(R<=g)return;let k=b?b*8:E,L=Number.POSITIVE_INFINITY,w;for(w=t.level-1;w>d;w--){let O=T[w].maxBitrate;if(L=this.getTimeToLoadFrag(f/1e3,k,c*O,!T[w].details),L=R||L>c*10)return;r.nextLoadLevel=r.nextAutoLevel=w,v?this.bwEstimator.sample(u-Math.min(f,p),l.loaded):this.bwEstimator.sampleTTFB(u);let P=T[w].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>P&&this.resetEstimator(P),this.clearTimer(),A.warn(`[abr] Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} is loading too slowly; Time to underbuffer: ${g.toFixed(3)} s Estimated load time for current fragment: ${R.toFixed(3)} s Estimated load time for down switch fragment: ${L.toFixed(3)} s TTFB estimate: ${p|0} ms Current BW estimate: ${K(E)?E|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${w} @ ${P|0} bps`),r.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(A.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new Vn(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(y.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=(r=t.part)!=null?r:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case D.FRAG_LOAD_TIMEOUT:{let i=t.frag,{fragCurrent:r,partCurrent:n}=this;if(i&&r&&i.sn===r.sn&&i.level===r.level){let a=performance.now(),o=n?n.stats:i.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){let d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,r){let n=e+i/t,a=r?this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let i=this.hls.config,{loading:r}=t.stats,n=r.end-r.start;K(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:i}){let r=i?i.stats:t.stats;if(t.type===z.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let n=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+r.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){let n={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(y.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:i,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;let a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==z.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,t,e,0,r,1,1);if(n>-1)return n;let a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return A.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=i&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:r,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay(),u=n.abrBandWidthFactor,d=n.abrBandWidthUpFactor;if(c){let p=this.findBestLevel(l,a,r,c,0,u,d);if(p>=0)return p}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!c){let p=this.bitrateTestDelay;p&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-p,A.info(`[abr] bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=d=1)}let f=this.findBestLevel(l,a,r,c,h,u,d);if(A.info(`[abr] ${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`),f>-1)return f;let m=i.levels[a],g=i.levels[i.loadLevel];return(m==null?void 0:m.bitrate)<(g==null?void 0:g.bitrate)?a:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,n,a,o){var l;let c=r+n,u=this.lastLoadedFragLevel,d=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:f}=this,{levels:m,allAudioTracks:g,loadLevel:p,config:v}=this.hls;if(m.length===1)return 0;let E=m[d],T=!!(E!=null&&(l=E.details)!=null&&l.live),x=p===-1||u===-1,_,I="SDR",b=(E==null?void 0:E.frameRate)||0,{audioPreference:R,videoPreference:k}=v,L=this.audioTracksByGroup||(this.audioTracksByGroup=Zm(g));if(x){if(this.firstSelection!==-1)return this.firstSelection;let q=this.codecTiers||(this.codecTiers=eg(m,L,t,i)),$=Jm(q,I,e,R,k),{codecSet:Z,videoRanges:ne,minFramerate:H,minBitrate:B,preferHDR:ee}=$;_=Z,I=ee?ne[ne.length-1]:ne[0],b=H,e=Math.max(e,B),A.log(`[abr] picked start tier ${JSON.stringify($)}`)}else _=E==null?void 0:E.codecSet,I=E==null?void 0:E.videoRange;let w=f?f.duration:h?h.duration:0,P=this.bwEstimator.getEstimateTTFB()/1e3,O=[];for(let q=i;q>=t;q--){var W;let $=m[q],Z=q>d;if(!$)continue;if(v.useMediaCapabilities&&!$.supportedResult&&!$.supportedPromise){let ye=navigator.mediaCapabilities;typeof(ye==null?void 0:ye.decodingInfo)=="function"&&Ym($,L,I,b,e,R)?($.supportedPromise=jm($,L,ye),$.supportedPromise.then(ve=>{if(!this.hls)return;$.supportedResult=ve;let _e=this.hls.levels,$e=_e.indexOf($);ve.error?A.warn(`[abr] MediaCapabilities decodingInfo error: "${ve.error}" for level ${$e} ${JSON.stringify(ve)}`):ve.supported||(A.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${$e} ${JSON.stringify(ve)}`),$e>-1&&_e.length>1&&(A.log(`[abr] Removing unsupported level ${$e}`),this.hls.removeLevel($e)))})):$.supportedResult=Ec}if(_&&$.codecSet!==_||I&&$.videoRange!==I||Z&&b>$.frameRate||!Z&&b>0&&b<$.frameRate||$.supportedResult&&!((W=$.supportedResult.decodingInfoResults)!=null&&W[0].smooth)){O.push(q);continue}let ne=$.details,H=(f?ne==null?void 0:ne.partTarget:ne==null?void 0:ne.averagetargetduration)||w,B;Z?B=o*e:B=a*e;let ee=w&&r>=w*2&&n===0?m[q].averageBitrate:m[q].maxBitrate,X=this.getTimeToLoadFrag(P,B,ee*H,ne===void 0);if(B>=ee&&(q===u||$.loadError===0&&$.fragmentError===0)&&(X<=P||!K(X)||T&&!this.bitrateTestDelay||X${q} adjustedbw(${Math.round(B)})-bitrate=${Math.round(B-ee)} ttfb:${P.toFixed(1)} avgDuration:${H.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${X.toFixed(1)} firstSelection:${x} codecSet:${_} videoRange:${I} hls.loadLevel:${p}`)),x&&(this.firstSelection=q),q}}return-1}set nextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:i}=this.hls,r=Math.min(Math.max(e,i),t);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}},Wn=class{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},ke={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Yn=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){let{hls:e}=this;e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let r=i.length;r--;){let n=i[r];if(!n)break;let a=n.end;if(n.start<=e&&a!==null&&e<=a)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){let{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){let a=i[r[n]];if((a==null?void 0:a.body.type)===t&&a.buffered){let o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,i,r){this.timeRanges&&(this.timeRanges[e]=t);let n=(r==null?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o||n>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===i&&this.removeFragment(o.body);return}let l=o.range[e];l&&l.time.some(c=>{let u=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return u&&this.removeFragment(o.body),u})})}detectPartialFragments(e){let t=this.timeRanges,{frag:i,part:r}=e;if(!t||i.sn==="initSegment")return;let n=ci(i),a=this.fragments[n];if(!a||a.buffered&&i.gap)return;let o=!i.relurl;Object.keys(t).forEach(l=>{let c=i.elementaryStreams[l];if(!c)return;let u=t[l],d=o||c.partial===!0;a.range[l]=this.getBufferedTimes(i,r,d,u)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),Cs(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.body)}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter(r=>r.fragment.sn>=e))}fragBuffered(e,t){let i=ci(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,i,r){let n={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let u=0;u=d&&l<=h){n.time.push({startPTS:Math.max(a,r.start(u)),endPTS:Math.min(o,r.end(u))});break}else if(ad){let f=Math.max(a,r.start(u)),m=Math.min(o,r.end(u));m>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:m}))}else if(o<=d)break}return n}getPartialFragment(e){let t=null,i,r,n,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{let u=l[c];u&&Cs(u)&&(r=u.body.start-o,n=u.body.end+o,e>=r&&e<=n&&(i=Math.min(e-r,n-e),a<=i&&(t=u.body,a=i)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||Cs(t))}getState(e){let t=ci(e),i=this.fragments[t];return i?i.buffered?Cs(i)?ke.PARTIAL:ke.OK:ke.APPENDING:ke.NOT_LOADED}isTimeBuffered(e,t,i){let r,n;for(let a=0;a=r&&t<=n)return!0;if(t<=r)return!1}return!1}onFragLoaded(e,t){let{frag:i,part:r}=t;if(i.sn==="initSegment"||i.bitrateTest)return;let n=r?null:t,a=ci(i);this.fragments[a]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:r,timeRanges:n}=t;if(i.sn==="initSegment")return;let a=i.type;if(r){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(r)}this.timeRanges=n,Object.keys(n).forEach(o=>{let l=n[o];this.detectEvictedFragments(o,l,a,r)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=ci(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let l=o.body;l.type!==i||r&&!l.gap||l.starte&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){let t=ci(e);e.stats.loaded=0,e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let r=e.sn;this.activePartLists[e.type]=i.filter(n=>n.fragment.sn!==r)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}};function Cs(s){var e,t,i;return s.buffered&&(s.body.gap||((e=s.range.video)==null?void 0:e.partial)||((t=s.range.audio)==null?void 0:t.partial)||((i=s.range.audiovideo)==null?void 0:i.partial))}function ci(s){return`${s.type}_${s.level}_${s.sn}`}var sg={length:0,start:()=>0,end:()=>0},he=class s{static isBuffered(e,t){try{if(e){let i=s.getBuffered(e);for(let r=0;r=i.start(r)&&t<=i.end(r))return!0}}catch{}return!1}static bufferInfo(e,t,i){try{if(e){let r=s.getBuffered(e),n=[],a;for(a=0;ad&&(r[u-1].end=e[c].end):r.push(e[c])}else r.push(e[c])}else r=e;let n=0,a,o=t,l=t;for(let c=0;c=u&&tt.startCC||s&&s.cc{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(Ml(e));return}else e.gap=!1;let c=this.loader=e.loader=n?new n(r):new a(r),u=Ol(e),d=Dl(r.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Pl};e.stats=c.stats,c.load(u,h,{onSuccess:(f,m,g,p)=>{this.resetLoader(e,c);let v=f.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:e,part:null,payload:v,networkDetails:p})},onError:(f,m,g,p)=>{this.resetLoader(e,c),l(new je({type:j.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:we({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:p}))},onAbort:(f,m,g)=>{this.resetLoader(e,c),l(new je({type:j.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,c),l(new je({type:j.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:f}))},onProgress:(f,m,g,p)=>{t&&t({frag:e,part:null,payload:g,networkDetails:p})}})})}loadPart(e,t,i){this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Ml(e,t));return}let c=this.loader=e.loader=n?new n(r):new a(r),u=Ol(e,t),d=Dl(r.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Pl};t.stats=c.stats,c.load(u,h,{onSuccess:(f,m,g,p)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:p};i(v),o(v)},onError:(f,m,g,p)=>{this.resetLoader(e,c),l(new je({type:j.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:we({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:p}))},onAbort:(f,m,g)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new je({type:j.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,c),l(new je({type:j.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:f}))}})})}updateStatsFromPart(e,t){let i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){let l=Math.round(e.duration/t.duration),c=Math.min(Math.round(i.loaded/n),l),d=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+d}else i.total=Math.max(i.loaded,i.total);let a=i.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function Ol(s,e=null){let t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(K(r)&&K(n)){var a;let o=r,l=n;if(s.sn==="initSegment"&&((a=s.decryptdata)==null?void 0:a.method)==="AES-128"){let c=n-r;c%16&&(l=n+(16-c%16)),r!==0&&(i.resetIV=!0,o=r-16)}i.rangeStart=o,i.rangeEnd=l}return i}function Ml(s,e){let t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:j.MEDIA_ERROR,details:D.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new je(i)}var je=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},zn=class{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}},Xn=class{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}};function lg(s){let e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?jt(s,0,e-t):s}var Qn=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let r=0;r<4;r++)i[r]=t.getUint32(r*4);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,c=l[0],u=l[1],d=l[2],h=l[3],f=new Uint32Array(256),m=0,g=0,p=0;for(p=0;p<256;p++)p<128?f[p]=p<<1:f[p]=p<<1^283;for(p=0;p<256;p++){let v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;let E=f[m],T=f[E],x=f[T],_=f[v]*257^v*16843008;r[m]=_<<24|_>>>8,n[m]=_<<16|_>>>16,a[m]=_<<8|_>>>24,o[m]=_,_=x*16843009^T*65537^E*257^m*16843008,c[v]=_<<24|_>>>8,u[v]=_<<16|_>>>16,d[v]=_<<8|_>>>24,h[v]=_,m?(m=E^f[f[f[x^E]]],g^=f[f[g]]):m=g=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),i=!0,r=0;for(;rthis.subtle?(this.logOnce("WebCrypto AES decrypt"),new zn(this.subtle,new Uint8Array(i)).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(A.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i)))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);let r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%cg;return i!==e.length&&(t=jt(e,0,i),this.remainderData=jt(e,i)),t}logOnce(e){this.logEnabled&&(A.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},ug={toString:function(s){let e="",t=s.length;for(let i=0;io.end){let d=a>u;(a{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${n.part?" p: "+n.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,r).then(n=>{if(!n)return;let a=this.state;if(this.fragContextChanged(e)){(a===C.FRAG_LOADING||!this.fragCurrent&&a===C.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=C.IDLE);return}"payload"in n&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(y.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(`Frag error: ${(n==null?void 0:n.message)||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===ke.APPENDING){let n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===ke.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,i=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:i};this.hls.trigger(y.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{if(!i||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{let{hls:r}=this,{payload:n}=i,a=e.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&a.method==="AES-128"){let o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer).catch(l=>{throw r.trigger(y.ERROR,{type:j.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{let c=self.performance.now();return r.trigger(y.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:c}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");let i=e.frag.stats;this.state=C.IDLE,e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var i,r,n,a;let o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===z.MAIN?"level":"track"} ${e.level} (frag:[${((i=e.startPTS)!=null?i:NaN).toFixed(3)}-${((r=e.endPTS)!=null?r:NaN).toFixed(3)}] > buffer:${o?ug.toString(he.getBuffered(o)):"(detached)"})`),e.sn!=="initSegment"){var l;if(e.type!==z.SUBTITLE){let u=e.elementaryStreams;if(!Object.keys(u).some(d=>!!u[d])){this.state=C.IDLE;return}}let c=(l=this.levels)==null?void 0:l[e.level];c!=null&&c.fragmentError&&(this.log(`Resetting level fragment error count of ${c.fragmentError} on frag buffered`),c.fragmentError=0)}this.state=C.IDLE,o&&(!this.loadedmetadata&&e.type==z.MAIN&&o.buffered.length&&((n=this.fragCurrent)==null?void 0:n.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:i,part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(l=>!l),o=new Xi(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var n;let a=t==null?void 0:t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(y.KEY_LOADED,u),this.state===C.KEY_LOADING&&(this.state=C.IDLE),u}),this.hls.trigger(y.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){let u=a.partList;if(u&&r){i>e.end&&a.fragmentHint&&(e=a.fragmentHint);let d=this.getNextPart(u,e,i);if(d>-1){let h=u[d];this.log(`Loading part sn: ${e.sn} p: ${h.index} cc: ${e.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${d}-${u.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=h.start+h.duration,this.state=C.FRAG_LOADING;let f;return o?f=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(e,h,t,r)).catch(m=>this.handleFragLoadError(m)):f=this.doFragPartsLoad(e,h,t,r).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(y.FRAG_LOADING,{frag:e,part:h,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),K(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;let l=this.config.progressive,c;return l&&o?c=o.then(u=>!u||this.fragContextChanged(u==null?void 0:u.frag)?null:this.fragmentLoader.load(e,r)).catch(u=>this.handleFragLoadError(u)):c=Promise.all([this.fragmentLoader.load(e,l?r:void 0),o]).then(([u])=>(!l&&u&&r&&r(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,i,r){return new Promise((n,a)=>{var o;let l=[],c=(o=i.details)==null?void 0:o.partList,u=d=>{this.fragmentLoader.loadPart(e,d,r).then(h=>{l[d.index]=h;let f=h.part;this.hls.trigger(y.FRAG_LOADED,h);let m=Ll(i,e.sn,d.index+1)||pc(c,e.sn,d.index+1);if(m)u(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;e.data&&t.details===D.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(y.ERROR,t)}else this.hls.trigger(y.ERROR,{type:j.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.IDLE);return}let{frag:i,part:r,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a),this.updateLevelTiming(i,r,n,e.partial)}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:r,sn:n,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of level ${r}. The current chunk will not be buffered.`),null;let o=t[r],l=a>-1?Ll(o,n,a):null,c=l?l.fragment:Gm(o,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(e,t,i,r,n){var a;if(!e||this.state!==C.PARSING)return;let{data1:o,data2:l}=e,c=o;if(o&&l&&(c=He(o,l)),!((a=c)!=null&&a.length))return;let u={type:e.type,frag:t,part:i,chunkMeta:r,parent:t.type,data:c};if(this.hls.trigger(y.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!he.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let i=t.currentTime,r=he.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){let i=this.getLoadPosition();return K(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){let{config:{maxBufferHole:r}}=this,n=he.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&n.nextStart=r?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=z.MAIN){let i=this.fragmentTracker.getAppendedFrag(e,z.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i=t.fragments,r=i.length;if(!r)return null;let{config:n}=this,a=i[0].start,o;if(t.live){let l=n.initialLiveManifestSize;if(rt}getNextFragmentLoopLoading(e,t,i,r,n){let a=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(o===null)return o;if(e=o,a&&e&&!e.gap&&i.nextStart){let l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r);if(l!==null&&i.len+l.len>=n)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let r=-1,n=!1,a=!0;for(let o=0,l=e.length;o-1&&ii.start&&i.loaded}getInitialLiveFragment(e,t){let i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=Hm(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];i.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=Wm(t,i.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){let{config:r}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=i,{fragmentHint:l}=i,{maxFragLookUpTolerance:c}=r,u=i.partList,d=!!(r.lowLatencyMode&&u!=null&&u.length&&l);d&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let h;if(et-c?0:c;h=ir(n,a,e,f)}else h=a[a.length-1];if(h){let f=h.sn-i.startSN,m=this.fragmentTracker.getState(h);if((m===ke.OK||m===ke.PARTIAL&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!d||u[0].fragment.sn>h.sn)&&n&&h.level===n.level){let p=a[f+1];h.sn=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&i.duration>r&&(n${e.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${r}`),c}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;if(i ${(r=this.fragCurrent)==null?void 0:r.url}`);return}let n=t.details===D.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);let a=t.errorAction,{action:o,retryCount:l=0,retryConfig:c}=a||{};if(a&&o===De.RetryRequest&&c){this.resetStartWhenNotLoaded(this.levelLastLoaded);let u=Ha(c,l);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${u}ms`),a.resolved=!0,this.retryDate=self.performance.now()+u,this.state=C.FRAG_LOADING_WAITING_RETRY}else if(c&&a)if(this.resetFragmentErrors(e),l.5;n&&this.reduceMaxBufferLength(r.len,(t==null?void 0:t.duration)||10);let a=!n;return a&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===z.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==C.STOPPED&&(this.state=C.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;let r=he.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===C.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=C.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;let t=e?e.details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){var n;let a=i.details;if(!a){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,c)=>{let u=e.elementaryStreams[c];if(u){let d=u.endPTS-u.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${d})`),l||!1;let h=r?0:mc(a,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:a,level:i,drift:h,type:c,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)&&((n=this.transmuxer)==null?void 0:n.error)===null){let l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(i.fragmentError===0&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(y.ERROR,{type:j.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=C.PARSED,this.hls.trigger(y.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}},rr=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,i;if(e.length)e.length===1?i=e[0]:i=dg(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}};function dg(s,e){let t=new Uint8Array(e),i=0;for(let r=0;r0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ze.audioId3,duration:Number.POSITIVE_INFINITY});r{if(K(s))return s*90;let i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};function pg(s,e,t,i){let r,n,a,o,l=navigator.userAgent.toLowerCase(),c=i,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];r=((e[t+2]&192)>>>6)+1;let d=(e[t+2]&60)>>>2;if(d>u.length-1){let h=new Error(`invalid ADTS sampling index:${d}`);s.emit(y.ERROR,y.ERROR,{type:j.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!0,error:h,reason:h.message});return}return a=(e[t+2]&1)<<2,a|=(e[t+3]&192)>>>6,A.log(`manifest codec:${i}, ADTS type:${r}, samplingIndex:${d}`),/firefox/i.test(l)?d>=6?(r=5,o=new Array(4),n=d-3):(r=2,o=new Array(2),n=d):l.indexOf("android")!==-1?(r=2,o=new Array(2),n=d):(r=5,o=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&d>=6?n=d-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(d>=6&&a===1||/vivaldi/i.test(l))||!i&&a===1)&&(r=2,o=new Array(2)),n=d)),o[0]=r<<3,o[0]|=(d&14)>>1,o[1]|=(d&1)<<7,o[1]|=a<<3,r===5&&(o[1]|=(n&14)>>1,o[2]=(n&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:u[d],channelCount:a,codec:"mp4a.40."+r,manifestCodec:c}}function xc(s,e){return s[e]===255&&(s[e+1]&246)===240}function _c(s,e){return s[e+1]&1?7:9}function Va(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function yg(s,e){return e+5=s.length)return!1;let i=Va(s,e);if(i<=t)return!1;let r=e+i;return r===s.length||nr(s,r)}return!1}function Sc(s,e,t,i,r){if(!s.samplerate){let n=pg(e,t,i,r);if(!n)return;s.config=n.config,s.samplerate=n.samplerate,s.channelCount=n.channelCount,s.codec=n.codec,s.manifestCodec=n.manifestCodec,A.log(`parsed codec:${s.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function bc(s){return 1024*9e4/s}function Tg(s,e){let t=_c(s,e);if(e+t<=s.length){let i=Va(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Ac(s,e,t,i,r){let n=bc(s.samplerate),a=i+r*n,o=Tg(e,t),l;if(o){let{frameLength:d,headerLength:h}=o,f=h+d,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+f);let g={unit:l,pts:a};return m||s.samples.push(g),{sample:g,length:f,missing:m}}let c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}var Os=null,xg=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],_g=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Sg=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],bg=[0,1,1,4];function Rc(s,e,t,i,r){if(t+24>e.length)return;let n=Lc(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=i+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=n.channelCount,s.samplerate=n.sampleRate,s.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function Lc(s,e){let t=s[e+1]>>3&3,i=s[e+1]>>1&3,r=s[e+2]>>4&15,n=s[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){let a=s[e+2]>>1&1,o=s[e+3]>>6,l=t===3?3-i:i===3?3:4,c=xg[l*14+r-1]*1e3,d=_g[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=Sg[t][i],m=bg[i],g=f*8*m,p=Math.floor(f*c/d+a)*m;if(Os===null){let T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Os=T?parseInt(T[1]):0}return!!Os&&Os<=87&&i===2&&c>=224e3&&o===0&&(s[e+3]=s[e+3]|128),{sampleRate:d,channelCount:h,frameLength:p,samplesPerFrame:g}}}function qa(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function Ic(s,e){return e+1{let a=mm(n);if(Rg.test(a.schemeIdUri)){let o=K(a.presentationTime)?a.presentationTime/a.timeScale:t+a.presentationTimeDelta/a.timeScale,l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let c=a.payload;i.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:ze.emsg,duration:l})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},kc=(s,e)=>{let t=0,i=5;e+=i;let r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=s[e];let o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<>l,t=t?t<e.length||e[t]!==11||e[t+1]!==119)return-1;let n=e[t+4]>>6;if(n>=3)return-1;let o=[48e3,44100,32e3][n],l=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(t+u>e.length)return-1;let d=e[t+6]>>5,h=0;d===2?h+=2:(d&1&&d!==1&&(h+=2),d&4&&(h+=2));let f=(e[t+6]<<8|e[t+7])>>12-h&1,g=[2,1,2,3,3,4,4,5][d]+f,p=e[t+5]>>3,v=e[t+5]&7,E=new Uint8Array([n<<6|p<<1|v>>2,(v&3)<<6|d<<3|f<<2|l>>4,l<<4&224]),T=1536/o*9e4,x=i+r*T,_=e.subarray(t,t+u);return s.config=E,s.channelCount=g,s.samplerate=o,s.samples.push({unit:_,pts:x}),u}var ta=class{constructor(){this.VideoSample=null}createVideoSample(e,t,i,r){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:r,length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,r;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){let n=i.units;r=n[n.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let i=t.samples,r=i.length;if(r){let n=i[r-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&A.log(e.pts+"/"+e.dts+":"+e.debug)}},ar=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&A.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t=8,i=8,r;for(let n=0;n{var d;switch(u.type){case 1:{let g=!1;l=!0;let p=u.data;if(c&&p.length>4){let v=new ar(p).readSliceType();(v===2||v===4||v===7||v===9)&&(g=!0)}if(g){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=g;break}case 5:l=!0,(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:{l=!0,lc(u.data,1,i.pts,t.samples);break}case 7:{var f,m;l=!0,c=!0;let g=u.data,v=new ar(g).readSPS();if(!e.sps||e.width!==v.width||e.height!==v.height||((f=e.pixelRatio)==null?void 0:f[0])!==v.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==v.pixelRatio[1]){e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.sps=[g],e.duration=n;let E=g.subarray(1,4),T="avc1.";for(let x=0;x<3;x++){let _=E[x].toString(16);_.length<2&&(_="0"+_),T+=_}e.codec=T}break}case 8:l=!0,e.pps=[u.data];break;case 9:l=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+u.type+" ");break}o&&l&&o.units.push(u)}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){let i=t.byteLength,r=e.naluState||0,n=r,a=[],o=0,l,c,u,d=-1,h=0;for(r===-1&&(d=0,h=t[0]&31,r=0,o=1);o=0){let f={data:t.subarray(d,c),type:h};a.push(f)}else{let f=this.getLastNalUnit(e.samples);f&&(n&&o<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),c>0&&(f.data=He(f.data,t.subarray(0,c)),f.state=0))}o=0&&r>=0){let f={data:t.subarray(d,i),type:h,state:r};a.push(f)}if(a.length===0){let f=this.getLastNalUnit(e.samples);f&&(f.data=He(f.data,t))}return e.naluState=r,a}},sa=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Qi(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){let r=e[t].unit;if(r.length<=16)return;let n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{let l=new Uint8Array(o);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t),r=0;for(let n=32;n{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)})}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){r();return}let n=e[t].units;for(;!(i>=n.length);i++){let a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}},Ie=188,ra=class s{constructor(e,t,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.videoParser=new ia}static probe(e){let t=s.syncOffset(e);return t>0&&A.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){let t=e.length,i=Math.min(Ie*5,t-Ie)+1,r=0;for(;r1&&(a===0&&o>2||l+Ie>i))return a}else{if(o)return-1;break}r++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:sc[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=s.createTrack("video"),this._audioTrack=s.createTrack("audio",r),this._id3Track=s.createTrack("id3"),this._txtTrack=s.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=r}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,r=!1){i||(this.sampleAes=null);let n,a=this._videoTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack,u=a.pid,d=a.pesData,h=o.pid,f=l.pid,m=o.pesData,g=l.pesData,p=null,v=this.pmtParsed,E=this._pmtId,T=e.length;if(this.remainderData&&(e=He(this.remainderData,e),T=e.length,this.remainderData=null),T>4,w;if(L>1){if(w=b+5+e[b+4],w===b+Ie)continue}else w=b+4;switch(k){case u:R&&(d&&(n=ui(d))&&this.videoParser.parseAVCPES(a,c,n,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(e.subarray(w,b+Ie)),d.size+=b+Ie-w);break;case h:if(R){if(m&&(n=ui(m)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}m={data:[],size:0}}m&&(m.data.push(e.subarray(w,b+Ie)),m.size+=b+Ie-w);break;case f:R&&(g&&(n=ui(g))&&this.parseID3PES(l,n),g={data:[],size:0}),g&&(g.data.push(e.subarray(w,b+Ie)),g.size+=b+Ie-w);break;case 0:R&&(w+=e[w]+1),E=this._pmtId=Lg(e,w);break;case E:{R&&(w+=e[w]+1);let P=Ig(e,w,this.typeSupported,i,this.observer);u=P.videoPid,u>0&&(a.pid=u,a.segmentCodec=P.segmentVideoCodec),h=P.audioPid,h>0&&(o.pid=h,o.segmentCodec=P.segmentAudioCodec),f=P.id3Pid,f>0&&(l.pid=f),p!==null&&!v&&(A.warn(`MPEG-TS PMT found at ${b} after unknown PID '${p}'. Backtracking to sync byte @${x} to parse all TS packets.`),p=null,b=x-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=k;break}}else _++;_>0&&or(this.observer,new Error(`Found ${_} TS packet/s that do not start with 0x47`)),a.pesData=d,o.pesData=m,l.pesData=g;let I={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return r&&this.extractRemainingSamples(I),I}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:i,id3Track:r,textTrack:n}=e,a=i.pesData,o=t.pesData,l=r.pesData,c;if(a&&(c=ui(a))?(this.videoParser.parseAVCPES(i,n,c,!0,this._duration),i.pesData=null):i.pesData=a,o&&(c=ui(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break;case"ac3":this.parseAC3PES(t,c);break}t.pesData=null}else o!=null&&o.size&&A.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(c=ui(l))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=l}demuxSampleAes(e,t,i){let r=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new sa(this.observer,this.config,t);return this.decrypt(r,n)}decrypt(e,t){return new Promise(i=>{let{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}destroy(){this._duration=0}parseAACPES(e,t){let i=0,r=this.aacOverFlow,n=t.data;if(r){this.aacOverFlow=null;let d=r.missing,h=r.sample.unit.byteLength;if(d===-1)n=He(r.sample.unit,n);else{let f=h-d;r.sample.unit.set(n.subarray(0,d),f),e.samples.push(r.sample),i=r.missing}}let a,o;for(a=i,o=n.length;a0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){A.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=Te({},t,{type:this._videoTrack?ze.emsg:ze.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}};function na(s,e){return((s[e+1]&31)<<8)+s[e+2]}function Lg(s,e){return(s[e+10]&31)<<8|s[e+11]}function Ig(s,e,t,i,r){let n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(s[e+1]&15)<<8|s[e+2],o=e+3+a-4,l=(s[e+10]&15)<<8|s[e+11];for(e+=12+l;e0){let d=e+5,h=u;for(;h>2;){switch(s[d]){case 106:t.ac3!==!0?A.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=c,n.segmentAudioCodec="ac3");break}let m=s[d+1]+2;d+=m,h-=m}}break;case 194:case 135:return or(r,new Error("Unsupported EC-3 in M2TS found")),n;case 36:return or(r,new Error("Unsupported HEVC in M2TS found")),n}e+=u+5}return n}function or(s,e,t){A.warn(`parsing error: ${e.message}`),s.emit(y.ERROR,y.ERROR,{type:j.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Tn(s){A.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function ui(s){let e=0,t,i,r,n,a,o=s.data;if(!s||s.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=He(o[0],o[1]),o.splice(1,1);if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(i=(t[4]<<8)+t[5],i&&i>s.size-6)return null;let c=t[7];c&192&&(n=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,c&64?(a=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,n-a>60*9e4&&(A.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=t[8];let u=r+9;if(s.size<=u)return null;s.size-=u;let d=new Uint8Array(s.size);for(let h=0,f=o.length;hm){u-=m;continue}else t=t.subarray(u),m-=u,u=0;d.set(t,e),e+=m}return i&&(i-=r+3),{data:d,pts:n,dts:a,len:i}}return null}var aa=class extends Zi{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=Wi(e,0),i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&Ka(t)!==void 0&&kc(e,i)<=16)return!1;for(let r=e.length;i>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),r=0,i=8;r>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return s.box(s.types.mdia,s.mdhd(e.timescale,e.duration),s.hdlr(e.type),s.minf(e))}static mfhd(e){return s.box(s.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?s.box(s.types.minf,s.box(s.types.smhd,s.SMHD),s.DINF,s.stbl(e)):s.box(s.types.minf,s.box(s.types.vmhd,s.VMHD),s.DINF,s.stbl(e))}static moof(e,t,i){return s.box(s.types.moof,s.mfhd(e),s.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=s.trak(e[t]);return s.box.apply(null,[s.types.moov,s.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(s.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=s.trex(e[t]);return s.box.apply(null,[s.types.mvex,...i])}static mvhd(e,t){t*=e;let i=Math.floor(t/(yt+1)),r=Math.floor(t%(yt+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return s.box(s.types.mvhd,n)}static sdtp(e){let t=e.samples||[],i=new Uint8Array(4+t.length),r,n;for(r=0;r>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));let o=s.box(s.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,c=e.height,u=e.pixelRatio[0],d=e.pixelRatio[1];return s.box(s.types.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,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,s.box(s.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),s.box(s.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){let t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){let t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return s.box(s.types.mp4a,s.audioStsd(e),s.box(s.types.esds,s.esds(e)))}static mp3(e){return s.box(s.types[".mp3"],s.audioStsd(e))}static ac3(e){return s.box(s.types["ac-3"],s.audioStsd(e),s.box(s.types.dac3,e.config))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?s.box(s.types.stsd,s.STSD,s.mp3(e)):e.segmentCodec==="ac3"?s.box(s.types.stsd,s.STSD,s.ac3(e)):s.box(s.types.stsd,s.STSD,s.mp4a(e)):s.box(s.types.stsd,s.STSD,s.avc1(e))}static tkhd(e){let t=e.id,i=e.duration*e.timescale,r=e.width,n=e.height,a=Math.floor(i/(yt+1)),o=Math.floor(i%(yt+1));return s.box(s.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,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,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let i=s.sdtp(e),r=e.id,n=Math.floor(t/(yt+1)),a=Math.floor(t%(yt+1));return s.box(s.types.traf,s.box(s.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),s.box(s.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),s.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,s.box(s.types.trak,s.tkhd(e),s.mdia(e))}static trex(e){let t=e.id;return s.box(s.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i=e.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n),o,l,c,u,d,h;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o>>24&255,c>>>16&255,c>>>8&255,c&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return s.box(s.types.trun,a)}static initSegment(e){s.types||s.init();let t=s.moov(e);return He(s.FTYP,t)}};Ae.types=void 0;Ae.HDLR_TYPES=void 0;Ae.STTS=void 0;Ae.STSC=void 0;Ae.STCO=void 0;Ae.STSZ=void 0;Ae.VMHD=void 0;Ae.SMHD=void 0;Ae.STSD=void 0;Ae.FTYP=void 0;Ae.DINF=void 0;var Cc=9e4;function Wa(s,e,t=1,i=!1){let r=s*e*t;return i?Math.round(r):r}function Dg(s,e,t=1,i=!1){return Wa(s,e,1/t,i)}function Gi(s,e=!1){return Wa(s,1e3,1/Cc,e)}function kg(s,e=1){return Wa(s,Cc,1/e)}var wg=10*1e3,Nl=1024,Cg=1152,Pg=1536,di=null,xn=null,gi=class{constructor(e,t,i,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,di===null){let a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);di=a?parseInt(a[1]):0}if(xn===null){let n=navigator.userAgent.match(/Safari\/(\d+)/i);xn=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){A.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){A.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){A.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,i=e.reduce((r,n)=>{let a=n.pts-r;return a<-4294967296?(t=!0,Ke(r,n.pts)):a>0?r:n.pts},e[0].pts);return t&&A.debug("PTS rollover detected"),i}remux(e,t,i,r,n,a,o,l){let c,u,d,h,f,m,g=n,p=n,v=e.pid>-1,E=t.pid>-1,T=t.samples.length,x=e.samples.length>0,_=o&&T>0||T>1;if((!v||x)&&(!E||_)||this.ISGenerated||o){if(this.ISGenerated){var b,R,k,L;let W=this.videoTrackConfig;W&&(t.width!==W.width||t.height!==W.height||((b=t.pixelRatio)==null?void 0:b[0])!==((R=W.pixelRatio)==null?void 0:R[0])||((k=t.pixelRatio)==null?void 0:k[1])!==((L=W.pixelRatio)==null?void 0:L[1]))&&this.resetInitSegment()}else d=this.generateIS(e,t,n,a);let w=this.isVideoContiguous,P=-1,O;if(_&&(P=Og(t.samples),!w&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,P>0){A.warn(`[mp4-remuxer]: Dropped ${P} out of ${T} video samples due to a missing keyframe`);let W=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,p+=(t.samples[0].pts-W)/t.inputTimeScale,O=p}else P===-1&&(A.warn(`[mp4-remuxer]: No keyframe found out of ${T} video samples`),m=!1);if(this.ISGenerated){if(x&&_){let W=this.getVideoStartPts(t.samples),$=(Ke(e.samples[0].pts,W)-W)/t.inputTimeScale;g+=Math.max(0,$),p+=Math.max(0,-$)}if(x){if(e.samplerate||(A.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,g,this.isAudioContiguous,a,E||_||l===z.AUDIO?p:void 0),_){let W=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(A.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,n,a)),c=this.remuxVideo(t,p,w,W)}}else _&&(c=this.remuxVideo(t,p,w,0));c&&(c.firstKeyFrame=P,c.independent=P!==-1,c.firstKeyFramePTS=O)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=Pc(i,n,this._initPTS,this._initDTS)),r.samples.length&&(h=Oc(r,n,this._initPTS))),{audio:u,video:c,initSegment:d,independent:m,text:h,id3:f}}generateIS(e,t,i,r){let n=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS,u=!c||r,d="audio/mp4",h,f,m;if(u&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(d="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):Ae.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(m=e.inputTimeScale,!c||m!==c.timescale?h=f=n[0].pts-Math.round(m*i):u=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Ae.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(m=t.inputTimeScale,!c||m!==c.timescale){let g=this.getVideoStartPts(a),p=Math.round(m*i);f=Math.min(f,Ke(a[0].dts,g)-p),h=Math.min(h,g-p)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:m},this._initDTS={baseTime:f,timescale:m}):h=m=void 0,{tracks:l,initPTS:h,timescale:m}}remuxVideo(e,t,i,r){let n=e.inputTimeScale,a=e.samples,o=[],l=a.length,c=this._initPTS,u=this.nextAvcDts,d=8,h=this.videoSampleDuration,f,m,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!i||u===null){let H=t*n,B=a[0].pts-Ke(a[0].dts,a[0].pts);di&&u!==null&&Math.abs(H-B-u)<15e3?i=!0:u=H-B}let E=c.baseTime*n/c.timescale;for(let H=0;H0?H-1:H].dts&&(v=!0)}v&&a.sort(function(H,B){let ee=H.dts-B.dts,X=H.pts-B.pts;return ee||X}),f=a[0].dts,m=a[a.length-1].dts;let T=m-f,x=T?Math.round(T/(l-1)):h||e.inputTimeScale/30;if(i){let H=f-u,B=H>x,ee=H<-1;if((B||ee)&&(B?A.warn(`AVC: ${Gi(H,!0)} ms (${H}dts) hole between fragments detected at ${t.toFixed(3)}`):A.warn(`AVC: ${Gi(-H,!0)} ms (${H}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ee||u>=a[0].pts||di)){f=u;let X=a[0].pts-H;if(B)a[0].dts=f,a[0].pts=X;else for(let ae=0;aeX);ae++)a[ae].dts-=H,a[ae].pts-=H;A.log(`Video: Initial PTS/DTS adjusted: ${Gi(X,!0)}/${Gi(f,!0)}, delta: ${Gi(H,!0)} ms`)}}f=Math.max(0,f);let _=0,I=0,b=f;for(let H=0;H0?B.dts-a[H-1].dts:x;if(ae=H>0?B.pts-a[H-1].pts:x,ve.stretchShortVideoTrack&&this.nextAudioPts!==null){let $e=Math.floor(ve.maxBufferHole*n),Ci=(r?g+r*n:this.nextAudioPts)-B.pts;Ci>$e?(h=Ci-_e,h<0?h=_e:w=!0,A.log(`[mp4-remuxer]: It is approximately ${Ci/90} ms to the next segment; using duration ${h/90} ms for the last video frame.`)):h=_e}else h=_e}let ye=Math.round(B.pts-B.dts);P=Math.min(P,h),W=Math.max(W,h),O=Math.min(O,ae),q=Math.max(q,ae),o.push(new cr(B.key,h,X,ye))}if(o.length){if(di){if(di<70){let H=o[0].flags;H.dependsOn=2,H.isNonSync=0}}else if(xn&&q-O0&&(r&&Math.abs(E-v)<9e3||Math.abs(Ke(g[0].pts-T,E)-v)<20*u),g.forEach(function($){$.pts=Ke($.pts-T,E)}),!i||v<0){if(g=g.filter($=>$.pts>=0),!g.length)return;n===0?v=0:r&&!m?v=Math.max(0,E):v=g[0].pts}if(e.segmentCodec==="aac"){let $=this.config.maxAudioFramesDrift;for(let Z=0,ne=v;Z=$*u&&X0){b+=p;try{I=new Uint8Array(b)}catch(X){this.observer.emit(y.ERROR,y.ERROR,{type:j.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,error:X,bytes:b,reason:`fail allocating audio mdat ${b}`});return}h||(new DataView(I.buffer).setUint32(0,b),I.set(Ae.types.mdat,4))}else return;I.set(H,p);let ee=H.byteLength;p+=ee,f.push(new cr(!0,c,ee,0)),_=B}let k=f.length;if(!k)return;let L=f[f.length-1];this.nextAudioPts=v=_+l*L.duration;let w=h?new Uint8Array(0):Ae.moof(e.sequenceNumber++,x/l,Te({},e,{samples:f}));e.samples=[];let P=x/a,O=v/a,q={data1:w,data2:I,startPTS:P,endPTS:O,startDTS:P,endDTS:O,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,q}remuxEmptyAudio(e,t,i,r){let n=e.inputTimeScale,a=e.samplerate?e.samplerate:n,o=n/a,l=this.nextAudioPts,c=this._initDTS,u=c.baseTime*9e4/c.timescale,d=(l!==null?l:r.startDTS*n)+u,h=r.endDTS*n+u,f=o*Nl,m=Math.ceil((h-d)/f),g=lr.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(A.warn("[mp4-remuxer]: remux empty Audio"),!g){A.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}let p=[];for(let v=0;v4294967296;)s+=t;return s}function Og(s){for(let e=0;ea.pts-o.pts);let n=s.samples;return s.samples=[],{samples:n}}var cr=class{constructor(e,t,i,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}},oa=class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(am(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let r=this.initData=ac(e);r.audio&&(t=Fl(r.audio,le.AUDIO)),r.video&&(i=Fl(r.video,le.VIDEO));let n={};r.audio&&r.video?n.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:r.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?n.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:A.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(e,t,i,r,n,a){var o,l;let{initPTS:c,lastEndTime:u}=this,d={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};K(u)||(u=this.lastEndTime=n||0);let h=t.samples;if(!(h!=null&&h.length))return d;let f={initPTS:void 0,timescale:1},m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(h),m=this.initData),!((l=m)!=null&&l.length))return A.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);let g=lm(h,m),p=om(m,h),v=p===null?n:p;(Mg(c,v,n,g)||f.timescale!==c.timescale&&a)&&(f.initPTS=v-n,c&&c.timescale===1&&A.warn(`Adjusting initPTS by ${f.initPTS-c.baseTime}`),this.initPTS=c={baseTime:f.initPTS,timescale:1});let E=e?v-c.baseTime/c.timescale:u,T=E+g;um(m,h,c.baseTime/c.timescale),g>0?this.lastEndTime=T:(A.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let x=!!m.audio,_=!!m.video,I="";x&&(I+="audio"),_&&(I+="video");let b={data1:h,startPTS:E,startDTS:E,endPTS:T,endDTS:T,type:I,hasAudio:x,hasVideo:_,nb:1,dropped:0};return d.audio=b.type==="audio"?b:void 0,d.video=b.type!=="audio"?b:void 0,d.initSegment=f,d.id3=Pc(i,n,c,c),r.samples.length&&(d.text=Oc(r,n,c)),d}};function Mg(s,e,t,i){if(s===null)return!0;let r=Math.max(i,1),n=e-s.baseTime/s.timescale;return Math.abs(n-t)>r}function Fl(s,e){let t=s==null?void 0:s.codec;if(t&&t.length>4)return t;if(e===le.AUDIO){if(t==="ec-3"||t==="ac-3"||t==="alac")return t;if(t==="fLaC"||t==="Opus")return Qs(t,!1);let i="mp4a.40.5";return A.info(`Parsed audio codec "${t}" or audio object type not handled. Using "${i}"`),i}return A.warn(`Unhandled video codec "${t}"`),t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":"avc1.42e01e"}var ut;try{ut=self.performance.now.bind(self.performance)}catch{A.debug("Unable to use Performance API on this environment"),ut=yi==null?void 0:yi.Date.now}var Ks=[{demux:Zn,remux:oa},{demux:ra,remux:gi},{demux:Jn,remux:gi},{demux:aa,remux:gi}];Ks.splice(2,0,{demux:ea,remux:gi});var ur=class{constructor(e,t,i,r,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.vendor=r,this.id=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,r){let n=i.transmuxing;n.executeStart=ut();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);let{contiguous:c,discontinuity:u,trackSwitch:d,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:g,videoCodec:p,defaultInitPts:v,duration:E,initSegmentData:T}=l,x=Ng(a,t);if(x&&x.method==="AES-128"){let R=this.getDecrypter();if(R.isSync()){let k=R.softwareDecrypt(a,x.key.buffer,x.iv.buffer);if(i.part>-1&&(k=R.flush()),!k)return n.executeEnd=ut(),_n(i);a=new Uint8Array(k)}else return this.decryptionPromise=R.webCryptoDecrypt(a,x.key.buffer,x.iv.buffer).then(k=>{let L=this.push(k,null,i);return this.decryptionPromise=null,L}),this.decryptionPromise}let _=this.needsProbing(u,d);if(_){let R=this.configureTransmuxer(a);if(R)return A.warn(`[transmuxer] ${R.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:j.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),n.executeEnd=ut(),_n(i)}(u||d||m||_)&&this.resetInitSegment(T,g,p,E,t),(u||m||_)&&this.resetInitialTimestamp(v),c||this.resetContiguity();let I=this.transmux(a,x,f,h,i),b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,n.executeEnd=ut(),I}flush(e){let t=e.transmuxing;t.executeStart=ut();let{decrypter:i,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return n.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(i){let d=i.flush();d&&a.push(this.push(d,null,e))}let{demuxer:l,remuxer:c}=this;if(!l||!c)return t.executeEnd=ut(),[_n(e)];let u=l.flush(o);return Hs(u)?u.then(d=>(this.flushRemux(a,d,e),a)):(this.flushRemux(a,u,e),a)}flushRemux(e,t,i){let{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;A.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);let u=this.remuxer.remux(r,n,a,o,c,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=ut()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,n){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,r),o.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,r,n):a=this.transmuxUnencrypted(e,i,r,n),a}transmuxUnencrypted(e,t,i,r){let{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,l,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,n){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,r,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){let{config:t,observer:i,typeSupported:r,vendor:n}=this,a;for(let h=0,f=Ks.length;h0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var _n=s=>({remuxResult:{},chunkMeta:s});function Hs(s){return"then"in s&&s.then instanceof Function}var la=class{constructor(e,t,i,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=n||null}},ca=class{constructor(e,t,i,r,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a}},Mc={exports:{}};(function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function r(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function n(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new r(u,d||l,h),m=t?t+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,d;if(this._eventsCount===0)return c;for(d in u=this._events)e.call(u,d)&&c.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,m=new Array(f);h{u=u||{},u.frag=this.frag,u.id=this.id,c===y.ERROR&&(this.error=u.error),this.hls.trigger(c,u)};this.observer=new Ya,this.observer.on(y.FRAG_DECRYPTED,a),this.observer.on(y.ERROR,a);let o=zt(n.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker!="undefined"&&(n.workerPath||hg())){try{n.workerPath?(A.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=mg(n.workerPath)):(A.log(`injecting Web Worker for "${t}"`),this.workerContext=fg()),this.onwmsg=d=>this.onWorkerMessage(d);let{worker:u}=this.workerContext;u.addEventListener("message",this.onwmsg),u.onerror=d=>{let h=new Error(`${d.message} (${d.filename}:${d.lineno})`);n.enableWorker=!1,A.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:j.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:h})},u.postMessage({cmd:"init",typeSupported:l,vendor:"",id:t,config:JSON.stringify(n)})}catch(u){A.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.resetWorker(),this.error=null,this.transmuxer=new ur(this.observer,l,n,"",t)}return}this.transmuxer=new ur(this.observer,l,n,"",t)}resetWorker(){if(this.workerContext){let{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,r,n,a,o,l,c,u){var d,h;c.transmuxing.start=self.performance.now();let{transmuxer:f}=this,m=a?a.start:n.start,g=n.decryptdata,p=this.frag,v=!(p&&n.cc===p.cc),E=!(p&&c.level===p.level),T=p?c.sn-p.sn:-1,x=this.part?c.part-this.part.index:-1,_=T===0&&c.id>1&&c.id===(p==null?void 0:p.stats.chunkCount),I=!E&&(T===1||T===0&&(x===1||_&&x<=0)),b=self.performance.now();(E||T||n.stats.parsing.start===0)&&(n.stats.parsing.start=b),a&&(x||!I)&&(a.stats.parsing.start=b);let R=!(p&&((d=n.initSegment)==null?void 0:d.url)===((h=p.initSegment)==null?void 0:h.url)),k=new ca(v,I,l,E,m,R);if(!I||v||R){A.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id} discontinuity: ${v} trackSwitch: ${E} contiguous: ${I} accurateTimeOffset: ${l} timeOffset: ${m} initSegmentChange: ${R}`);let L=new la(i,r,t,o,u);this.configureTransmuxer(L)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:c,state:k},e instanceof ArrayBuffer?[e]:[]);else if(f){let L=f.push(e,g,c,k);Hs(L)?(f.async=!0,L.then(w=>{this.handleTransmuxComplete(w)}).catch(w=>{this.transmuxerError(w,c,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(L))}}flush(e){e.transmuxing.start=self.performance.now();let{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);Hs(i)||t.async?(Hs(i)||(i=Promise.resolve(i)),i.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")})):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(y.ERROR,{type:j.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}onWorkerMessage(e){let t=e.data;if(!(t!=null&&t.event)){A.warn(`worker message received with no ${t?"event name":"data"}`);return}let i=this.hls;if(this.hls)switch(t.event){case"init":{var r;let n=(r=this.workerContext)==null?void 0:r.objectURL;n&&self.URL.revokeObjectURL(n);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":A[t.data.logType]&&A[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data);break}}}configureTransmuxer(e){let{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}};function Nc(s,e){if(s.length!==e.length)return!1;for(let t=0;ts[r]!==e[r])}function ua(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}var Ul=100,da=class extends Ji{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",z.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.ERROR,this.onError,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.ERROR,this.onError,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n}){if(i==="main"){let a=t.cc;this.initPTS[t.cc]={baseTime:r,timescale:n},this.log(`InitPTS for cc: ${a} found from main: ${r}`),this.videoTrackCC=a,this.state===C.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=C.STOPPED;return}let t=this.lastCurrentTime;this.stopLoad(),this.setInterval(Ul),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=C.IDLE):(this.loadedmetadata=!1,this.state=C.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case C.IDLE:this.doTickIdle();break;case C.WAITING_TRACK:{var e;let{levels:i,trackId:r}=this,n=i==null||(e=i[r])==null?void 0:e.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=C.WAITING_INIT_PTS}break}case C.FRAG_LOADING_WAITING_RETRY:{var t;let i=performance.now(),r=this.retryDate;if(!r||i>=r||(t=this.media)!=null&&t.seeking){let{levels:n,trackId:a}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((n==null?void 0:n[a])||null),this.state=C.IDLE}break}case C.WAITING_INIT_PTS:{let i=this.waitingData;if(i){let{frag:r,part:n,cache:a,complete:o}=i;if(this.initPTS[r.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=C.FRAG_LOADING;let l=a.flush(),c={frag:r,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),o&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${r.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{let l=this.getLoadPosition(),c=he.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);Kn(c.end,this.config.maxFragLookUpTolerance,r)<0&&(this.log(`Waiting fragment cc (${r.cc}) @ ${r.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=C.IDLE}}this.onTickEnd()}clearWaitingFragment(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=C.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){let{hls:e,levels:t,media:i,trackId:r}=this,n=e.config;if(!i&&(this.startFragRequested||!n.startFragPrefetch)||!(t!=null&&t[r]))return;let a=t[r],o=a.details;if(!o||o.live&&this.levelLastLoaded!==a||this.waitForCdnTuneIn(o)){this.state=C.WAITING_TRACK;return}let l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,le.AUDIO,z.AUDIO));let c=this.getFwdBufferInfo(l,z.AUDIO);if(c===null)return;let{bufferedTrack:u,switchingTrack:d}=this;if(!d&&this._streamEnded(c,o)){e.trigger(y.BUFFER_EOS,{type:"audio"}),this.state=C.ENDED;return}let h=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,z.MAIN),f=c.len,m=this.getMaxBufferLength(h==null?void 0:h.len),g=o.fragments,p=g[0].start,v=this.flushing?this.getLoadPosition():c.end;if(d&&i){let _=this.getLoadPosition();u&&!vi(d.attrs,u.attrs)&&(v=_),o.PTSKnown&&_p||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=p+.05)}if(f>=m&&!d&&vh.end+o.targetduration;if(x||!(h!=null&&h.len)&&c.len){let _=this.getAppendedFrag(E.start,z.MAIN);if(_===null||(T||(T=!!_.gap||!!x&&h.len===0),x&&!T||T&&c.nextStart&&c.nextStart<_.end))return}this.loadFragment(E,a,v)}getMaxBufferLength(e){let t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Et(i))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?this.setInterval(Ul):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=C.IDLE,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=C.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(y.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}let{levels:r}=this,{details:n,id:a}=t;if(!r){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Audio track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);let o=r[a],l=0;if(n.live||(i=o.details)!=null&&i.live){this.checkLiveUpdate(n);let u=this.mainDetails;if(n.deltaUpdateFailed||!u)return;if(!o.details&&n.hasProgramDateTime&&u.hasProgramDateTime)sr(n,u),l=n.fragments[0].start;else{var c;l=this.alignPlaylists(n,o.details,(c=this.levelLastLoaded)==null?void 0:c.details)}}o.details=n,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(this.mainDetails||n,l),this.state===C.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=C.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let{frag:i,part:r,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}let u=c.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let d=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new dr(this.hls,z.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],m=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){let p=r?r.index:-1,v=p!==-1,E=new Xi(i.level,i.sn,i.stats.chunkCount,n.byteLength,p,v);h.push(n,m,d,"",i,r,u.totalduration,!1,E,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);let{cache:g}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new rr,complete:!1};g.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=C.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i.type!==z.AUDIO){if(!this.loadedmetadata&&i.type===z.MAIN){let n=this.videoBuffer||this.media;n&&he.getBuffered(n).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;let n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(y.AUDIO_TRACK_SWITCHED,we({},n)))}this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(z.AUDIO,t);break;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===ie.AUDIO_TRACK&&(this.state=C.IDLE);break;case D.BUFFER_APPEND_ERROR:case D.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;if(t.details===D.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==le.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==le.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===C.ENDED&&(this.state=C.IDLE);let i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,z.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:c,level:u}=o,{details:d}=u,{audio:h,text:f,id3:m,initSegment:g}=n;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l);return}if(this.state=C.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){let p=l.initSegment||l;this._bufferInitSegment(u,g.tracks,p,a),r.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:g.tracks})}if(h){let{startPTS:p,endPTS:v,startDTS:E,endDTS:T}=h;c&&(c.elementaryStreams[le.AUDIO]={startPTS:p,endPTS:v,startDTS:E,endDTS:T}),l.setElementaryStreamInfo(le.AUDIO,p,v,E,T),this.bufferFragmentData(h,l,c,a)}if(m!=null&&(t=m.samples)!=null&&t.length){let p=Te({id:i,frag:l,details:d},m);r.trigger(y.FRAG_PARSING_METADATA,p)}if(f){let p=Te({id:i,frag:l,details:d},f);r.trigger(y.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,i,r){if(this.state!==C.PARSING)return;t.video&&delete t.video;let n=t.audio;if(!n)return;n.id="audio";let a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(y.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:o};this.hls.trigger(y.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||r===ke.NOT_LOADED||r===ke.PARTIAL){var n;if(e.sn==="initSegment")this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=C.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragments[0].start!==t.details.fragments[0].start&&sr(t.details,a)}else this.startFragRequested=!0,super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){let{media:t,bufferedTrack:i}=this,r=i==null?void 0:i.attrs,n=e.attrs;t&&r&&(r.CHANNELS!==n.CHANNELS||i.name!==e.name||i.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(y.AUDIO_TRACK_SWITCHED,we({},e))}},ha=class extends zi{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Audio track with id:${i} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(r==null?void 0:r.length)!==(i==null?void 0:i.length)||i!=null&&i.some(o=>(r==null?void 0:r.indexOf(o))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,f)=>{h.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let l=this.hls.config.audioPreference;if(!n&&l){let h=st(l,o,li);if(h>-1)n=o[h];else{let f=st(l,this.tracks);n=this.tracks[f]}}let c=this.findTrackId(n);c===-1&&n&&(c=this.findTrackId(null));let u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i==null?void 0:i.join(",")}`),this.hls.trigger(y.AUDIO_TRACKS_UPDATED,u);let d=this.trackId;if(c!==-1&&d===-1)this.setAudioTrack(c);else if(o.length&&d===-1){var a;let h=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(y.ERROR,{type:j.MEDIA_ERROR,details:D.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}else this.shouldReloadPlaylist(n)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===ie.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&(this.requestScheduled=-1,this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){let r=this.currentTrack;if(r&&mi(e,r,li))return r;let n=st(e,this.tracksInGroup,li);if(n>-1){let a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(r){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=ig(e,t.levels,i,a,li);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=st(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;let i=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===i&&n||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(y.AUDIO_TRACK_SWITCHING,we({},r)),n))return;let a=this.switchParams(r.url,i==null?void 0:i.details,r.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i=n[c].start&&o<=n[c].end){a=n[c];break}let l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(e,t){let{startOffset:i,endOffset:r}=t;if(i===0&&r!==Number.POSITIVE_INFINITY){let n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;onew Et(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{let r=new Et(i);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,z.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(Bl)}onSubtitleTrackLoaded(e,t){var i;let{currentTrackId:r,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(i=l.details)!=null&&i.live){let d=this.mainDetails;if(a.deltaUpdateFailed||!d)return;let h=d.fragments[0];if(!l.details)a.hasProgramDateTime&&d.hasProgramDateTime?(sr(a,d),c=a.fragments[0].start):h&&(c=h.start,Gn(a,c));else{var u;c=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),c===0&&h&&(c=h.start,Gn(a,c))}}l.details=a,this.levelLastLoaded=l,o===r&&(!this.startFragRequested&&(this.mainDetails||!a.live)&&this.setStartPosition(this.mainDetails||a,c),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===C.IDLE&&(ir(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e,r=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&r!=null&&r.key&&r.iv&&r.method==="AES-128"){let a=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch(o=>{throw n.trigger(y.ERROR,{type:j.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{let l=performance.now();n.trigger(y.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=C.IDLE})}}doTick(){if(!this.media){this.state=C.IDLE;return}if(this.state===C.IDLE){let{currentTrackId:e,levels:t}=this,i=t==null?void 0:t[e];if(!i||!t.length||!i.details)return;let{config:r}=this,n=this.getLoadPosition(),a=he.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:o,len:l}=a,c=this.getFwdBufferInfo(this.media,z.MAIN),u=i.details,d=this.getMaxBufferLength(c==null?void 0:c.len)+u.levelTargetDuration;if(l>d)return;let h=u.fragments,f=h.length,m=u.edge,g=null,p=this.fragPrevious;if(om-v?0:v;g=ir(p,h,Math.max(h[0].start,o),E),!g&&p&&p.start{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}},ga=class extends zi{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null,i=Bs(this.media.textTracks);for(let n=0;n-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Bs(this.media.textTracks).forEach(t=>{hi(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(r==null?void 0:r.length)!==(i==null?void 0:i.length)||i!=null&&i.some(a=>(r==null?void 0:r.indexOf(a))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let a=this.tracks.filter(u=>!i||i.indexOf(u.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(u=>u.default)&&(this.selectDefaultTrack=!1),a.forEach((u,d)=>{u.id=d});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;let o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;let u=st(o,a);if(u>-1)n=a[u];else{let d=st(o,this.tracks);n=this.tracks[d]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i==null?void 0:i.join(",")}" group-id`),this.hls.trigger(y.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r-1){let n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}else{if(i)return null;{let n=st(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){let i=t.id,r=t.groupId,n=t.url;if(e)try{n=e.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(y.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:e||null})}}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=Bs(e.textTracks),i=this.currentTrack,r;if(i&&(r=t.filter(n=>ua(i,n))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==r&&(n.mode="disabled")}),r){let n=this.subtitleDisplay?"showing":"hidden";r.mode!==n&&(r.mode=n)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!K(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;let i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:e});return}let n=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));let{id:a,groupId:o="",name:l,type:c,url:u}=r;this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:u});let d=this.switchParams(r.url,i==null?void 0:i.details,r.details);this.loadPlaylist(d)}},pa=class{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,i){let r=this.queues[t];r.push(e),r.length===1&&!i&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t,i=new Promise(n=>{t=n}),r={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,e),i}executeNext(e){let t=this.queues[e];if(t.length){let i=t[0];try{i.execute()}catch(r){A.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${r}`),i.onError(r);let n=this.buffers[e];n!=null&&n.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}},$l=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ya=class{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=i=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{let{media:i,mediaSource:r}=this;this.log("Media source opened"),i&&(i.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:i,mediaSource:r})),r&&r.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:i,_objectUrl:r}=this;i!==r&&A.error(`Media element src was set while attaching MediaSource (${r} > ${i})`)},this.hls=e;let t="[buffer-controller]";this.appendSource=xm(zt(e.config.preferManagedMediaSource)),this.log=A.log.bind(A,t),this.warn=A.warn.bind(A,t),this.error=A.error.bind(A,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_APPENDING,this.onBufferAppending,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.BUFFER_EOS,this.onBufferEos,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.FRAG_PARSED,this.onFragParsed,this),e.on(y.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_APPENDING,this.onBufferAppending,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_EOS,this.onBufferEos,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.FRAG_PARSED,this.onFragParsed,this),e.off(y.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new pa(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){let i=this.media=t.media,r=zt(this.appendSource);if(i&&r){var n;let a=this.mediaSource=new r;this.log(`created media source: ${(n=a.constructor)==null?void 0:n.name}`),a.addEventListener("sourceopen",this._onMediaSourceOpen),a.addEventListener("sourceended",this._onMediaSourceEnded),a.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.addEventListener("startstreaming",this._onStartStreaming),a.addEventListener("endstreaming",this._onEndStreaming));let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");let l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,Gl(i),Ug(i,o),i.load()}catch{i.src=o}else i.src=o;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){let{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(this.log("media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(r){this.warn(`onMediaDetaching: ${r.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(e.removeAttribute("src"),this.appendSource&&Gl(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(y.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer()}resetBuffer(e){let t=this.sourceBuffer[e];try{if(t){var i;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}}catch(r){this.warn(`onBufferReset ${e}`,r)}}onBufferCodecs(e,t){let i=this.getSourceBufferTypes().length,r=Object.keys(t);if(r.forEach(a=>{if(i){let l=this.tracks[a];if(l&&typeof l.buffer.changeType=="function"){var o;let{id:c,codec:u,levelCodec:d,container:h,metadata:f}=t[a],m=fl(l.codec,l.levelCodec),g=m==null?void 0:m.replace($l,"$1"),p=fl(u,d),v=(o=p)==null?void 0:o.replace($l,"$1");if(p&&g!==v){a.slice(0,5)==="audio"&&(p=Qs(p,this.appendSource));let E=`${h};codecs=${p}`;this.appendChangeType(a,E),this.log(`switching codec ${m} to ${p}`),this.tracks[a]={buffer:l.buffer,codec:u,container:h,levelCodec:d,metadata:f,id:c}}}}else this.pendingTracks[a]=t[a]}),i)return;let n=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==n&&(this.log(`${n} bufferCodec event(s) expected ${r.join(",")}`),this.bufferCodecEventsExpected=n),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(e,t){let{operationQueue:i}=this,r={execute:()=>{let n=this.sourceBuffer[e];n&&(this.log(`changing ${e} sourceBuffer type to ${t}`),n.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};i.append(r,e,!!this.pendingTracks[e])}onBufferAppending(e,t){let{hls:i,operationQueue:r,tracks:n}=this,{data:a,type:o,frag:l,part:c,chunkMeta:u}=t,d=u.buffering[o],h=self.performance.now();d.start=h;let f=l.stats.buffering,m=c?c.stats.buffering:null;f.start===0&&(f.start=h),m&&m.start===0&&(m.start=h);let g=n.audio,p=!1;o==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||u.id===1||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);let v=l.start,E={execute:()=>{if(d.executeStart=self.performance.now(),p){let T=this.sourceBuffer[o];if(T){let x=v-T.timestampOffset;Math.abs(x)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${v} (delta: ${x}) sn: ${l.sn})`),T.timestampOffset=v)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{let T=self.performance.now();d.executeEnd=d.end=T,f.first===0&&(f.first=T),m&&m.first===0&&(m.first=T);let{sourceBuffer:x}=this,_={};for(let I in x)_[I]=he.getBuffered(x[I]);this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(y.BUFFER_APPENDED,{type:o,frag:l,part:c,chunkMeta:u,parent:l.type,timeRanges:_})},onError:T=>{let x={type:j.MEDIA_ERROR,parent:l.type,details:D.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:c,chunkMeta:u,error:T,err:T,fatal:!1};if(T.code===DOMException.QUOTA_EXCEEDED_ERR)x.details=D.BUFFER_FULL_ERROR;else{let _=++this.appendErrors[o];x.details=D.BUFFER_APPEND_ERROR,this.warn(`Failed ${_}/${i.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),_>=i.config.appendErrorMaxRetry&&(x.fatal=!0)}i.trigger(y.ERROR,x)}};r.append(E,o,!!this.pendingTracks[o])}onBufferFlushing(e,t){let{operationQueue:i}=this,r=n=>({execute:this.removeExecutor.bind(this,n,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(y.BUFFER_FLUSHED,{type:n})},onError:a=>{this.warn(`Failed to remove from ${n} SourceBuffer`,a)}});t.type?i.append(r(t.type),t.type):this.getSourceBufferTypes().forEach(n=>{i.append(r(n),n)})}onFragParsed(e,t){let{frag:i,part:r}=t,n=[],a=r?r.elementaryStreams:i.elementaryStreams;a[le.AUDIOVIDEO]?n.push("audiovideo"):(a[le.AUDIO]&&n.push("audio"),a[le.VIDEO]&&n.push("video"));let o=()=>{let l=self.performance.now();i.stats.buffering.end=l,r&&(r.stats.buffering.end=l);let c=r?r.stats:i.stats;this.hls.trigger(y.FRAG_BUFFERED,{frag:i,part:r,stats:c,id:i.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,n)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((r,n)=>{let a=this.sourceBuffer[n];return a&&(!t.type||t.type===n)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${n} sourceBuffer now EOS`))),r&&!!(!a||a.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(n=>{let a=this.sourceBuffer[n];a&&(a.ending=!1)});let{mediaSource:r}=this;if(!r||r.readyState!=="open"){r&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${r.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),r.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){let{hls:e,details:t,media:i}=this;if(!i||t===null||!this.getSourceBufferTypes().length)return;let n=e.config,a=i.currentTime,o=t.levelTargetDuration,l=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(K(l)&&l>0){let c=Math.max(l,o),u=Math.floor(a/o)*o-c;this.flushBackBuffer(a,o,u)}if(K(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){let c=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),u=Math.max(c,o),d=Math.floor(a/o)*o+u;this.flushFrontBuffer(a,o,d)}}flushBackBuffer(e,t,i){let{details:r,sourceBuffer:n}=this;this.getSourceBufferTypes().forEach(o=>{let l=n[o];if(l){let c=he.getBuffered(l);if(c.length>0&&i>c.start(0)){if(this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:i}),r!=null&&r.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l.ended&&c.end(c.length-1)-e{let o=r[a];if(o){let l=he.getBuffered(o),c=l.length;if(c<2)return;let u=l.start(c-1),d=l.end(c-1);if(i>u||e>=u&&e<=d)return;if(o.ended&&e-d<2*t){this.log(`Cannot flush ${a} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;let{details:e,hls:t,media:i,mediaSource:r}=this,n=e.fragments[0].start+e.totalduration,a=i.duration,o=K(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(e)):(n>o&&n>a||!K(a))&&(this.log(`Updating Media Source duration to ${n.toFixed(3)}`),r.duration=n)}updateSeekableRange(e){let t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&t!=null&&t.setLiveSeekableRange){let n=Math.max(0,i[0].start),a=Math.max(n,n+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${n}-${a}.`),t.setLiveSeekableRange(n,a)}}checkPendingTracks(){let{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,r=Object.keys(i).length;if(r&&(!e||r===2||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};let n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(y.BUFFER_CREATED,{tracks:this.tracks}),n.forEach(a=>{t.executeNext(a)});else{let a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(y.ERROR,{type:j.MEDIA_ERROR,details:D.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(e){let{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(let n in e)if(!t[n]){var r;let a=e[n];if(!a)throw Error(`source buffer exists for track ${n}, however track does not`);let o=((r=a.levelCodec)==null?void 0:r.indexOf(","))===-1?a.levelCodec:a.codec;o&&n.slice(0,5)==="audio"&&(o=Qs(o,this.appendSource));let l=`${a.container};codecs=${o}`;this.log(`creating sourceBuffer(${l})`);try{let c=t[n]=i.addSourceBuffer(l),u=n;this.addBufferListener(u,"updatestart",this._onSBUpdateStart),this.addBufferListener(u,"updateend",this._onSBUpdateEnd),this.addBufferListener(u,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(u,"bufferedchange",(d,h)=>{let f=h.removedRanges;f!=null&&f.length&&this.hls.trigger(y.BUFFER_FLUSHED,{type:n})}),this.tracks[n]={buffer:c,codec:o,container:a.container,levelCodec:a.levelCodec,metadata:a.metadata,id:a.id}}catch(c){this.error(`error while trying to add sourceBuffer: ${c.message}`),this.hls.trigger(y.ERROR,{type:j.MEDIA_ERROR,details:D.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:n,mimeType:l})}}}get mediaSrc(){var e,t;let i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}_onSBUpdateStart(e){let{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let{operationQueue:i}=this;i.current(e).onComplete(),i.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var i;let r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(y.ERROR,{type:j.MEDIA_ERROR,details:D.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});let n=this.operationQueue.current(e);n&&n.onError(r)}removeExecutor(e,t,i){let{media:r,mediaSource:n,operationQueue:a,sourceBuffer:o}=this,l=o[e];if(!r||!n||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(e);return}let c=K(r.duration)?r.duration:1/0,u=K(n.duration)?n.duration:1/0,d=Math.max(0,t),h=Math.min(i,c,u);h>d&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${d},${h}] from the ${e} SourceBuffer`),l.remove(d,h)):a.shiftAndExecuteNext(e)}appendExecutor(e,t){let i=this.sourceBuffer[t];if(!i){if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);return}i.ended=!1,i.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}let{operationQueue:i}=this,r=t.map(n=>i.appendBlocker(n));Promise.all(r).then(()=>{e(),t.forEach(n=>{let a=this.sourceBuffer[n];a!=null&&a.updating||i.shiftAndExecuteNext(n)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){let r=this.sourceBuffer[e];if(!r)return;let n=i.bind(this,e);this.listeners[e].push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){let t=this.sourceBuffer[e];t&&this.listeners[e].forEach(i=>{t.removeEventListener(i.event,i.listener)})}};function Gl(s){let e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function Ug(s,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}var Bg={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Fc=s=>String.fromCharCode(Bg[s]||s),Ye=15,ct=100,$g={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Gg={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Kg={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Hg={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Vg=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],va=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i=typeof t=="function"?t():t;A.log(`${this.time} [${e}] ${i}`)}}},Vt=function(e){let t=[];for(let i=0;ict&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ct)}moveCursor(e){let t=this.pos+e;if(e>1)for(let i=this.pos+1;i=144&&this.backSpace();let t=Fc(e);if(this.pos>=ct){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t"pacData = "+JSON.stringify(e));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],i="",r=-1;for(let n=0;n0&&(e?i="["+t.join(" | ")+"]":i=t.join(` `)),i}getTextAndFormat(){return this.rows}},fr=class{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new qi(i),this.nonDisplayedMemory=new qi(i),this.lastOutputScreen=new qi(i),this.currRollUpRow=this.displayedMemory.rows[Ye-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Ye-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;it+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{let i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},mr=class{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Wg(),this.logger=void 0;let r=this.logger=new va;this.channels=[null,new fr(e,t,r),new fr(e+1,i,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let i=0;i"["+Vt([t[i],t[i+1]])+"] -> ("+Vt([r,n])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(qg(r,n,l)){Ms(null,null,l),this.logger.log(3,()=>"Repeated command ("+Vt([r,n])+") is dropped");continue}Ms(r,n,this.cmdHistory),a=this.parseCmd(r,n),a||(a=this.parseMidrow(r,n)),a||(a=this.parsePAC(r,n)),a||(a=this.parseBackgroundAttributes(r,n))}else Ms(null,null,l);if(!a&&(o=this.parseChars(r,n),o)){let u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Vt([r,n])+" orig: "+Vt([t[i],t[i+1]]))}}parseCmd(e,t){let i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(i||r))return!1;let n=e===20||e===21||e===23?1:2,a=this.channels[n];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let r=this.channels[i];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Vt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(r||n))return!1;let a=e<=23?1:2;t>=64&&t<=95?i=a===1?$g[e]:Kg[e]:i=a===1?Gg[e]:Hg[e];let o=this.channels[a];return o?(o.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,r.underline=(i&1)===1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=Math.floor((i-16)/2)*4,r}parseChars(e,t){let i,r=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Fc(a)+"' in channel "+i),r=[a]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+Vt(r).join(",")),r}parseBackgroundAttributes(e,t){let i=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(i||r))return!1;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=Vg[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));let o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;ee)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},ja=function(){if(yi!=null&&yi.VTTCue)return self.VTTCue;let s=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;let c=l.toLowerCase();return~o.indexOf(c)?c:!1}function i(o){return t(s,o)}function r(o){return t(e,o)}function n(o,...l){let c=1;for(;c100)throw new Error("Position must be between 0 and 100.");I=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},d,{get:function(){return b},set:function(L){let w=r(L);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");b=w,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",n({},d,{get:function(){return R},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");R=L,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",n({},d,{get:function(){return k},set:function(L){let w=r(L);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");k=w,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),xa=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function Uc(s){function e(i,r,n,a){return(i|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}let t=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}var _a=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r=0&&i<=100)return this.set(e,i),!0}return!1}};function Bc(s,e,t,i){let r=i?s.split(i):[s];for(let n in r){if(typeof r[n]!="string")continue;let a=r[n].split(t);if(a.length!==2)continue;let o=a[0],l=a[1];e(o,l)}}var Sa=new ja(0,0,""),Ns=Sa.align==="middle"?"middle":"center";function Yg(s,e,t){let i=s;function r(){let o=Uc(s);if(o===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){let c=new _a;Bc(o,function(h,f){let m;switch(h){case"region":for(let g=t.length-1;g>=0;g--)if(t[g].id===f){c.set(h,t[g].region);break}break;case"vertical":c.alt(h,f,["rl","lr"]);break;case"line":m=f.split(","),c.integer(h,m[0]),c.percent(h,m[0])&&c.set("snapToLines",!1),c.alt(h,m[0],["auto"]),m.length===2&&c.alt("lineAlign",m[1],["start",Ns,"end"]);break;case"position":m=f.split(","),c.percent(h,m[0]),m.length===2&&c.alt("positionAlign",m[1],["start",Ns,"end","line-left","line-right","auto"]);break;case"size":c.percent(h,f);break;case"align":c.alt(h,f,["start",Ns,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let u=c.get("line","auto");u==="auto"&&Sa.line===-1&&(u=-1),l.line=u,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Ns);let d=c.get("position","auto");d==="auto"&&Sa.position===50&&(d=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=d}function a(){s=s.replace(/^\s+/,"")}if(a(),e.startTime=r(),a(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),a(),e.endTime=r(),a(),n(s,e)}function $c(s){return s.replace(//gi,` `)}var ba=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new xa,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let n=t.buffer,a=0;for(n=$c(n);a")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Yg(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=` `),t.cue.text+=n}continue;case"BADCUE":n||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){let e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=` `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},jg=/\r\n|\n\r|\n|\r/g,Sn=function(e,t,i=0){return e.slice(i,i+t.length)===t},zg=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!K(t)||!K(i)||!K(r)||!K(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*r,t+=60*60*1e3*n,t},bn=function(e){let t=5381,i=e.length;for(;i;)t=t*33^e.charCodeAt(--i);return(t>>>0).toString()};function za(s,e,t){return bn(s.toString())+bn(e.toString())+bn(t)}var Xg=function(e,t,i){let r=e[t],n=e[r.prevCC];if(!n||!n.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=!1;return}for(;(a=n)!=null&&a.new;){var a;e.ccOffset+=r.start-n.start,r.new=!1,r=n,n=e[r.prevCC]}e.presentationOffset=i};function Qg(s,e,t,i,r,n,a){let o=new ba,l=rt(new Uint8Array(s)).trim().replace(jg,` `).split(` `),c=[],u=e?kg(e.baseTime,e.timescale):0,d="00:00.000",h=0,f=0,m,g=!0;o.oncue=function(p){let v=t[i],E=t.ccOffset,T=(h-u)/9e4;if(v!=null&&v.new&&(f!==void 0?E=t.ccOffset=v.start:Xg(t,i,T)),T){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}E=T-t.presentationOffset}let x=p.endTime-p.startTime,_=Ke((p.startTime+E-f)*9e4,r*9e4)/9e4;p.startTime=Math.max(_,0),p.endTime=Math.max(_+x,0);let I=p.text.trim();p.text=decodeURIComponent(encodeURIComponent(I)),p.id||(p.id=za(p.startTime,p.endTime,I)),p.endTime>0&&c.push(p)},o.onparsingerror=function(p){m=p},o.onflush=function(){if(m){a(m);return}n(c)},l.forEach(p=>{if(g)if(Sn(p,"X-TIMESTAMP-MAP=")){g=!1,p.slice(16).split(",").forEach(v=>{Sn(v,"LOCAL:")?d=v.slice(6):Sn(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{f=zg(d)/1e3}catch(v){m=v}return}else p===""&&(g=!1);o.parse(p+` `)}),o.flush()}var An="stpp.ttml.im1t",Gc=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Kc=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Jg={left:"start",center:"center",right:"end",start:"start",end:"end"};function Kl(s,e,t,i){let r=J(new Uint8Array(s),["mdat"]);if(r.length===0){i(new Error("Could not parse IMSC1 mdat"));return}let n=r.map(o=>rt(o)),a=Dg(e.baseTime,1,e.timescale);try{n.forEach(o=>t(Zg(o,a)))}catch(o){i(o)}}function Zg(s,e){let r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((d,h)=>(d[h]=r.getAttribute(`ttp:${h}`)||n[h],d),{}),o=r.getAttribute("xml:space")!=="preserve",l=Hl(Rn(r,"styling","style")),c=Hl(Rn(r,"layout","region")),u=Rn(r,"body","[begin]");return[].map.call(u,d=>{let h=Hc(d,o);if(!h||!d.hasAttribute("begin"))return null;let f=In(d.getAttribute("begin"),a),m=In(d.getAttribute("dur"),a),g=In(d.getAttribute("end"),a);if(f===null)throw Vl(d);if(g===null){if(m===null)throw Vl(d);g=f+m}let p=new ja(f-e,g-e,h);p.id=za(p.startTime,p.endTime,p.text);let v=c[d.getAttribute("region")],E=l[d.getAttribute("style")],T=ep(v,E,l),{textAlign:x}=T;if(x){let _=Jg[x];_&&(p.lineAlign=_),p.align=x}return Te(p,T),p}).filter(d=>d!==null)}function Rn(s,e,t){let i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Hl(s){return s.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Hc(s,e){return[].slice.call(s.childNodes).reduce((t,i,r)=>{var n;return i.nodeName==="br"&&r?t+` `:(n=i.childNodes)!=null&&n.length?Hc(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function ep(s,e,t){let i="http://www.w3.org/ns/ttml#styling",r=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{let c=Ln(e,i,l)||Ln(s,i,l)||Ln(r,i,l);return c&&(o[l]=c),o},{})}function Ln(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function Vl(s){return new Error(`Could not parse ttml timestamp ${s}`)}function In(s,e){if(!s)return null;let t=Uc(s);return t===null&&(Gc.test(s)?t=tp(s,e):Kc.test(s)&&(t=ip(s,e))),t}function tp(s,e){let t=Gc.exec(s),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function ip(s,e){let t=Kc.exec(s),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}var Aa=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Wl(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){let e=new fi(this,"textTrack1"),t=new fi(this,"textTrack2"),i=new fi(this,"textTrack3"),r=new fi(this,"textTrack4");this.cea608Parser1=new mr(1,e,t),this.cea608Parser2=new mr(3,i,r)}}addCues(e,t,i,r,n){let a=!1;for(let o=n.length;o--;){let l=n[o],c=sp(l[0],l[1],t,i);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=!0,c/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,i,r)}else{let o=this.Cues.newCue(null,t,i,r);this.hls.trigger(y.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n}){let{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:r,timescale:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(y.FRAG_LOADED,o)}))}getExistingTrack(e,t){let{media:i}=this;if(i)for(let r=0;r{hi(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Wl(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let i=0;in.textCodec===An);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Nc(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let a=this.media,o=a?Bs(a.textTracks):null;if(this.tracks.forEach((l,c)=>{let u;if(o){let d=null;for(let h=0;hc!==null).map(c=>c.label);l.length&&A.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let r=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!r)return;let n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===z.MAIN){var i,r;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=t.frag,u=(i=(r=t.part)==null?void 0:r.index)!=null?i:-1;n&&a&&(c!==o+1||c===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=u}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.type===z.SUBTITLE)if(r.byteLength){let n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===An?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;Kl(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),i.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},r=>{A.log(`Failed to parse IMSC1: ${r}`),i.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})})}_parseVTTs(e){var t;let{frag:i,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}let l=this.hls,c=(t=i.initSegment)!=null&&t.data?He(i.initSegment.data,new Uint8Array(r)):r;Qg(c,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,u=>{this._appendCues(u,i.level),l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},u=>{let d=u.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(i,r),A.log(`Failed to parse VTT cue: ${u}`),!(d&&o>i.cc)&&l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:u})})}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||Kl(t,this.initPTS[e.cc],()=>{i.textCodec=An,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>fc(r,n))}else{let r=this.tracks[t];if(!r)return;let n=r.default?"default":"subtitles"+t;i.trigger(y.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===z.SUBTITLE&&this.onFragLoaded(y.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();let{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!i||!r)return;let{frag:n,samples:a}=t;if(!(n.type===z.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let o=0;oNn(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>Nn(o[l],t,r))}}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,r=2;for(let n=0;nthis.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return-1;let i=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,s.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;let r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0,n=e.length-1,a=Math.max(t,i);for(let o=0;o=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}},La=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let n=r-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,c=this.hls;if(c.trigger(y.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let u=c.currentLevel;A.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=u)&&(u=u-1,c.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:c.currentLevel}),c.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},Fs="[eme]",gr=class s{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=s.CDMCleanupPromise?[s.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=A.debug.bind(A,Fs),this.log=A.log.bind(A,Fs),this.warn=A.warn.bind(A,Fs),this.error=A.error.bind(A,Fs),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(y.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(y.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===de.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=c=>{let u=c.shift();this.getMediaKeysPromise(u,r,n).then(d=>a({keySystem:u,mediaKeys:d})).catch(d=>{c.length?l(c):d instanceof Ne?o(d):o(new Ne({type:j.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Zl===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return i(e,t)}getMediaKeysPromise(e,t,i){let r=Wf(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e],a=n==null?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),a=this.requestMediaKeySystemAccess(e,r);let o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);let c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),c.then(d=>d?this.setMediaKeysServerCertificate(u,e,d):u))),o.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),o.mediaKeys})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${tt.hexDump(e.keyId||[])}`);let r=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,n,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return tt.hexDump(e.keyId)}updateKeySession(e,t){var i;let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${tt.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])} } (data length: ${t&&t.byteLength})`),r.update(t)}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{let r=dn(this.config),n=e.map(nl).filter(a=>!!a&&r.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{let o=ol(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(e){let t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();let l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t});return this.generateRequestWithPreferredKeySession(l,"cenc",t.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Ne?this.hls.trigger(y.ERROR,e.data):this.hls.trigger(y.ERROR,{type:j.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){let t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){let r=nl(e.keyFormat),n=r?[r]:dn(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=dn(this.config)),e.length===0)throw new Ne({type:j.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){let{initDataType:t,initData:i}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.debug(r),i===null)return;let n,a;if(t==="sinf"&&this.config.drmSystems[de.FAIRPLAY]){let d=be(new Uint8Array(i));try{let h=$a(JSON.parse(d).sinf),f=oc(new Uint8Array(h));if(!f)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");n=f.subarray(8,24),a=de.FAIRPLAY}catch(h){this.warn(`${r} Failed to parse sinf: ${h}`);return}}else{let d=ym(i),h=d.filter(f=>f.systemId===Ki.WIDEVINE)[0];if(!h){d.length===0||d.some(f=>!f.systemId)?this.warn(`${r} contains incomplete or invalid pssh data`):this.log(`ignoring ${r} for ${d.map(f=>al(f.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(a=al(h.systemId),h.version===0&&h.data){let f=h.data.length-22;n=h.data.subarray(f,f+16)}}if(!a||!n)return;let o=tt.hexDump(n),{keyIdToKeySessionPromise:l,mediaKeySessions:c}=this,u=l[o];for(let d=0;dthis.generateRequestWithPreferredKeySession(h,t,i,"encrypted-event-key-match"));break}}u||(u=l[o]=this.getKeySystemSelectionPromise([a]).then(({keySystem:d,mediaKeys:h})=>{var f;this.throwIfDestroyed();let m=new Yi("ISO-23001-7",o,(f=ol(d))!=null?f:"");return m.pssh=new Uint8Array(i),m.keyId=n,this.attemptSetMediaKeys(d,h).then(()=>{this.throwIfDestroyed();let g=this.createMediaKeySessionContext({decryptdata:m,keySystem:d,mediaKeys:h});return this.generateRequestWithPreferredKeySession(g,t,i,"encrypted-event-no-match")})})),u.catch(d=>this.handleError(d))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,r){var n,a;let o=(n=this.config.drmSystems)==null||(a=n[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let m=o.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=e.decryptdata.pssh=m.initData?new Uint8Array(m.initData):null}catch(m){var l;if(this.warn(m.message),(l=this.hls)!=null&&l.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${c} (init data type: ${t} length: ${i?i.byteLength:null})`);let u=new Ya,d=e._onmessage=m=>{let g=e.mediaKeysSession;if(!g){u.emit("error",new Error("invalid state"));return}let{messageType:p,message:v}=m;this.log(`"${p}" message event for session "${g.sessionId}" message size: ${v.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,v).catch(E=>{this.handleError(E),u.emit("error",E)}):p==="license-release"?e.keySystem===de.FAIRPLAY&&(this.updateKeySession(e,Pn("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${p}"`)},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);let p=e.keyStatus;u.emit("keyStatus",p),p==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",d),e.mediaKeysSession.addEventListener("keystatuseschange",h);let f=new Promise((m,g)=>{u.on("error",g),u.on("keyStatus",p=>{p.startsWith("usable")?m():p==="output-restricted"?g(new Ne({type:j.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?g(new Ne({type:j.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${p}"`)):p==="expired"?g(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var m;this.log(`Request generated for key-session "${(m=e.mediaKeysSession)==null?void 0:m.sessionId}" keyId: ${c}`)}).catch(m=>{throw new Ne({type:j.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_SESSION,error:m,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>{throw u.removeAllListeners(),this.removeSession(e),m}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${tt.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${tt.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){let t=this.config,i=t.loader,r=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={responseType:"arraybuffer",url:n},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,m,g)=>{a(h.data)},onError:(h,f,m,g)=>{o(new Ne({type:j.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:we({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,m)=>{o(new Ne({type:j.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(h,f,m)=>{o(new Error("aborted"))}};r.load(l,u,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new Ne({type:j.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new Ne({type:j.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:r,fatal:!0},r.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let d=0,h=n.length;d in key message");return Pn(atob(c))}setupLicenseXHR(e,t,i,r){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,i,r)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{let a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);let c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(u){this.error(u)}r(l)}else{let l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)n(new Ne({type:j.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let u=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==de.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){let e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Yi.clearKeyUriToKeyIdMap();let i=t.length;s.CDMCleanupPromise=Promise.all(t.map(r=>this.removeSession(r)).concat(e==null?void 0:e.setMediaKeys(null).catch(r=>{this.log(`Could not clear media keys: ${r}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(r=>{this.log(`Could not close sessions and clear media keys: ${r}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}};gr.CDMCleanupPromise=void 0;var Ne=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}},Pe;(function(s){s.MANIFEST="m",s.AUDIO="a",s.VIDEO="v",s.MUXED="av",s.INIT="i",s.CAPTION="c",s.TIMED_TEXT="tt",s.KEY="k",s.OTHER="o"})(Pe||(Pe={}));var Ia;(function(s){s.DASH="d",s.HLS="h",s.SMOOTH="s",s.OTHER="o"})(Ia||(Ia={}));var Yt;(function(s){s.OBJECT="CMCD-Object",s.REQUEST="CMCD-Request",s.SESSION="CMCD-Session",s.STATUS="CMCD-Status"})(Yt||(Yt={}));var rp={[Yt.OBJECT]:["br","d","ot","tb"],[Yt.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Yt.SESSION]:["cid","pr","sf","sid","st","v"],[Yt.STATUS]:["bs","rtp"]},es=class s{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof s?i:new s(i))),this.value=e,this.params=t}},pr=class{constructor(e){this.description=void 0,this.description=e}},np="Dict";function ap(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function op(s,e,t,i){return new Error(`failed to ${s} "${ap(e)}" as ${t}`,{cause:i})}var Yl="Bare Item",lp="Boolean",cp="Byte Sequence",up="Decimal",dp="Integer";function hp(s){return s<-999999999999999||99999999999999912)throw nt(s,up);let t=e.toString();return t.includes(".")?t:`${t}.0`}var xp="String";function _p(s){if(fp.test(s))throw nt(s,xp);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Sp(s){return s.description||s.toString().slice(7,-1)}function jl(s){let e=Sp(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw nt(e,mp);return e}function Da(s){switch(typeof s){case"number":if(!K(s))throw nt(s,Yl);return Number.isInteger(s)?qc(s):Tp(s);case"string":return _p(s);case"symbol":return jl(s);case"boolean":return pp(s);case"object":if(s instanceof Date)return Ep(s);if(s instanceof Uint8Array)return vp(s);if(s instanceof pr)return jl(s);default:throw nt(s,Yl)}}function ka(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw nt(s,gp);return s}function Xa(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${ka(e)}`:`;${ka(e)}=${Da(t)}`).join("")}function Yc(s){return s instanceof es?`${Da(s.value)}${Xa(s.params)}`:Da(s)}function bp(s){return`(${s.value.map(Yc).join(" ")})${Xa(s.params)}`}function Ap(s,e={whitespace:!0}){if(typeof s!="object")throw nt(s,np);let t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof es||(n=new es(n));let a=ka(r);return n.value===!0?a+=Xa(n.params):(a+="=",Array.isArray(n.value)?a+=bp(n):a+=Yc(n)),a}).join(`,${i}`)}function Rp(s,e){return Ap(s,e)}var Lp=s=>s==="ot"||s==="sf"||s==="st",Ip=s=>typeof s=="number"?K(s):s!=null&&s!==""&&s!==!1;function Dp(s,e){let t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;let r=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}function kp(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}var Vs=s=>Math.round(s),wp=(s,e)=>(e!=null&&e.baseUrl&&(s=Dp(s,e.baseUrl)),encodeURIComponent(s)),Us=s=>Vs(s/100)*100,Cp={br:Vs,d:Vs,bl:Us,dl:Us,mtp:Us,nor:wp,rtp:Us,tb:Vs};function Pp(s,e){let t={};if(s==null||typeof s!="object")return t;let i=Object.keys(s).sort(),r=Te({},Cp,e==null?void 0:e.formatters),n=e==null?void 0:e.filter;return i.forEach(a=>{if(n!=null&&n(a))return;let o=s[a],l=r[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||Ip(o)&&(Lp(a)&&typeof o=="string"&&(o=new pr(o)),t[a]=o))}),t}function jc(s,e={}){return s?Rp(Pp(s,e),Te({whitespace:!1},e)):""}function Op(s,e={}){if(!s)return{};let t=Object.entries(s),i=Object.entries(rp).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),r=t.reduce((n,a)=>{var o,l;let[c,u]=a,d=((o=i.find(h=>h[1].includes(c)))==null?void 0:o[0])||Yt.REQUEST;return(l=n[d])!=null||(n[d]={}),n[d][c]=u,n},{});return Object.entries(r).reduce((n,[a,o])=>(n[a]=jc(o,e),n),{})}function Mp(s,e,t){return Te(s,Op(e,t))}var Np="CMCD";function Fp(s,e={}){if(!s)return"";let t=jc(s,e);return`${Np}=${encodeURIComponent(t)}`}var zl=/CMCD=[^&#]+/;function Up(s,e,t){let i=Fp(e,t);if(!i)return s;if(zl.test(s))return s.replace(zl,i);let r=s.includes("?")?"&":"?";return`${s}${r}${i}`}var wa=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=r=>{try{this.apply(r,{ot:Pe.MANIFEST,su:!this.initialized})}catch(n){A.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=r=>{try{let n=r.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===Pe.VIDEO||o===Pe.AUDIO||o==Pe.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(r,l)}catch(n){A.warn("Could not generate segment CMCD data.",n)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||kp(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:1,sf:Ia.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Te(t,this.createData());let i=t.ot===Pe.INIT||t.ot===Pe.VIDEO||t.ot===Pe.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((n,a)=>(r.includes(a)&&(n[a]=t[a]),n),{})),this.useHeaders?(e.headers||(e.headers={}),Mp(e.headers,t)):e.url=Up(e.url,t)}getObjectType(e){let{type:t}=e;if(t==="subtitle")return Pe.TIMED_TEXT;if(e.sn==="initSegment")return Pe.INIT;if(t==="audio")return Pe.AUDIO;if(t==="main")return this.hls.audioTracks.length?Pe.VIDEO:Pe.MUXED}getTopBandwidth(e){let t=0,i,r=this.hls;if(e===Pe.AUDIO)i=r.audioTracks;else{let n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;i=r.levels.slice(0,a)}for(let n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){let t=this.hls.media,i=e===Pe.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:he.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}},Bp=3e5,Ca=class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=A.log.bind(A,"[content-steering]:"),this.registerListeners()}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if((i==null?void 0:i.action)===De.SendAlternateToPenaltyBox&&i.flags===We.MoveAllAlternatesMatchingHost){let r=this.levels,n=this.pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:c}=t.context;o&&r?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=r.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),i.resolved||A.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${JSON.stringify(n)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t,i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>Bp&&delete i[n]});for(let n=0;n0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,yc(t),this.hls.trigger(y.LEVELS_UPDATED,{levels:t});let c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;let c=this.getLevelsForPathway(o).map(u=>{let d=new pe(u.attrs);d["PATHWAY-ID"]=a;let h=d.AUDIO&&`${d.AUDIO}_clone_${a}`,f=d.SUBTITLES&&`${d.SUBTITLES}_clone_${a}`;h&&(i[d.AUDIO]=h,d.AUDIO=h),f&&(r[d.SUBTITLES]=f,d.SUBTITLES=f);let m=zc(u.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Et({attrs:d,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:m,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let p=1;p{this.log(`Loaded steering manifest: "${r}"`);let m=u.data;if(m.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;let{"RELOAD-URI":g,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":v}=m;if(g)try{this.uri=new self.URL(g,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||h.url),p&&this.clonePathways(p);let E={steeringManifest:m,url:r.toString()};this.hls.trigger(y.STEERING_MANIFEST_LOADED,E),v&&this.updatePathwayPriority(v)},onError:(u,d,h,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${d.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let m=this.timeToLoad*1e3;if(u.code===429){let g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){let p=g.getResponseHeader("Retry-After");p&&(m=parseFloat(p)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,m)},onTimeout:(u,d,h)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let r=(i=this.hls)==null?void 0:i.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Xl(s,e,t,i){s&&Object.keys(e).forEach(r=>{let n=s.filter(a=>a.groupId===r).map(a=>{let o=Te({},a);return o.details=void 0,o.attrs=new pe(o.attrs),o.url=o.attrs.URI=zc(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=i,o});s.push(...n)})}function zc(s,e,t,i){let{HOST:r,PARAMS:n,[t]:a}=i,o;e&&(o=a==null?void 0:a[e],o&&(s=o));let l=new self.URL(s);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(c=>{c&&l.searchParams.set(c,n[c])}),l.href}var $p=/^age:\s*[\d.]+\s*$/im,yr=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new pi,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&K(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);let l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=c,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;let u=this.callbacks.onProgress;if(u&&u(i,e,l,t),!this.callbacks)return;let d={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(d,i,e,t)}else{let l=n.loadPolicy.errorRetry,c=i.retry,u={url:e.url,data:void 0,code:a};tr(l,c,!1,u)?this.retry(l):(A.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i))}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(tr(e,t,!0))this.retry(e);else{var i;A.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Ha(e,i.retry),i.retry++,A.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&$p.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}};function Gp(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var Kp=/(\d+)-(\d+)\/(\d+)/,vr=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Wp,this.controller=new self.AbortController,this.stats=new pi}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let n=Hp(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=c&&K(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},t.timeout),self.fetch(this.request).then(d=>{this.response=this.loader=d;let h=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},u-(h-r.loading.start)),!d.ok){let{status:f,statusText:m}=d;throw new Pa(m||"fetch, bad network response",f,d)}return r.loading.first=h,r.total=qp(d.headers)||r.total,a&&K(t.highWaterMark)?this.loadProgressively(d,r,e,t.highWaterMark,a):o?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{let h=this.response;if(!h)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let f=d[l];f&&(r.loaded=r.total=f);let m={url:h.url,data:d,code:h.status};a&&!K(t.highWaterMark)&&a(r,e,d,h),i.onSuccess(m,r,e,h)}).catch(d=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;let h=d&&d.code||0,f=d?d.message:null;i.onError({code:h,text:f},e,d?d.details:null,r)})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,n){let a=new rr,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&n(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));let u=c.value,d=u.length;return t.loaded+=d,d=r&&n(t,i,a.flush(),e)):n(t,i,u,e),l()}).catch(()=>Promise.reject());return l()}};function Hp(s,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Te({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function Vp(s){let e=Kp.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function qp(s){let e=s.get("Content-Range");if(e){let i=Vp(e);if(K(i))return i}let t=s.get("Content-Length");if(t)return parseInt(t)}function Wp(s,e){return new self.Request(s.url,e)}var Pa=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},Yp=/\s/,jp={newCue(s,e,t,i){let r=[],n,a,o,l,c,u=self.VTTCue||self.TextTrackCue;for(let h=0;h=16?l--:l++;let f=$c(c.trim()),m=za(e,t,f);s!=null&&(d=s.cues)!=null&&d.getCueById(m)||(a=new u(e,t,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return s&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>fc(s,h))),r}},zp={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Xc=we(we({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:yr,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:qn,bufferController:ya,capLevelController:Ra,errorController:Hn,fpsController:La,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Zl,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:zp},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Xp()),{},{subtitleStreamController:fa,subtitleTrackController:ga,timelineController:Aa,audioStreamController:da,audioTrackController:ha,emeController:gr,cmcdController:wa,contentSteeringController:Ca});function Xp(){return{cueHandler:jp,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Qp(s,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let t=Oa(s),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{let a=`${n==="level"?"playlist":n}LoadPolicy`,o=e[a]===void 0,l=[];r.forEach(c=>{let u=`${n}Loading${c}`,d=e[u];if(d!==void 0&&o){l.push(u);let h=t[a].default;switch(e[a]={default:h},c){case"TimeOut":h.maxLoadTimeMs=d,h.maxTimeToFirstByteMs=d;break;case"MaxRetry":h.errorRetry.maxNumRetry=d,h.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":h.errorRetry.retryDelayMs=d,h.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=d,h.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&A.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),we(we({},t),e)}function Oa(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Oa):Object.keys(s).reduce((e,t)=>(e[t]=Oa(s[t]),e),{}):s}function Jp(s){let e=s.loader;e!==vr&&e!==yr?(A.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):Gp()&&(s.loader=vr,s.progressive=!0,s.enableSoftwareAES=!0,A.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Dn,Ma=class extends zi{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],n={},a={},o=!1,l=!1,c=!1;t.levels.forEach(u=>{var d,h;let f=u.attrs,{audioCodec:m,videoCodec:g}=u;((d=m)==null?void 0:d.indexOf("mp4a.40.34"))!==-1&&(Dn||(Dn=/chrome|firefox/i.test(navigator.userAgent)),Dn&&(u.audioCodec=m=void 0)),m&&(u.audioCodec=m=Qs(m,i)),((h=g)==null?void 0:h.indexOf("avc1"))===0&&(g=u.videoCodec=Am(g));let{width:p,height:v,unknownCodecs:E}=u;if(o||(o=!!(p&&v)),l||(l=!!g),c||(c=!!m),E!=null&&E.length||m&&!gn(m,"audio",i)||g&&!gn(g,"video",i))return;let{CODECS:T,"FRAME-RATE":x,"HDCP-LEVEL":_,"PATHWAY-ID":I,RESOLUTION:b,"VIDEO-RANGE":R}=f,L=`${`${I||"."}-`}${u.bitrate}-${b}-${x}-${T}-${R}-${_}`;if(n[L])if(n[L].uri!==u.url&&!u.attrs["PATHWAY-ID"]){let w=a[L]+=1;u.attrs["PATHWAY-ID"]=new Array(w+1).join(".");let P=new Et(u);n[L]=P,r.push(P)}else n[L].addGroupId("audio",f.AUDIO),n[L].addGroupId("text",f.SUBTITLES);else{let w=new Et(u);n[L]=w,a[L]=1,r.push(w)}}),this.filterAndSortMediaOptions(r,t,o,l,c)}filterAndSortMediaOptions(e,t,i,r,n){let a=[],o=[],l=e;if((i||r)&&n&&(l=l.filter(({videoCodec:m,videoRange:g,width:p,height:v})=>(!!m||!!(p&&v))&&Mm(g))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);let m=new Error("no level with compatible codecs found in manifest");this.hls.trigger(y.ERROR,{type:j.MEDIA_ERROR,details:D.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:m,reason:m.message})}});return}if(t.audioTracks){let{preferManagedMediaSource:m}=this.hls.config;a=t.audioTracks.filter(g=>!g.audioCodec||gn(g.audioCodec,"audio",m)),Ql(a)}t.subtitles&&(o=t.subtitles,Ql(o));let c=l.slice(0);l.sort((m,g)=>{if(m.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"])return(m.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&m.height!==g.height)return m.height-g.height;if(m.frameRate!==g.frameRate)return m.frameRate-g.frameRate;if(m.videoRange!==g.videoRange)return Js.indexOf(m.videoRange)-Js.indexOf(g.videoRange);if(m.videoCodec!==g.videoCodec){let p=hl(m.videoCodec),v=hl(g.videoCodec);if(p!==v)return v-p}if(m.uri===g.uri&&m.codecSet!==g.codecSet){let p=Xs(m.codecSet),v=Xs(g.codecSet);if(p!==v)return v-p}return m.averageBitrate!==g.averageBitrate?m.averageBitrate-g.averageBitrate:0});let u=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let m=0;mp&&p===Xc.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}let h=n&&!r,f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:!h&&a.some(m=>!!m.url)};this.hls.trigger(y.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let u=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(y.ERROR,{type:j.OTHER_ERROR,details:D.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:u,reason:u.message}),d)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&a.details&&r&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(y.LEVEL_SWITCHING,l);let c=a.details;if(!c||c.live){let u=this.switchParams(a.uri,r==null?void 0:r.details,c);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===ie.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===z.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var i;let{level:r,details:n}=t,a=this._levels[r];if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}r===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(r,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();let t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}let n=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${n?" Pathway "+n:""} ${r}`),this.clearTimer(),this.hls.trigger(y.LEVEL_LOADING,{url:r,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;let i=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(a=>a.level=-1)),!1));yc(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(y.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}};function Ql(s){let e={};s.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}var Na=class{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyUriToKeyInfo){let r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=D.KEY_LOAD_ERROR,i,r,n){return new je({type:j.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){let{sn:i,cc:r}=e;for(let n=0;n{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,c))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((r=o)!=null&&r.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(n.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,D.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){let r=this.emeController.loadKey(i);if(r)return(e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,r=i.loader,n=new r(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=i.keyLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,m,g)=>{let{frag:p,keyInfo:v,url:E}=m;if(!p.decryptdata||v!==this.keyUriToKeyInfo[E])return o(this.createKeyLoadError(p,D.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));v.decryptdata.key=p.decryptdata.key=new Uint8Array(h.data),p.keyLoader=null,v.loader=null,a({frag:p,keyInfo:v})},onError:(h,f,m,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,D.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,we({url:l.url,data:void 0},h)))},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,D.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,D.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,u,d)})}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],n&&n.destroy()}};function Qc(){return self.SourceBuffer||self.WebKitSourceBuffer}function Jc(){if(!zt())return!1;let e=Qc();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Zp(){if(!Jc())return!1;let s=zt();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(ji(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(ji(e,"audio"))))}function e0(){var s;let e=Qc();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}var t0=250,qs=2,i0=.1,s0=.05,Fa=class{constructor(e,t,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){let{config:i,media:r,stalled:n}=this;if(r===null)return;let{currentTime:a,seeking:o}=r,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),n!==null){if(this.stallReported){let p=self.performance.now()-n;A.warn(`playback not stuck anymore @${a}, after ${Math.round(p)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(r.paused&&!o||r.ended||r.playbackRate===0||!he.getBuffered(r).length){this.nudgeRetry=0;return}let u=he.bufferInfo(r,a,0),d=u.nextStart||0;if(o){let p=u.len>qs,v=!d||t&&t.start<=a||d-a>qs&&!this.fragmentTracker.getPartialFragment(a);if(p||v)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var h;if(!(u.len>0)&&!d)return;let v=Math.max(d,u.start||0)-a,E=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,x=(E==null||(h=E.details)==null?void 0:h.live)?E.details.targetduration*2:qs,_=this.fragmentTracker.getPartialFragment(a);if(v>0&&(v<=x||_)){r.paused||this._trySkipBufferHole(_);return}}let f=self.performance.now();if(n===null){this.stalled=f;return}let m=f-n;if(!o&&m>=t0&&(this._reportStall(u),!this.media))return;let g=he.bufferInfo(r,a,i.maxBufferHole);this._tryFixBufferStall(g,m)}_tryFixBufferStall(e,t){let{config:i,fragmentTracker:r,media:n}=this;if(n===null)return;let a=n.currentTime,o=r.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-ai.highBufferWatchdogPeriod*1e3&&(A.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){let{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;let n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);A.warn(n.message),t.trigger(y.ERROR,{type:j.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){let{config:t,hls:i,media:r}=this;if(r===null)return 0;let n=r.currentTime,a=he.bufferInfo(r,n,0),o=n0&&a.len<1&&r.readyState<3,u=o-n;if(u>0&&(l||c)){if(u>t.maxBufferHole){let{fragmentTracker:h}=this,f=!1;if(n===0){let m=h.getAppendedFrag(0,z.MAIN);m&&o1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=C.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=C.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case C.WAITING_LEVEL:{let{levels:t,level:i}=this,r=t==null?void 0:t[i],n=r==null?void 0:r.details;if(n&&(!n.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(n))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:{var e;let t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){let{levels:r,level:n}=this,a=r==null?void 0:r[n];this.resetStartWhenNotLoaded(a||null),this.state=C.IDLE}}break}this.state===C.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=e.nextLoadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let g={};this.altAudio&&(g.type="video"),this.hls.trigger(y.BUFFER_EOS,g),this.state=C.ENDED;return}e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let c=a.details;if(!c||this.state===C.WAITING_LEVEL||c.live&&this.levelLastLoaded!==a){this.level=n,this.state=C.WAITING_LEVEL;return}let u=o.len,d=this.getMaxBufferLength(a.maxBitrate);if(u>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let h=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(h,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==ke.OK){var m;let p=((m=this.backtrackFragment)!=null?m:f).sn-c.startSN,v=c.fragments[p-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let p=this.audioOnly&&!this.altAudio?le.AUDIO:le.VIDEO,v=(p===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,p,z.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,z.MAIN,d)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===ke.NOT_LOADED||r===ke.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,z.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len{let a=n.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&r&&!e0(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==C.IDLE)return;let r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=C.WAITING_LEVEL)}onLevelLoaded(e,t){var i;let{levels:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!r){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);let l=r[n],c=this.fragCurrent;c&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let u=0;if(a.live||(i=l.details)!=null&&i.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(y.LEVEL_UPDATED,{details:a,level:n}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=C.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,u),this.tick()}_handleFragmentLoadProgress(e){var t;let{frag:i,part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let c=o.videoCodec,u=l.PTSKnown||!l.live,d=(t=i.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new dr(this.hls,z.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,g=m!==-1,p=new Xi(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,g),v=this.initPTS[i.cc];f.push(n,d,h,c,i,r,l.totalduration,u,p,v)}onAudioTrackSwitching(e,t){let i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();let n=this.hls;i&&(n.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(y.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=t.id,r=!!this.hls.audioTracks[i].url;if(r){let n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r,this.tick()}onBufferCreated(e,t){let i=t.tracks,r,n,a=!1;for(let o in i){let l=i[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let c=i[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i&&i.type!==z.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===C.PARSED&&(this.state=C.IDLE);return}let n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(z.MAIN,t);break;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ie.LEVEL&&(this.state=C.IDLE);break;case D.BUFFER_APPEND_ERROR:case D.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===D.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){let{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!he.getBuffered(e).length){let i=this.state!==C.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==le.AUDIO||this.audioOnly&&!this.altAudio){let i=(t===le.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,z.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t0&&(a{let{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(y.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;let i="main",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:c,level:u}=o,{video:d,text:h,id3:f,initSegment:m}=n,{details:g}=u,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=C.PARSING,m){if(m!=null&&m.tracks){let T=l.initSegment||l;this._bufferInitSegment(u,m.tracks,T,a),r.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:i,tracks:m.tracks})}let v=m.initPTS,E=m.timescale;K(v)&&(this.initPTS[l.cc]={baseTime:v,timescale:E},r.trigger(y.INIT_PTS_FOUND,{frag:l,id:i,initPTS:v,timescale:E}))}if(d&&g&&l.sn!=="initSegment"){let v=g.fragments[l.sn-1-g.startSN],E=l.sn===g.startSN,T=!v||l.cc>v.cc;if(n.independent!==!1){let{startPTS:x,endPTS:_,startDTS:I,endDTS:b}=d;if(c)c.elementaryStreams[d.type]={startPTS:x,endPTS:_,startDTS:I,endDTS:b};else if(d.firstKeyFrame&&d.independent&&a.id===1&&!T&&(this.couldBacktrack=!0),d.dropped&&d.independent){let R=this.getMainFwdBufferInfo(),k=(R?R.end:this.getLoadPosition())+this.config.maxBufferHole,L=d.firstKeyFramePTS?d.firstKeyFramePTS:x;if(!E&&kqs&&(l.gap=!0);l.setElementaryStreamInfo(d.type,x,_,I,b),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(d,l,c,a,E||T)}else if(E||T)l.gap=!0;else{this.backtrack(l);return}}if(p){let{startPTS:v,endPTS:E,startDTS:T,endDTS:x}=p;c&&(c.elementaryStreams[le.AUDIO]={startPTS:v,endPTS:E,startDTS:T,endDTS:x}),l.setElementaryStreamInfo(le.AUDIO,v,E,T,x),this.bufferFragmentData(p,l,c,a)}if(g&&f!=null&&(t=f.samples)!=null&&t.length){let v={id:i,frag:l,details:g,samples:f.samples};r.trigger(y.FRAG_PARSING_METADATA,v)}if(g&&h){let v={id:i,frag:l,details:g,samples:h.samples};r.trigger(y.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(e,t,i,r){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;let{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec,c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");let u=n.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(y.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{let u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:l,data:u,frag:i,part:null,chunkMeta:r,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,z.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=C.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let i=e.currentTime;if(he.isBuffered(e,i)?t=this.getAppendedFrag(i):he.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(y.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(y.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){let e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){let e=this.media;if(e){let t=e.currentTime,i=this.currentFrag;if(i&&K(t)&&K(i.programDateTime)){let r=i.programDateTime+(t-i.start)*1e3;return new Date(r)}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},ts=class s{static get version(){return"1.5.15"}static isMSESupported(){return Jc()}static isSupported(){return Zp()}static getMediaSource(){return zt()}static get Events(){return y}static get ErrorTypes(){return j}static get ErrorDetails(){return D}static get DefaultConfig(){return s.defaultConfig?s.defaultConfig:Xc}static set DefaultConfig(e){s.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Ya,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,Uf(e.debug||!1,"Hls instance");let t=this.config=Qp(s.DefaultConfig,e);this.userConfig=e,t.progressive&&Jp(t);let{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=t,l=new a(this),c=this.abrController=new i(this),u=this.bufferController=new r(this),d=this.capLevelController=new n(this),h=new o(this),f=new Mn(this),m=new Un(this),g=t.contentSteeringController,p=g?new g(this):null,v=this.levelController=new Ma(this,p),E=new Yn(this),T=new Na(this.config),x=this.streamController=new Ua(this,E,T);d.setStreamController(x),h.setStreamController(x);let _=[f,v,x];p&&_.splice(1,0,p),this.networkControllers=_;let I=[c,u,d,h,m,E];this.audioTrackController=this.createController(t.audioTrackController,_);let b=t.audioStreamController;b&&_.push(new b(this,E,T)),this.subtitleTrackController=this.createController(t.subtitleTrackController,_);let R=t.subtitleStreamController;R&&_.push(new R(this,E,T)),this.createController(t.timelineController,I),T.emeController=this.emeController=this.createController(t.emeController,I),this.cmcdController=this.createController(t.cmcdController,I),this.latencyController=this.createController(Bn,I),this.coreComponents=I,_.push(l);let k=l.onErrorOut;typeof k=="function"&&this.on(y.ERROR,k,l)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(A.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;let r=e===y.ERROR;this.trigger(y.ERROR,{type:j.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){A.log("destroy"),this.trigger(y.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){A.log("attachMedia"),this._media=e,this.trigger(y.MEDIA_ATTACHING,{media:e})}detachMedia(){A.log("detachMedia"),this.trigger(y.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();let t=this.media,i=this.url,r=this.url=Ba.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,A.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(y.MANIFEST_LOADING,{url:e})}startLoad(e=-1){A.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){A.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){A.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){A.log("recoverMediaError");let e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){let e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){A.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){A.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){A.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){A.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){A.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(A.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Om(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}};ts.defaultConfig=void 0;var me=ts,fe={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},ue={NOT_AN_ERROR:0,NETWORK_OFFLINE:2000002,NETWORK_UNKNOWN_ERROR:2e6,NETWORK_NO_STATUS:2000001,NETWORK_INVALID_URL:24e5,NETWORK_NOT_FOUND:2404e3,NETWORK_NOT_READY:2412e3,NETWORK_GENERIC_SERVER_FAIL:25e5,NETWORK_TOKEN_MISSING:2403201,NETWORK_TOKEN_MALFORMED:2412202,NETWORK_TOKEN_EXPIRED:2403210,NETWORK_TOKEN_AUD_MISSING:2403221,NETWORK_TOKEN_AUD_MISMATCH:2403222,NETWORK_TOKEN_SUB_MISMATCH:2403232,ENCRYPTED_ERROR:5e6,ENCRYPTED_UNSUPPORTED_KEY_SYSTEM:5000001,ENCRYPTED_GENERATE_REQUEST_FAILED:5000002,ENCRYPTED_UPDATE_LICENSE_FAILED:5000003,ENCRYPTED_UPDATE_SERVER_CERT_FAILED:5000004,ENCRYPTED_CDM_ERROR:5000005,ENCRYPTED_OUTPUT_RESTRICTED:5000006,ENCRYPTED_MISSING_TOKEN:5000002},lu=s=>s===fe.VIDEO?"playback":s,Tt=class is extends Error{constructor(e,t=is.MEDIA_ERR_CUSTOM,i,r){var n;super(e),this.name="MediaError",this.code=t,this.context=r,this.fatal=i!=null?i:t>=is.MEDIA_ERR_NETWORK&&t<=is.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=is.defaultMessages[this.code])!=null?n:"")}};Tt.MEDIA_ERR_ABORTED=1,Tt.MEDIA_ERR_NETWORK=2,Tt.MEDIA_ERR_DECODE=3,Tt.MEDIA_ERR_SRC_NOT_SUPPORTED=4,Tt.MEDIA_ERR_ENCRYPTED=5,Tt.MEDIA_ERR_CUSTOM=100,Tt.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail.",3:"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.",4:"An unsupported error occurred. The server or network failed, or your browser does not support this format.",5:"The media is encrypted and there are no keys to decrypt it."};var V=Tt,n0=s=>s==null,no=(s,e)=>n0(e)?!1:s in e,Za={ANY:"any",MUTED:"muted"},Ue={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},Xt={MSE:"mse",NATIVE:"native"},Tr={HEADER:"header",QUERY:"query",NONE:"none"},ao=Object.values(Tr),_t={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},eo={HLS:_t.M3U8},py=Object.keys(eo),yy=[...Object.values(_t),"hls","HLS"];var a0="en",to={code:a0},xe=(s,e,t,i,r=s)=>{r.addEventListener(e,t,i),s.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function o0(s,e,t){e&&t>e&&(t=e);for(let i=0;i=t)return!0;return!1}var Ar=s=>{let e=s.indexOf("?");if(e<0)return[s];let t=s.slice(0,e),i=s.slice(e);return[t,i]},Rr=s=>{let e=s.type;if(e){let i=e.toUpperCase();return no(i,eo)?eo[i]:e}let{src:t}=s;return t?l0(t):""},cu=s=>s==="VOD"?Ue.ON_DEMAND:Ue.LIVE,uu=s=>s==="EVENT"?Number.POSITIVE_INFINITY:s==="VOD"?Number.NaN:0,l0=s=>{let e="";try{e=new URL(s).pathname}catch{console.error("invalid url")}let t=e.lastIndexOf(".");if(t<0)return"";let i=e.slice(t+1).toUpperCase();return no(i,_t)?_t[i]:""},c0=s=>{let e=(s!=null?s:"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=decodeURIComponent(atob(t).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(i)}catch{return}},u0=({exp:s},e=Date.now())=>!s||s*1e3s!==e,h0=({aud:s},e)=>!s,f0=({aud:s},e)=>s!==e,du="en";function se(s,e=!0){var t,i;let r=e&&(i=(t=to)==null?void 0:t[s])!=null?i:s,n=e?to.code:du;return new m0(r,n)}var m0=class{constructor(s,e=(t=>(t=to)!=null?t:du)()){this.message=s,this.locale=e}format(s){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var i;return(i=s[t])!=null?i:""})}toString(){return this.message}},g0=Object.values(Za),Zc=s=>typeof s=="boolean"||typeof s=="string"&&g0.includes(s),p0=(s,e,t)=>{let{autoplay:i}=s,r=!1,n=!1,a=Zc(i)?i:!!i,o=()=>{r||xe(e,"playing",()=>{r=!0},{once:!0})};if(o(),xe(e,"loadstart",()=>{r=!1,o(),Qa(e,a)},{once:!0}),xe(e,"loadstart",()=>{t||(s.streamType&&s.streamType!==Ue.UNKNOWN?n=s.streamType===Ue.LIVE:n=!Number.isFinite(e.duration)),Qa(e,a)},{once:!0}),t&&t.once(me.Events.LEVEL_LOADED,(l,c)=>{var u;s.streamType&&s.streamType!==Ue.UNKNOWN?n=s.streamType===Ue.LIVE:n=(u=c.details.live)!=null?u:!1}),!a){let l=()=>{!n||Number.isFinite(s.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&xe(e,"play",()=>{e.preload==="metadata"?t.once(me.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{r||(a=Zc(l)?l:!!l,Qa(e,a))}},Qa=(s,e)=>{if(!e)return;let t=s.muted,i=()=>s.muted=t;switch(e){case Za.ANY:s.play().catch(()=>{s.muted=!0,s.play().catch(i)});break;case Za.MUTED:s.muted=!0,s.play().catch(i);break;default:s.play().catch(()=>{});break}},y0=({preload:s,src:e},t,i)=>{let r=d=>{d!=null&&["","none","metadata","auto"].includes(d)?t.setAttribute("preload",d):t.removeAttribute("preload")};if(!i)return r(s),r;let n=!1,a=!1,o=i.config.maxBufferLength,l=i.config.maxBufferSize,c=d=>{r(d);let h=d!=null?d:t.preload;a||h==="none"||(h==="metadata"?(i.config.maxBufferLength=1,i.config.maxBufferSize=1):(i.config.maxBufferLength=o,i.config.maxBufferSize=l),u())},u=()=>{!n&&e&&(n=!0,i.loadSource(e))};return xe(t,"play",()=>{a=!0,i.config.maxBufferLength=o,i.config.maxBufferSize=l,u()},{once:!0}),c(s),c};function v0(s,e){var t;if(!("videoTracks"in s))return;let i=new WeakMap;e.on(me.Events.MANIFEST_PARSED,function(c,u){l();let d=s.addVideoTrack("main");d.selected=!0;for(let[h,f]of u.levels.entries()){let m=d.addRendition(f.url[0],f.width,f.height,f.videoCodec,f.bitrate);i.set(f,`${h}`),m.id=`${h}`}}),e.on(me.Events.AUDIO_TRACKS_UPDATED,function(c,u){o();for(let d of u.audioTracks){let h=d.default?"main":"alternative",f=s.addAudioTrack(h,d.name,d.lang);f.id=`${d.id}`,d.default&&(f.enabled=!0)}}),s.audioTracks.addEventListener("change",()=>{var c;let u=+((c=[...s.audioTracks].find(h=>h.enabled))==null?void 0:c.id),d=e.audioTracks.map(h=>h.id);u!=e.audioTrack&&d.includes(u)&&(e.audioTrack=u)}),e.on(me.Events.LEVELS_UPDATED,function(c,u){var d;let h=s.videoTracks[(d=s.videoTracks.selectedIndex)!=null?d:0];if(!h)return;let f=u.levels.map(m=>i.get(m));for(let m of s.videoRenditions)m.id&&!f.includes(m.id)&&h.removeRendition(m)});let r=c=>{let u=c.target.selectedIndex;u!=e.nextLevel&&n(u)},n=c=>{let u=s.currentTime,d=!1,h=(f,m)=>{d||(d=!Number.isFinite(m.endOffset))};e.on(me.Events.BUFFER_FLUSHING,h),e.nextLevel=c,e.off(me.Events.BUFFER_FLUSHING,h),d||e.trigger(me.Events.BUFFER_FLUSHING,{startOffset:u+10,endOffset:1/0,type:"video"})};(t=s.videoRenditions)==null||t.addEventListener("change",r);let a=()=>{for(let c of s.videoTracks)s.removeVideoTrack(c)},o=()=>{for(let c of s.audioTracks)s.removeAudioTrack(c)},l=()=>{a(),o()};e.once(me.Events.DESTROYING,l)}var Ja=s=>"time"in s?s.time:s.startTime;function E0(s,e){e.on(me.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{tracks:n})=>{n.forEach(a=>{var o,l;let c=(o=a.subtitleTrack)!=null?o:a.closedCaptions,u=e.subtitleTracks.findIndex(({lang:h,name:f,type:m})=>h==(c==null?void 0:c.lang)&&f===a.label&&m.toLowerCase()===a.kind),d=((l=a._id)!=null?l:a.default)?"default":`${a.kind}${u}`;hu(s,a.kind,a.label,c==null?void 0:c.lang,d,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let r=Array.from(s.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind));if(!r)return;let n=e.subtitleTracks[e.subtitleTrack],a=n?n.default?"default":`${e.subtitleTracks[e.subtitleTrack].type.toLowerCase()}${e.subtitleTrack}`:void 0;if(e.subtitleTrack<0||(r==null?void 0:r.id)!==a){let o=e.subtitleTracks.findIndex(({lang:l,name:c,type:u,default:d})=>r.id==="default"&&d||l==r.language&&c===r.label&&u.toLowerCase()===r.kind);e.subtitleTrack=o}(r==null?void 0:r.id)===a&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};s.textTracks.addEventListener("change",t),e.on(me.Events.CUES_PARSED,(r,{track:n,cues:a})=>{let o=s.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(c=>{var u;(u=o.cues)!=null&&u.getCueById(c.id)||o.addCue(c)}),l&&(o.mode="disabled")}),e.once(me.Events.DESTROYING,()=>{s.textTracks.removeEventListener("change",t),s.querySelectorAll("track[data-removeondestroy]").forEach(r=>{r.remove()})});let i=()=>{Array.from(s.textTracks).forEach(r=>{var n,a;if(!["subtitles","caption"].includes(r.kind)&&(r.label==="thumbnails"||r.kind==="chapters")){if(!((n=r.cues)!=null&&n.length)){let o="track";r.kind&&(o+=`[kind="${r.kind}"]`),r.label&&(o+=`[label="${r.label}"]`);let l=s.querySelector(o),c=(a=l==null?void 0:l.getAttribute("src"))!=null?a:"";l==null||l.removeAttribute("src"),setTimeout(()=>{l==null||l.setAttribute("src",c)},0)}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(me.Events.MANIFEST_LOADED,i),e.once(me.Events.MEDIA_ATTACHED,i)}function hu(s,e,t,i,r,n){let a=document.createElement("track");return a.kind=e,a.label=t,i&&(a.srclang=i),r&&(a.id=r),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),s.append(a),a.track}function ss(s,e,t){var i;return(i=Array.from(s.querySelectorAll("track")).find(r=>r.track.label===e&&r.track.kind===t))==null?void 0:i.track}async function fu(s,e,t,i){let r=ss(s,t,i);return r||(r=hu(s,i,t),r.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),r.mode!=="hidden"&&(r.mode="hidden"),[...e].sort((n,a)=>Ja(a)-Ja(n)).forEach(n=>{var a,o;let l=n.value,c=Ja(n);if("endTime"in n&&n.endTime!=null)r==null||r.addCue(new VTTCue(c,n.endTime,i==="chapters"?l:JSON.stringify(l!=null?l:null)));else{let u=Array.prototype.findIndex.call(r==null?void 0:r.cues,m=>m.startTime>=c),d=(a=r==null?void 0:r.cues)==null?void 0:a[u],h=d?d.startTime:Number.isFinite(s.duration)?s.duration:Number.MAX_SAFE_INTEGER,f=(o=r==null?void 0:r.cues)==null?void 0:o[u-1];f&&(f.endTime=c),r==null||r.addCue(new VTTCue(c,h,i==="chapters"?l:JSON.stringify(l!=null?l:null)))}}),s.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),r}var oo="cuepoints",mu=Object.freeze({label:oo});async function lo(s,e,t=mu){return fu(s,e,t.label,"metadata")}var io=s=>({time:s.startTime,value:JSON.parse(s.text)});function gu(s,e={label:oo}){let t=ss(s,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,i=>io(i)):[]}function co(s,e={label:oo}){var t,i;let r=ss(s,e.label,"metadata");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return io(r.activeCues[0]);let{currentTime:n}=s,a=Array.prototype.find.call((i=r.activeCues)!=null?i:[],({startTime:o,endTime:l})=>o<=n&&l>n);return io(a||r.activeCues[0])}async function T0(s,e=mu){return new Promise(t=>{xe(s,"loadstart",async()=>{let i=await lo(s,[],e);xe(s,"cuechange",()=>{let r=co(s);if(r){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});s.dispatchEvent(n)}},{},i),t(i)})})}var uo="chapters",pu=Object.freeze({label:uo}),so=s=>({startTime:s.startTime,endTime:s.endTime,value:s.text});async function ho(s,e,t=pu){return fu(s,e,t.label,"chapters")}function yu(s,e={label:uo}){var t;let i=ss(s,e.label,"chapters");return(t=i==null?void 0:i.cues)!=null&&t.length?Array.from(i.cues,r=>so(r)):[]}function fo(s,e={label:uo}){var t,i;let r=ss(s,e.label,"chapters");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return so(r.activeCues[0]);let{currentTime:n}=s,a=Array.prototype.find.call((i=r.activeCues)!=null?i:[],({startTime:o,endTime:l})=>o<=n&&l>n);return so(a||r.activeCues[0])}async function x0(s,e=pu){return new Promise(t=>{xe(s,"loadstart",async()=>{let i=await ho(s,[],e);xe(s,"cuechange",()=>{let r=fo(s);if(r){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:r});s.dispatchEvent(n)}},{},i),t(i)})})}function vu(s,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-s.currentTime*1e3)}return typeof s.getStartDate=="function"?s.getStartDate():new Date(NaN)}function Eu(s,e){if(e&&e.playingDate)return e.playingDate;if(typeof s.getStartDate=="function"){let t=s.getStartDate();return new Date(t.getTime()+s.currentTime*1e3)}return new Date(NaN)}var eu={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},_0=s=>{if(s===fe.VIDEO)return eu.VIDEO;if(s===fe.DRM)return eu.DRM},S0=(s,e)=>{var t,i;let r=lu(s),n=`${r}Token`;return(t=e.tokens)!=null&&t[r]?(i=e.tokens)==null?void 0:i[r]:no(n,e)?e[n]:void 0},Sr=(s,e,t,i=!1,r=!(n=>(n=globalThis.navigator)==null?void 0:n.onLine)())=>{var n,a;if(r){let p=se("Your device appears to be offline",i),v,E=V.MEDIA_ERR_NETWORK,T=new V(p,E,!0,v);return T.errorCategory=e,T.muxCode=ue.NETWORK_OFFLINE,T.data=s,T}let o="status"in s?s.status:s.code,l=Date.now(),c=V.MEDIA_ERR_NETWORK;if(o===200)return;let u=lu(e),d=S0(e,t),h=_0(e),[f]=Ar((n=t.playbackId)!=null?n:"");if(!o||!f)return;let m=c0(d);if(d&&!m){let p=se("The {tokenNamePrefix}-token provided is invalid or malformed.",i).format({tokenNamePrefix:u}),v=se("Compact JWT string: {token}",i).format({token:d}),E=new V(p,c,!0,v);return E.errorCategory=e,E.muxCode=ue.NETWORK_TOKEN_MALFORMED,E.data=s,E}if(o>=500){let p=new V("",c,!0);return p.errorCategory=e,p.muxCode=ue.NETWORK_UNKNOWN_ERROR,p}if(o===403)if(m){if(u0(m,l)){let p={timeStyle:"medium",dateStyle:"medium"},v=se("The video\u2019s secured {tokenNamePrefix}-token has expired.",i).format({tokenNamePrefix:u}),E=se("Expired at: {expiredDate}. Current time: {currentDate}.",i).format({expiredDate:new Intl.DateTimeFormat("en",p).format((a=m.exp)!=null?a:0*1e3),currentDate:new Intl.DateTimeFormat("en",p).format(l)}),T=new V(v,c,!0,E);return T.errorCategory=e,T.muxCode=ue.NETWORK_TOKEN_EXPIRED,T.data=s,T}if(d0(m,f)){let p=se("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",i).format({tokenNamePrefix:u}),v=se("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",i).format({tokenNamePrefix:u,playbackId:f,tokenPlaybackId:m.sub}),E=new V(p,c,!0,v);return E.errorCategory=e,E.muxCode=ue.NETWORK_TOKEN_SUB_MISMATCH,E.data=s,E}if(h0(m,h)){let p=se("The {tokenNamePrefix}-token is formatted with incorrect information.",i).format({tokenNamePrefix:u}),v=se("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",i).format({tokenNamePrefix:u,expectedAud:h}),E=new V(p,c,!0,v);return E.errorCategory=e,E.muxCode=ue.NETWORK_TOKEN_AUD_MISSING,E.data=s,E}if(f0(m,h)){let p=se("The {tokenNamePrefix}-token is formatted with incorrect information.",i).format({tokenNamePrefix:u}),v=se("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",i).format({tokenNamePrefix:u,expectedAud:h,aud:m.aud}),E=new V(p,c,!0,v);return E.errorCategory=e,E.muxCode=ue.NETWORK_TOKEN_AUD_MISMATCH,E.data=s,E}}else{let p=se("Authorization error trying to access this {category} URL. If this is a signed URL, you might need to provide a {tokenNamePrefix}-token.",i).format({tokenNamePrefix:u,category:e}),v=se("Specified playback ID: {playbackId}",i).format({playbackId:f}),E=new V(p,c,!0,v);return E.errorCategory=e,E.muxCode=ue.NETWORK_TOKEN_MISSING,E.data=s,E}if(o===412){let p=se("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",i),v=se("Specified playback ID: {playbackId}",i).format({playbackId:f}),E=new V(p,c,!0,v);return E.errorCategory=e,E.muxCode=ue.NETWORK_NOT_READY,E.data=s,E}if(o===404){let p=se("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",i),v=se("Specified playback ID: {playbackId}",i).format({playbackId:f}),E=new V(p,c,!0,v);return E.errorCategory=e,E.muxCode=ue.NETWORK_NOT_FOUND,E.data=s,E}if(o===400){let p=se("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."),v=se("Specified playback ID: {playbackId}",i).format({playbackId:f}),E=new V(p,c,!0,v);return E.errorCategory=e,E.muxCode=ue.NETWORK_INVALID_URL,E.data=s,E}let g=new V("",c,!0);return g.errorCategory=e,g.muxCode=ue.NETWORK_UNKNOWN_ERROR,g.data=s,g},xr={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},b0=s=>{if(s.includes("fps"))return xr.FAIRPLAY;if(s.includes("playready"))return xr.PLAYREADY;if(s.includes("widevine"))return xr.WIDEVINE},A0=async s=>fetch(s).then(e=>e.status!==200?Promise.reject(e):e.text()).then(e=>{let t=e.split(` `).find((i,r,n)=>r&&n[r-1].startsWith("#EXT-X-STREAM-INF"));return fetch(t).then(i=>i.status!==200?Promise.reject(i):i.text()).then(i=>i.split(` `))}),R0=s=>{var e,t,i;let r=(t=((e=s.find(l=>l.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),n=cu(r),a=uu(r),o;if(n===Ue.LIVE){let l=s.find(c=>c.startsWith("#EXT-X-PART-INF"));if(l)o=+l.split(":")[1].split("=")[1]*2;else{let c=s.find(d=>d.startsWith("#EXT-X-TARGETDURATION")),u=(i=c==null?void 0:c.split(":"))==null?void 0:i[1];o=+(u!=null?u:6)*3}}return{streamType:n,targetLiveWindow:a,liveEdgeStartOffset:o}},L0=async(s,e)=>{if(e===_t.MP4)return{streamType:Ue.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0};if(e===_t.M3U8){let t=await A0(s);return R0(t)}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${s}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0}},I0=async(s,e,t=Rr({src:s}))=>{var i,r,n;let{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}=await L0(s,t);((i=Ce.get(e))!=null?i:{}).liveEdgeStartOffset=l,((r=Ce.get(e))!=null?r:{}).targetLiveWindow=o,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((n=Ce.get(e))!=null?n:{}).streamType=a,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},D0=s=>{var e;let t=s.type,i=cu(t),r=uu(t),n,a=!!((e=s.partList)!=null&&e.length);return i===Ue.LIVE&&(n=a?s.partTarget*2:s.targetduration*3),{streamType:i,targetLiveWindow:r,liveEdgeStartOffset:n,lowLatency:a}},k0=(s,e,t)=>{var i,r,n,a,o,l,c,u;let{streamType:d,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=D0(s);if(d===Ue.LIVE){m?(t.config.backBufferLength=(i=t.userConfig.backBufferLength)!=null?i:4,t.config.maxFragLookUpTolerance=(r=t.userConfig.maxFragLookUpTolerance)!=null?r:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let g=Object.freeze({get length(){return e.seekable.length},start(p){return e.seekable.start(p)},end(p){var v;return p>this.length||p<0||Number.isFinite(e.duration)?e.seekable.end(p):(v=t.liveSyncPosition)!=null?v:e.seekable.end(p)}});((o=Ce.get(e))!=null?o:{}).seekable=g}((l=Ce.get(e))!=null?l:{}).liveEdgeStartOffset=f,((c=Ce.get(e))!=null?c:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((u=Ce.get(e))!=null?u:{}).streamType=d,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},tu,iu,w0=(iu=(tu=globalThis==null?void 0:globalThis.navigator)==null?void 0:tu.userAgent)!=null?iu:"",su,ru,nu,C0=(nu=(ru=(su=globalThis==null?void 0:globalThis.navigator)==null?void 0:su.userAgentData)==null?void 0:ru.platform)!=null?nu:"",P0=w0.toLowerCase().includes("android")||["x11","android"].some(s=>C0.toLowerCase().includes(s)),Ce=new WeakMap,xt="mux.com",au,ou,Tu=(ou=(au=me).isSupported)==null?void 0:ou.call(au),O0=P0,xu=()=>Is.utils.now(),M0=Is.utils.generateUUID,_u=({playbackId:s,customDomain:e=xt,maxResolution:t,minResolution:i,renditionOrder:r,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:c,tokens:{playback:u=c}={},extraSourceParams:d={}}={})=>{if(!s)return;let[h,f=""]=Ar(s),m=new URL(`https://stream.${e}/${h}.m3u8${f}`);return u||m.searchParams.has("token")?(m.searchParams.forEach((g,p)=>{p!="token"&&m.searchParams.delete(p)}),u&&m.searchParams.set("token",u)):(t&&m.searchParams.set("max_resolution",t),i&&(m.searchParams.set("min_resolution",i),t&&+t.slice(0,-1)<+i.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",i,"maxResolution",t)),r&&m.searchParams.set("rendition_order",r),n&&m.searchParams.set("program_start_time",`${n}`),a&&m.searchParams.set("program_end_time",`${a}`),o&&m.searchParams.set("asset_start_time",`${o}`),l&&m.searchParams.set("asset_end_time",`${l}`),Object.entries(d).forEach(([g,p])=>{p!=null&&m.searchParams.set(g,p)})),m.toString()},Lr=s=>{if(!s)return;let[e]=s.split("?");return e||void 0},mo=s=>{if(!s||!s.startsWith("https://stream."))return;let[e]=new URL(s).pathname.slice(1).split(".m3u8");return e||void 0},N0=s=>{var e,t,i;return(e=s==null?void 0:s.metadata)!=null&&e.video_id?s.metadata.video_id:ku(s)&&(i=(t=Lr(s.playbackId))!=null?t:mo(s.src))!=null?i:s.src},go=s=>{var e;return(e=Ce.get(s))==null?void 0:e.error},br=s=>{var e,t;return(t=(e=Ce.get(s))==null?void 0:e.streamType)!=null?t:Ue.UNKNOWN},Su=s=>{var e,t;return(t=(e=Ce.get(s))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},Ir=s=>{var e,t;return(t=(e=Ce.get(s))==null?void 0:e.seekable)!=null?t:s.seekable},bu=s=>{var e;let t=(e=Ce.get(s))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let i=Ir(s);return i.length?i.end(i.length-1)-t:Number.NaN},po=.034,F0=(s,e,t=po)=>Math.abs(s-e)<=t,Au=(s,e,t=po)=>s>e||F0(s,e,t),U0=(s,e=po)=>s.paused&&Au(s.currentTime,s.duration,e),Ru=(s,e)=>{var t,i,r;if(!e||!s.buffered.length)return;if(s.readyState>2)return!1;let n=e.currentLevel>=0?(i=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:i.details:(r=e.levels.find(d=>!!d.details))==null?void 0:r.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(s.currentTimec&&ls.ended||s.loop?s.ended:e&&Ru(s,e)?!0:U0(s),Lu=(s,e,t)=>{vo(e,t);let{metadata:i={}}=s,{view_session_id:r=M0()}=i,n=N0(s);i.view_session_id=r,i.video_id=n,s.metadata=i;let a=u=>{var d;(d=e.mux)==null||d.emit("hb",{view_drm_type:u})};s.drmTypeCb=a,Ce.set(e,{});let o=B0(s,e),l=y0(s,e,o);q0(s,e,o),W0(s,e,o),T0(e),x0(e);let c=p0(s,e,o);return{engine:o,setAutoplay:c,setPreload:l}},vo=(s,e)=>{let t=e==null?void 0:e.engine;t&&(t.detachMedia(),t.destroy()),s!=null&&s.mux&&!s.mux.deleted&&(s.mux.destroy(),delete s.mux),s&&(s.removeAttribute("src"),s.load(),s.removeEventListener("error",Cu),s.removeEventListener("error",ro),s.removeEventListener("durationchange",wu),Ce.delete(s),s.dispatchEvent(new Event("teardown")))};function Iu(s,e){var t;let i=Rr(s);if(i!==_t.M3U8)return!0;let r=!i||((t=e.canPlayType(i))!=null?t:!0),{preferPlayback:n}=s,a=n===Xt.MSE,o=n===Xt.NATIVE;return r&&(o||!(Tu&&(a||O0)))}var B0=(s,e)=>{let{debug:t,streamType:i,startTime:r=-1,metadata:n,preferCmcd:a,_hlsConfig:o={}}=s,l=Rr(s)===_t.M3U8,c=Iu(s,e);if(l&&!c&&Tu){let u={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelToPlayerSize:!0,capLevelOnFPSDrop:!0},d=$0(i),h=G0(s),f=a!==Tr.NONE?{useHeaders:a===Tr.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0;return new me({debug:t,startPosition:r,cmcd:f,xhrSetup:(m,g)=>{var p,v;if(a&&a!==Tr.QUERY)return;let E=new URL(g);if(!E.searchParams.has("CMCD"))return;let T=((v=(p=E.searchParams.get("CMCD"))==null?void 0:p.split(","))!=null?v:[]).filter(x=>x.startsWith("sid")||x.startsWith("cid")).join(",");E.searchParams.set("CMCD",T),m.open("GET",E)},...u,...d,...h,...o})}},$0=s=>s===Ue.LIVE?{backBufferLength:8}:{},G0=s=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:i}=s,r=Lr(t);return!e||!r?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:_r(s,"fairplay"),serverCertificateUrl:Du(s,"fairplay")},"com.widevine.alpha":{licenseUrl:_r(s,"widevine")},"com.microsoft.playready":{licenseUrl:_r(s,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let c=(l=o.videoCapabilities)==null?void 0:l.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:c}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let l=b0(n);return i==null||i(l),o}))}},K0=async s=>{let e=await fetch(s);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},H0=async(s,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:s});if(t.status!==200)return Promise.reject(t);let i=await t.arrayBuffer();return new Uint8Array(i)},V0=(s,e)=>{xe(e,"encrypted",async t=>{try{let i=t.initDataType;if(i!=="skd"){console.error(`Received unexpected initialization data type "${i}"`);return}if(!e.mediaKeys){let l=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[i],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(u=>{var d;return(d=s.drmTypeCb)==null||d.call(s,xr.FAIRPLAY),u}).catch(()=>{let u=se("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),d=new V(u,V.MEDIA_ERR_ENCRYPTED,!0);d.errorCategory=fe.DRM,d.muxCode=ue.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,e.dispatchEvent(new CustomEvent("error",{detail:d}))});if(!l)return;let c=await l.createMediaKeys();try{let u=await K0(Du(s,"fairplay")).catch(d=>{if(d instanceof Response){let h=Sr(d,fe.DRM,s);return console.error("mediaError",h==null?void 0:h.message,h==null?void 0:h.context),h?Promise.reject(h):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(d)});await c.setServerCertificate(u).catch(()=>{let d=se("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),h=new V(d,V.MEDIA_ERR_ENCRYPTED,!0);return h.errorCategory=fe.DRM,h.muxCode=ue.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(h)})}catch(u){e.dispatchEvent(new CustomEvent("error",{detail:u}));return}await e.setMediaKeys(c)}let r=t.initData;if(r==null){console.error(`Could not start encrypted playback due to missing initData in ${t.type} event`);return}let n=e.mediaKeys.createSession();n.addEventListener("keystatuseschange",()=>{n.keyStatuses.forEach(l=>{let c;if(l==="internal-error"){let u=se("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");c=new V(u,V.MEDIA_ERR_ENCRYPTED,!0),c.errorCategory=fe.DRM,c.muxCode=ue.ENCRYPTED_CDM_ERROR}else if(l==="output-restricted"||l==="output-downscaled"){let u=se("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");c=new V(u,V.MEDIA_ERR_ENCRYPTED,!1),c.errorCategory=fe.DRM,c.muxCode=ue.ENCRYPTED_OUTPUT_RESTRICTED}c&&e.dispatchEvent(new CustomEvent("error",{detail:c}))})});let a=await Promise.all([n.generateRequest(i,r).catch(()=>{let l=se("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),c=new V(l,V.MEDIA_ERR_ENCRYPTED,!0);c.errorCategory=fe.DRM,c.muxCode=ue.ENCRYPTED_GENERATE_REQUEST_FAILED,e.dispatchEvent(new CustomEvent("error",{detail:c}))}),new Promise(l=>{n.addEventListener("message",c=>{l(c.message)},{once:!0})})]).then(([,l])=>l);n.generateRequest(i,r);let o=await H0(a,_r(s,"fairplay")).catch(l=>{if(l instanceof Response){let c=Sr(l,fe.DRM,s);return console.error("mediaError",c==null?void 0:c.message,c==null?void 0:c.context),c?Promise.reject(c):Promise.reject(new Error("Unexpected error in license key request"))}return Promise.reject(l)});await n.update(o).catch(()=>{let l=se("Failed to update DRM license. This may be an issue with the player or your protected content."),c=new V(l,V.MEDIA_ERR_ENCRYPTED,!0);return c.errorCategory=fe.DRM,c.muxCode=ue.ENCRYPTED_UPDATE_LICENSE_FAILED,Promise.reject(c)})}catch(i){e.dispatchEvent(new CustomEvent("error",{detail:i}));return}})},_r=({playbackId:s,tokens:{drm:e}={},customDomain:t=xt},i)=>{let r=Lr(s);return`https://license.${t.toLocaleLowerCase().endsWith(xt)?t:xt}/license/${i}/${r}?token=${e}`},Du=({playbackId:s,tokens:{drm:e}={},customDomain:t=xt},i)=>{let r=Lr(s);return`https://license.${t.toLocaleLowerCase().endsWith(xt)?t:xt}/appcert/${i}/${r}?token=${e}`},ku=({playbackId:s,src:e,customDomain:t})=>{if(s)return!0;if(typeof e!="string")return!1;let i=window==null?void 0:window.location.href,r=new URL(e,i).hostname.toLocaleLowerCase();return r.includes(xt)||!!t&&r.includes(t.toLocaleLowerCase())},q0=(s,e,t)=>{var i;let{envKey:r,disableTracking:n}=s,a=ku(s);if(!n&&(r||a)){let{playerInitTime:o,playerSoftwareName:l,playerSoftwareVersion:c,beaconCollectionDomain:u,debug:d,disableCookies:h}=s,f={...s.metadata,video_title:((i=s==null?void 0:s.metadata)==null?void 0:i.video_title)||void 0},m=g=>typeof g.player_error_code=="string"?!1:typeof s.errorTranslator=="function"?s.errorTranslator(g):g;Is.monitor(e,{debug:d,beaconCollectionDomain:u,hlsjs:t,Hls:t?me:void 0,automaticErrorTracking:!1,errorTranslator:m,disableCookies:h,data:{...r?{env_key:r}:{},player_software_name:l,player_software:l,player_software_version:c,player_init_time:o,...f}})}},W0=(s,e,t)=>{var i,r;let n=Iu(s,e),{src:a}=s,o=()=>{e.ended||!yo(e,t)||(Ru(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},l,c,u=()=>{let d=Ir(e),h,f;d.length>0&&(h=d.start(0),f=d.end(0)),(c!==f||l!==h)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),l=h,c=f};if(xe(e,"durationchange",u),e&&n){let d=Rr(s);if(typeof a=="string"){let h=()=>{if(br(e)!==Ue.LIVE||Number.isFinite(e.duration))return;let m=setInterval(u,1e3);e.addEventListener("teardown",()=>{clearInterval(m)},{once:!0}),xe(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(m)})},f=async()=>I0(a,e,d).then(h).catch(m=>{if(m instanceof Response){let g=Sr(m,fe.VIDEO,s);if(g){e.dispatchEvent(new CustomEvent("error",{detail:g}));return}}else m instanceof Error});if(e.preload==="none"){let m=()=>{f(),e.removeEventListener("loadedmetadata",g)},g=()=>{f(),e.removeEventListener("play",m)};xe(e,"play",m,{once:!0}),xe(e,"loadedmetadata",g,{once:!0})}else f();(i=s.tokens)!=null&&i.drm?V0(s,e):xe(e,"encrypted",()=>{let m=se("Attempting to play DRM-protected content without providing a DRM token."),g=new V(m,V.MEDIA_ERR_ENCRYPTED,!0);g.errorCategory=fe.DRM,g.muxCode=ue.ENCRYPTED_MISSING_TOKEN,e.dispatchEvent(new CustomEvent("error",{detail:g}))},{once:!0}),e.setAttribute("src",a),s.startTime&&(((r=Ce.get(e))!=null?r:{}).startTime=s.startTime,e.addEventListener("durationchange",wu,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",Cu),e.addEventListener("error",ro),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(h=>{h.remove()})},{once:!0}),xe(e,"pause",o),xe(e,"seeked",o),xe(e,"play",()=>{e.ended||Au(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else t&&a?(t.once(me.Events.LEVEL_LOADED,(d,h)=>{k0(h.details,e,t),u(),br(e)===Ue.LIVE&&!Number.isFinite(e.duration)&&(t.on(me.Events.LEVEL_UPDATED,u),xe(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(me.Events.LEVELS_UPDATED,u)}))}),t.on(me.Events.ERROR,(d,h)=>{e.dispatchEvent(new CustomEvent("error",{detail:Y0(h,s)}))}),e.addEventListener("error",ro),xe(e,"waiting",o),v0(s,t),E0(e,t),t.attachMedia(e)):console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function wu(s){var e;let t=s.target,i=(e=Ce.get(t))==null?void 0:e.startTime;if(i&&o0(t.seekable,t.duration,i)){let r=t.preload==="auto";r&&(t.preload="none"),t.currentTime=i,r&&(t.preload="auto")}}async function Cu(s){if(!s.isTrusted)return;s.stopImmediatePropagation();let e=s.target;if(!(e!=null&&e.error))return;let{message:t,code:i}=e.error,r=new V(t,i);if(e.src&&i===V.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=go(e))!=null?n:e.error;(a==null?void 0:a.code)===V.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.dispatchEvent(new CustomEvent("error",{detail:r}))},500);return}if(e.src&&(i!==V.MEDIA_ERR_DECODE||i!==void 0))try{let{status:n}=await fetch(e.src);r.data={response:{code:n}}}catch{}e.dispatchEvent(new CustomEvent("error",{detail:r}))}function ro(s){var e,t;if(!(s instanceof CustomEvent)||!(s.detail instanceof V))return;let i=s.target,r=s.detail;!r||!r.fatal||(((e=Ce.get(i))!=null?e:{}).error=r,(t=i.mux)==null||t.emit("error",{player_error_code:r.code,player_error_message:r.message,player_error_context:r.context}))}var Y0=(s,e)=>{var t,i,r;console.error("getErrorFromHlsErrorData()",s);let n={[me.ErrorTypes.NETWORK_ERROR]:V.MEDIA_ERR_NETWORK,[me.ErrorTypes.MEDIA_ERROR]:V.MEDIA_ERR_DECODE,[me.ErrorTypes.KEY_SYSTEM_ERROR]:V.MEDIA_ERR_ENCRYPTED},a=u=>[D.KEY_SYSTEM_LICENSE_REQUEST_FAILED,D.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(u.details)?V.MEDIA_ERR_NETWORK:n[u.type],o=u=>{if(u.type===j.KEY_SYSTEM_ERROR)return fe.DRM;if(u.type===j.NETWORK_ERROR)return fe.VIDEO},l,c=a(s);if(c===V.MEDIA_ERR_NETWORK&&s.response){let u=(t=o(s))!=null?t:fe.VIDEO;l=(i=Sr(s.response,u,e))!=null?i:new V("",c)}else if(c===V.MEDIA_ERR_ENCRYPTED)if(s.details===D.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let u=se("Attempting to play DRM-protected content without providing a DRM token.");l=new V(u,V.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=fe.DRM,l.muxCode=ue.ENCRYPTED_MISSING_TOKEN}else if(s.details===D.KEY_SYSTEM_NO_ACCESS){let u=se("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");l=new V(u,V.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=fe.DRM,l.muxCode=ue.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(s.details===D.KEY_SYSTEM_NO_SESSION){let u=se("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");l=new V(u,V.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=fe.DRM,l.muxCode=ue.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(s.details===D.KEY_SYSTEM_SESSION_UPDATE_FAILED){let u=se("Failed to update DRM license. This may be an issue with the player or your protected content.");l=new V(u,V.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=fe.DRM,l.muxCode=ue.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(s.details===D.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let u=se("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");l=new V(u,V.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=fe.DRM,l.muxCode=ue.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(s.details===D.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let u=se("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");l=new V(u,V.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=fe.DRM,l.muxCode=ue.ENCRYPTED_CDM_ERROR}else if(s.details===D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let u=se("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");l=new V(u,V.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=fe.DRM,l.muxCode=ue.ENCRYPTED_OUTPUT_RESTRICTED}else l=new V(s.error.message,V.MEDIA_ERR_ENCRYPTED,s.fatal),l.errorCategory=fe.DRM,l.muxCode=ue.ENCRYPTED_ERROR;else l=new V("",c,s.fatal);return l.context||(l.context=`${s.url?`url: ${s.url} `:""}${s.response&&(s.response.code||s.response.text)?`response: ${s.response.code}, ${s.response.text} `:""}${s.reason?`failure reason: ${s.reason} `:""}${s.level?`level: ${s.level} `:""}${s.parent?`parent stream controller: ${s.parent} `:""}${s.buffer?`buffer length: ${s.buffer} `:""}${s.error?`error: ${s.error} `:""}${s.event?`event: ${s.event} `:""}${s.err?`error message: ${(r=s.err)==null?void 0:r.message} `:""}`),l.data=s,l};var j0=()=>{try{return"0.22.0"}catch{}return"UNKNOWN"},z0=j0(),Pu=()=>z0;var To=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting","waitingforkey","resize","enterpictureinpicture","leavepictureinpicture","webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"];function X0(s){return` `}function Q0(s){return` `}var Nu=(s,{tag:e,is:t})=>{var n,a,o,l,c,Fu,d,h,f,m,Qt,p,Eo,E,Uu,x,Bu;let i=(a=(n=globalThis.document)==null?void 0:n.createElement)==null?void 0:a.call(n,e,{is:t}),r=i?J0(i):[];return o=class extends s{constructor(){super();F(this,m);F(this,p);F(this,E);F(this,x);F(this,d,void 0);F(this,h,void 0);F(this,f,new Map)}static get observedAttributes(){var k,L,w;return ce(k=o,c,Fu).call(k),[...(w=(L=i==null?void 0:i.constructor)==null?void 0:L.observedAttributes)!=null?w:[],"autopictureinpicture","disablepictureinpicture","disableremoteplayback","autoplay","controls","controlslist","crossorigin","loop","muted","playsinline","poster","preload","src"]}get nativeEl(){var R,k,L;return ce(this,m,Qt).call(this),(L=(k=(R=S(this,h))!=null?R:this.shadowRoot.querySelector(e))!=null?k:this.querySelector(":scope > [slot=media]"))!=null?L:this.querySelector(e)}set nativeEl(R){G(this,h,R)}get defaultMuted(){return this.hasAttribute("muted")}set defaultMuted(R){this.toggleAttribute("muted",!!R)}get src(){return this.getAttribute("src")}set src(R){this.setAttribute("src",`${R}`)}get preload(){var R,k;return(k=this.getAttribute("preload"))!=null?k:(R=this.nativeEl)==null?void 0:R.preload}set preload(R){this.setAttribute("preload",`${R}`)}init(){var R,k;if(!this.shadowRoot){this.attachShadow({mode:"open"});let L=Z0(this.attributes);t&&(L.is=t),e&&(L.part=e),this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(L)}this.nativeEl.muted=this.hasAttribute("muted");for(let L of r)ce(this,E,Uu).call(this,L);this.shadowRoot.addEventListener("slotchange",this),ce(this,p,Eo).call(this);for(let L of this.constructor.Events)(k=(R=this.shadowRoot).addEventListener)==null||k.call(R,L,this,!0)}handleEvent(R){if(R.type==="slotchange"){ce(this,p,Eo).call(this);return}R.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(R.type,{detail:R.detail}))}attributeChangedCallback(R,k,L){ce(this,m,Qt).call(this),ce(this,x,Bu).call(this,R,k,L)}connectedCallback(){ce(this,m,Qt).call(this)}},l=new WeakMap,c=new WeakSet,Fu=function(){if(S(this,l))return;G(this,l,!0);let R=new Set(this.observedAttributes);R.delete("muted");for(let k of r){if(k in this.prototype)continue;if(typeof i[k]=="function")this.prototype[k]=function(...w){return ce(this,m,Qt).call(this),this.call?this.call(k,...w):this.nativeEl[k].apply(this.nativeEl,w)};else{let w={get(){var O,W,q;ce(this,m,Qt).call(this);let P=k.toLowerCase();if(R.has(P)){let $=this.getAttribute(P);return $===null?!1:$===""?!0:$}return(q=(O=this.get)==null?void 0:O.call(this,k))!=null?q:(W=this.nativeEl)==null?void 0:W[k]}};k!==k.toUpperCase()&&(w.set=function(P){ce(this,m,Qt).call(this);let O=k.toLowerCase();if(R.has(O)){P===!0||P===!1||P==null?this.toggleAttribute(O,!!P):this.setAttribute(O,P);return}if(this.set){this.set(k,P);return}this.nativeEl[k]=P}),Object.defineProperty(this.prototype,k,w)}}},d=new WeakMap,h=new WeakMap,f=new WeakMap,m=new WeakSet,Qt=function(){S(this,d)||(G(this,d,!0),this.init())},p=new WeakSet,Eo=function(){let R=new Map(S(this,f));this.shadowRoot.querySelector("slot:not([name])").assignedElements({flatten:!0}).filter(k=>["track","source"].includes(k.localName)).forEach(k=>{var w,P;R.delete(k);let L=S(this,f).get(k);L||(L=k.cloneNode(),S(this,f).set(k,L)),(P=(w=this.nativeEl).append)==null||P.call(w,L),L.localName==="track"&&L.default&&(L.kind==="chapters"||L.kind==="metadata")&&L.track.mode==="disabled"&&(L.track.mode="hidden")}),R.forEach(k=>k.remove())},E=new WeakSet,Uu=function(R){if(Object.prototype.hasOwnProperty.call(this,R)){let k=this[R];delete this[R],this[R]=k}},x=new WeakSet,Bu=function(R,k,L){var w,P,O,W,q,$;["id","class"].includes(R)||!o.observedAttributes.includes(R)&&this.constructor.observedAttributes.includes(R)||(L===null?(P=(w=this.nativeEl).removeAttribute)==null||P.call(w,R):((W=(O=this.nativeEl).getAttribute)==null?void 0:W.call(O,R))!=L&&(($=(q=this.nativeEl).setAttribute)==null||$.call(q,R,L)))},F(o,c),te(o,"getTemplateHTML",e.endsWith("audio")?X0:Q0),te(o,"shadowRootOptions",{mode:"open"}),te(o,"Events",To),F(o,l,void 0),o};function J0(s){let e=[];for(let t=Object.getPrototypeOf(s);t&&t!==HTMLElement.prototype;t=Object.getPrototypeOf(t))e.push(...Object.getOwnPropertyNames(t));return e}function $u(s){let e="";for(let t in s){let i=s[t];i===""?e+=` ${t}`:e+=` ${t}="${i}"`}return e}function Z0(s){let e={};for(let t of s)e[t.name]=t.value;return e}var Ou,Dr=Nu((Ou=globalThis.HTMLElement)!=null?Ou:class{},{tag:"video"}),Mu,_y=Nu((Mu=globalThis.HTMLElement)!=null?Mu:class{},{tag:"audio"});var dt=new WeakMap,Ei=class extends Error{},kr=class extends Error{};var Gu=globalThis.WeakRef?class extends Set{add(s){super.add(new WeakRef(s))}forEach(s){super.forEach(e=>{let t=e.deref();t&&s(t)})}}:Set;function Ku(s){var e,t,i;(t=(e=globalThis.chrome)==null?void 0:e.cast)!=null&&t.isAvailable?(i=globalThis.cast)!=null&&i.framework?s():customElements.whenDefined("google-cast-button").then(s):globalThis.__onGCastApiAvailable=()=>{customElements.whenDefined("google-cast-button").then(s)}}function Hu(){return globalThis.chrome}function Vu(){var t;let s="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1";if((t=globalThis.chrome)!=null&&t.cast||document.querySelector(`script[src="${s}"]`))return;let e=document.createElement("script");e.src=s,document.head.append(e)}function St(){var s,e;return(e=(s=globalThis.cast)==null?void 0:s.framework)==null?void 0:e.CastContext.getInstance()}function rs(){var s;return(s=St())==null?void 0:s.getCurrentSession()}function wr(){var s;return(s=rs())==null?void 0:s.getSessionObj().media[0]}function qu(s){return new Promise((e,t)=>{wr().editTracksInfo(s,e,t)})}function Wu(s){return new Promise((e,t)=>{wr().getStatus(s,e,t)})}function xo(s){return St().setOptions({..._o(),...s})}function _o(){return{receiverApplicationId:"CC1AD845",autoJoinPolicy:"origin_scoped",androidReceiverCompatible:!1,language:"en-US",resumeSavedSession:!0}}var Cr=new Gu,bt=new WeakSet,Re;Ku(()=>{var s,e,t,i;if(!((e=(s=globalThis.chrome)==null?void 0:s.cast)!=null&&e.isAvailable)){console.debug("chrome.cast.isAvailable",(i=(t=globalThis.chrome)==null?void 0:t.cast)==null?void 0:i.isAvailable);return}Re||(Re=cast.framework,St().addEventListener(Re.CastContextEventType.CAST_STATE_CHANGED,r=>{Cr.forEach(n=>{var a,o;return(o=(a=dt.get(n)).onCastStateChanged)==null?void 0:o.call(a,r)})}),St().addEventListener(Re.CastContextEventType.SESSION_STATE_CHANGED,r=>{Cr.forEach(n=>{var a,o;return(o=(a=dt.get(n)).onSessionStateChanged)==null?void 0:o.call(a,r)})}),Cr.forEach(r=>{var n,a;return(a=(n=dt.get(r)).init)==null?void 0:a.call(n)}))});var Yu=0,oe,ns,Be,ht,Zt,ei,At,Or,ft,Jt,Mr,ju,as,So,Nr,zu,os,bo,Fr,Xu,ls,Ao,Pr=class extends EventTarget{constructor(t){super();F(this,ft);F(this,Mr);F(this,as);F(this,Nr);F(this,os);F(this,Fr);F(this,ls);F(this,oe,void 0);F(this,ns,void 0);F(this,Be,void 0);F(this,ht,void 0);F(this,Zt,"disconnected");F(this,ei,!1);F(this,At,new Set);F(this,Or,new WeakMap);G(this,oe,t),Cr.add(this),dt.set(this,{init:()=>ce(this,os,bo).call(this),onCastStateChanged:()=>ce(this,as,So).call(this),onSessionStateChanged:()=>ce(this,Nr,zu).call(this),getCastPlayer:()=>S(this,ft,Jt)}),ce(this,os,bo).call(this)}get state(){return S(this,Zt)}async watchAvailability(t){if(S(this,oe).disableRemotePlayback)throw new Ei("disableRemotePlayback attribute is present.");return S(this,Or).set(t,++Yu),S(this,At).add(t),Yu}async cancelWatchAvailability(t){if(S(this,oe).disableRemotePlayback)throw new Ei("disableRemotePlayback attribute is present.");t?S(this,At).delete(t):S(this,At).clear()}async prompt(){var i,r,n,a;if(S(this,oe).disableRemotePlayback)throw new Ei("disableRemotePlayback attribute is present.");if(!((r=(i=globalThis.chrome)==null?void 0:i.cast)!=null&&r.isAvailable))throw new kr("The RemotePlayback API is disabled on this platform.");let t=bt.has(S(this,oe));bt.add(S(this,oe)),xo(S(this,oe).castOptions),Object.entries(S(this,ht)).forEach(([o,l])=>{S(this,Be).controller.addEventListener(o,l)});try{await St().requestSession()}catch(o){if(o==="cancel"){t||bt.delete(S(this,oe));return}throw new Error(o)}(a=(n=dt.get(S(this,oe)))==null?void 0:n.loadOnPrompt)==null||a.call(n)}};oe=new WeakMap,ns=new WeakMap,Be=new WeakMap,ht=new WeakMap,Zt=new WeakMap,ei=new WeakMap,At=new WeakMap,Or=new WeakMap,ft=new WeakSet,Jt=function(){if(bt.has(S(this,oe)))return S(this,Be)},Mr=new WeakSet,ju=function(){bt.has(S(this,oe))&&(Object.entries(S(this,ht)).forEach(([t,i])=>{S(this,Be).controller.removeEventListener(t,i)}),bt.delete(S(this,oe)),S(this,oe).muted=S(this,Be).isMuted,S(this,oe).currentTime=S(this,Be).savedPlayerState.currentTime,S(this,Be).savedPlayerState.isPaused===!1&&S(this,oe).play())},as=new WeakSet,So=function(){let t=St().getCastState();if(bt.has(S(this,oe))&&t==="CONNECTING"&&(G(this,Zt,"connecting"),this.dispatchEvent(new Event("connecting"))),!S(this,ei)&&(t!=null&&t.includes("CONNECT"))){G(this,ei,!0);for(let i of S(this,At))i(!0)}else if(S(this,ei)&&(!t||t==="NO_DEVICES_AVAILABLE")){G(this,ei,!1);for(let i of S(this,At))i(!1)}},Nr=new WeakSet,zu=async function(){var i;let{SESSION_RESUMED:t}=Re.SessionState;if(St().getSessionState()===t&&S(this,oe).castSrc===((i=wr())==null?void 0:i.media.contentId)){bt.add(S(this,oe)),Object.entries(S(this,ht)).forEach(([r,n])=>{S(this,Be).controller.addEventListener(r,n)});try{await Wu(new chrome.cast.media.GetStatusRequest)}catch(r){console.error(r)}S(this,ht)[Re.RemotePlayerEventType.IS_PAUSED_CHANGED](),S(this,ht)[Re.RemotePlayerEventType.PLAYER_STATE_CHANGED]()}},os=new WeakSet,bo=function(){!Re||S(this,ns)||(G(this,ns,!0),xo(S(this,oe).castOptions),S(this,oe).textTracks.addEventListener("change",()=>ce(this,ls,Ao).call(this)),ce(this,as,So).call(this),G(this,Be,new Re.RemotePlayer),new Re.RemotePlayerController(S(this,Be)),G(this,ht,{[Re.RemotePlayerEventType.IS_CONNECTED_CHANGED]:({value:t})=>{t===!0?(G(this,Zt,"connected"),this.dispatchEvent(new Event("connect"))):(ce(this,Mr,ju).call(this),G(this,Zt,"disconnected"),this.dispatchEvent(new Event("disconnect")))},[Re.RemotePlayerEventType.DURATION_CHANGED]:()=>{S(this,oe).dispatchEvent(new Event("durationchange"))},[Re.RemotePlayerEventType.VOLUME_LEVEL_CHANGED]:()=>{S(this,oe).dispatchEvent(new Event("volumechange"))},[Re.RemotePlayerEventType.IS_MUTED_CHANGED]:()=>{S(this,oe).dispatchEvent(new Event("volumechange"))},[Re.RemotePlayerEventType.CURRENT_TIME_CHANGED]:()=>{var t;(t=S(this,ft,Jt))!=null&&t.isMediaLoaded&&S(this,oe).dispatchEvent(new Event("timeupdate"))},[Re.RemotePlayerEventType.VIDEO_INFO_CHANGED]:()=>{S(this,oe).dispatchEvent(new Event("resize"))},[Re.RemotePlayerEventType.IS_PAUSED_CHANGED]:()=>{S(this,oe).dispatchEvent(new Event(this.paused?"pause":"play"))},[Re.RemotePlayerEventType.PLAYER_STATE_CHANGED]:()=>{var t,i;((t=S(this,ft,Jt))==null?void 0:t.playerState)!==chrome.cast.media.PlayerState.PAUSED&&S(this,oe).dispatchEvent(new Event({[chrome.cast.media.PlayerState.PLAYING]:"playing",[chrome.cast.media.PlayerState.BUFFERING]:"waiting",[chrome.cast.media.PlayerState.IDLE]:"emptied"}[(i=S(this,ft,Jt))==null?void 0:i.playerState]))},[Re.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED]:async()=>{var t;(t=S(this,ft,Jt))!=null&&t.isMediaLoaded&&(await Promise.resolve(),ce(this,Fr,Xu).call(this))}}))},Fr=new WeakSet,Xu=function(){ce(this,ls,Ao).call(this)},ls=new WeakSet,Ao=async function(){var h,f,m,g,p;if(!S(this,ft,Jt))return;let i=((f=(h=S(this,Be).mediaInfo)==null?void 0:h.tracks)!=null?f:[]).filter(({type:v})=>v===chrome.cast.media.TrackType.TEXT),r=[...S(this,oe).textTracks].filter(({kind:v})=>v==="subtitles"||v==="captions"),n=i.map(({language:v,name:E,trackId:T})=>{var _;let{mode:x}=(_=r.find(I=>I.language===v&&I.label===E))!=null?_:{};return x?{mode:x,trackId:T}:!1}).filter(Boolean),o=n.filter(({mode:v})=>v!=="showing").map(({trackId:v})=>v),l=n.find(({mode:v})=>v==="showing"),c=(p=(g=(m=rs())==null?void 0:m.getSessionObj().media[0])==null?void 0:g.activeTrackIds)!=null?p:[],u=c;if(c.length&&(u=u.filter(v=>!o.includes(v))),l!=null&&l.trackId&&(u=[...u,l.trackId]),u=[...new Set(u)],!((v,E)=>v.length===E.length&&v.every(T=>E.includes(T)))(c,u))try{let v=new chrome.cast.media.EditTracksInfoRequest(u);await qu(v)}catch(v){console.error(v)}};var Qu=s=>{var e,t,i,r,n,a,o,re,c,Ju;return t=class extends s{constructor(){super(...arguments);F(this,o);F(this,c);F(this,i,{paused:!1});F(this,r,_o());F(this,n,void 0);F(this,a,void 0)}get remote(){return S(this,a)?S(this,a):Hu()?(Vu(),dt.set(this,{loadOnPrompt:()=>ce(this,c,Ju).call(this)}),G(this,a,new Pr(this))):super.remote}attributeChangedCallback(f,m,g){if(super.attributeChangedCallback(f,m,g),f==="cast-receiver"&&g){S(this,r).receiverApplicationId=g;return}if(S(this,o,re))switch(f){case"cast-stream-type":case"cast-src":this.load();break}}async load(){var E,T;if(!S(this,o,re))return super.load();let f=new chrome.cast.media.MediaInfo(this.castSrc,this.castContentType);f.customData=this.castCustomData;let m=[...this.querySelectorAll("track")].filter(({kind:x,src:_})=>_&&(x==="subtitles"||x==="captions")),g=[],p=0;m.length&&(f.tracks=m.map(x=>{let _=++p;g.length===0&&x.track.mode==="showing"&&g.push(_);let I=new chrome.cast.media.Track(_,chrome.cast.media.TrackType.TEXT);return I.trackContentId=x.src,I.trackContentType="text/vtt",I.subtype=x.kind==="captions"?chrome.cast.media.TextTrackType.CAPTIONS:chrome.cast.media.TextTrackType.SUBTITLES,I.name=x.label,I.language=x.srclang,I})),this.castStreamType==="live"?f.streamType=chrome.cast.media.StreamType.LIVE:f.streamType=chrome.cast.media.StreamType.BUFFERED,f.metadata=new chrome.cast.media.GenericMediaMetadata,f.metadata.title=this.title,f.metadata.images=[{url:this.poster}];let v=new chrome.cast.media.LoadRequest(f);v.currentTime=(E=super.currentTime)!=null?E:0,v.autoplay=!S(this,i).paused,v.activeTrackIds=g,await((T=rs())==null?void 0:T.loadMedia(v)),this.dispatchEvent(new Event("volumechange"))}play(){var f;if(S(this,o,re)){S(this,o,re).isPaused&&((f=S(this,o,re).controller)==null||f.playOrPause());return}return super.play()}pause(){var f;if(S(this,o,re)){S(this,o,re).isPaused||(f=S(this,o,re).controller)==null||f.playOrPause();return}super.pause()}get castOptions(){return S(this,r)}get castReceiver(){var f;return(f=this.getAttribute("cast-receiver"))!=null?f:void 0}set castReceiver(f){this.castReceiver!=f&&this.setAttribute("cast-receiver",`${f}`)}get castSrc(){var f,m,g;return(g=(m=this.getAttribute("cast-src"))!=null?m:(f=this.querySelector("source"))==null?void 0:f.src)!=null?g:this.currentSrc}set castSrc(f){this.castSrc!=f&&this.setAttribute("cast-src",`${f}`)}get castContentType(){var f;return(f=this.getAttribute("cast-content-type"))!=null?f:void 0}set castContentType(f){this.setAttribute("cast-content-type",`${f}`)}get castStreamType(){var f,m;return(m=(f=this.getAttribute("cast-stream-type"))!=null?f:this.streamType)!=null?m:void 0}set castStreamType(f){this.setAttribute("cast-stream-type",`${f}`)}get castCustomData(){return S(this,n)}set castCustomData(f){let m=typeof f;if(!["object","undefined"].includes(m)){console.error(`castCustomData must be nullish or an object but value was of type ${m}`);return}G(this,n,f)}get readyState(){if(S(this,o,re))switch(S(this,o,re).playerState){case chrome.cast.media.PlayerState.IDLE:return 0;case chrome.cast.media.PlayerState.BUFFERING:return 2;default:return 3}return super.readyState}get paused(){return S(this,o,re)?S(this,o,re).isPaused:super.paused}get muted(){var f;return S(this,o,re)?(f=S(this,o,re))==null?void 0:f.isMuted:super.muted}set muted(f){var m;if(S(this,o,re)){(f&&!S(this,o,re).isMuted||!f&&S(this,o,re).isMuted)&&((m=S(this,o,re).controller)==null||m.muteOrUnmute());return}super.muted=f}get volume(){var f,m;return S(this,o,re)?(m=(f=S(this,o,re))==null?void 0:f.volumeLevel)!=null?m:1:super.volume}set volume(f){var m;if(S(this,o,re)){S(this,o,re).volumeLevel=+f,(m=S(this,o,re).controller)==null||m.setVolumeLevel();return}super.volume=f}get duration(){var f,m,g;return S(this,o,re)&&((f=S(this,o,re))!=null&&f.isMediaLoaded)?(g=(m=S(this,o,re))==null?void 0:m.duration)!=null?g:NaN:super.duration}get currentTime(){var f,m,g;return S(this,o,re)&&((f=S(this,o,re))!=null&&f.isMediaLoaded)?(g=(m=S(this,o,re))==null?void 0:m.currentTime)!=null?g:0:super.currentTime}set currentTime(f){var m;if(S(this,o,re)){S(this,o,re).currentTime=f,(m=S(this,o,re).controller)==null||m.seek();return}super.currentTime=f}},i=new WeakMap,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakSet,re=function(){var f,m;return(m=(f=dt.get(this.remote))==null?void 0:f.getCastPlayer)==null?void 0:m.call(f)},c=new WeakSet,Ju=async function(){S(this,i).paused=Ts(t.prototype,this,"paused"),Ts(t.prototype,this,"pause").call(this),this.muted=Ts(t.prototype,this,"muted");try{await this.load()}catch(f){console.error(f)}},te(t,"observedAttributes",[...(e=s.observedAttributes)!=null?e:[],"cast-src","cast-content-type","cast-stream-type","cast-receiver"]),t};var mt=class extends Event{constructor(t,i){super(t);te(this,"track");this.track=i.track}};var Ro=new WeakMap;function U(s){var e;return(e=Ro.get(s))!=null?e:ey(s,{})}function ey(s,e){let t=Ro.get(s);return t||Ro.set(s,t={}),Object.assign(t,e)}function Ur(s,e){let t=s.videoTracks;U(e).media=s,U(e).renditionSet||(U(e).renditionSet=new Set);let i=U(t).trackSet;i.add(e);let r=i.size-1;r in ii.prototype||Object.defineProperty(ii.prototype,r,{get(){return[...U(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new mt("addtrack",{track:e}))})}function Br(s){var i;let e=(i=U(s).media)==null?void 0:i.videoTracks;if(!e)return;U(e).trackSet.delete(s),queueMicrotask(()=>{e.dispatchEvent(new mt("removetrack",{track:s}))})}function Zu(s){var i;let e=(i=U(s).media.videoTracks)!=null?i:[],t=!1;for(let r of e)r!==s&&(r.selected=!1,t=!0);if(t){if(U(e).changeRequested)return;U(e).changeRequested=!0,queueMicrotask(()=>{delete U(e).changeRequested,e.dispatchEvent(new Event("change"))})}}var Rt,Lt,It,ti,cs,ii=class extends EventTarget{constructor(){super();F(this,ti);F(this,Rt,void 0);F(this,Lt,void 0);F(this,It,void 0);U(this).trackSet=new Set}[Symbol.iterator](){return S(this,ti,cs).values()}get length(){return S(this,ti,cs).size}getTrackById(t){var i;return(i=[...S(this,ti,cs)].find(r=>r.id===t))!=null?i:null}get selectedIndex(){return[...S(this,ti,cs)].findIndex(t=>t.selected)}get onaddtrack(){return S(this,Rt)}set onaddtrack(t){S(this,Rt)&&(this.removeEventListener("addtrack",S(this,Rt)),G(this,Rt,void 0)),typeof t=="function"&&(G(this,Rt,t),this.addEventListener("addtrack",t))}get onremovetrack(){return S(this,Lt)}set onremovetrack(t){S(this,Lt)&&(this.removeEventListener("removetrack",S(this,Lt)),G(this,Lt,void 0)),typeof t=="function"&&(G(this,Lt,t),this.addEventListener("removetrack",t))}get onchange(){return S(this,It)}set onchange(t){S(this,It)&&(this.removeEventListener("change",S(this,It)),G(this,It,void 0)),typeof t=="function"&&(G(this,It,t),this.addEventListener("change",t))}};Rt=new WeakMap,Lt=new WeakMap,It=new WeakMap,ti=new WeakSet,cs=function(){return U(this).trackSet};var gt=class extends Event{constructor(t,i){super(t);te(this,"rendition");this.rendition=i.rendition}};function ed(s,e){let t=U(s).media.videoRenditions;U(e).media=U(s).media,U(e).track=s;let i=U(s).renditionSet;i.add(e);let r=i.size-1;r in si.prototype||Object.defineProperty(si.prototype,r,{get(){return Ti(this)[r]}}),queueMicrotask(()=>{s.selected&&t.dispatchEvent(new gt("addrendition",{rendition:e}))})}function td(s){let e=U(s).media.videoRenditions,t=U(s).track;U(t).renditionSet.delete(s),queueMicrotask(()=>{U(s).track.selected&&e.dispatchEvent(new gt("removerendition",{rendition:s}))})}function id(s){let e=U(s).media.videoRenditions;!e||U(e).changeRequested||(U(e).changeRequested=!0,queueMicrotask(()=>{delete U(e).changeRequested,U(s).track.selected&&e.dispatchEvent(new Event("change"))}))}function Ti(s){return[...U(s).media.videoTracks].filter(t=>t.selected).flatMap(t=>[...U(t).renditionSet])}var Dt,kt,wt,si=class extends EventTarget{constructor(){super(...arguments);F(this,Dt,void 0);F(this,kt,void 0);F(this,wt,void 0)}[Symbol.iterator](){return Ti(this).values()}get length(){return Ti(this).length}getRenditionById(t){var i;return(i=Ti(this).find(r=>`${r.id}`==`${t}`))!=null?i:null}get selectedIndex(){return Ti(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[i,r]of Ti(this).entries())r.selected=i===t}get onaddrendition(){return S(this,Dt)}set onaddrendition(t){S(this,Dt)&&(this.removeEventListener("addrendition",S(this,Dt)),G(this,Dt,void 0)),typeof t=="function"&&(G(this,Dt,t),this.addEventListener("addrendition",t))}get onremoverendition(){return S(this,kt)}set onremoverendition(t){S(this,kt)&&(this.removeEventListener("removerendition",S(this,kt)),G(this,kt,void 0)),typeof t=="function"&&(G(this,kt,t),this.addEventListener("removerendition",t))}get onchange(){return S(this,wt)}set onchange(t){S(this,wt)&&(this.removeEventListener("change",S(this,wt)),G(this,wt,void 0)),typeof t=="function"&&(G(this,wt,t),this.addEventListener("change",t))}};Dt=new WeakMap,kt=new WeakMap,wt=new WeakMap;var xi,us=class{constructor(){te(this,"src");te(this,"id");te(this,"width");te(this,"height");te(this,"bitrate");te(this,"frameRate");te(this,"codec");F(this,xi,!1)}get selected(){return S(this,xi)}set selected(e){S(this,xi)!==e&&(G(this,xi,e),id(this))}};xi=new WeakMap;var _i,Si=class{constructor(){te(this,"id");te(this,"kind");te(this,"label","");te(this,"language","");te(this,"sourceBuffer");F(this,_i,!1)}addRendition(e,t,i,r,n,a){let o=new us;return o.src=e,o.width=t,o.height=i,o.frameRate=a,o.bitrate=n,o.codec=r,ed(this,o),o}removeRendition(e){td(e)}get selected(){return S(this,_i)}set selected(e){S(this,_i)!==e&&(G(this,_i,e),e===!0&&Zu(this))}};_i=new WeakMap;function sd(s,e){let t=U(s).media.audioRenditions;U(e).media=U(s).media,U(e).track=s;let i=U(s).renditionSet;i.add(e);let r=i.size-1;r in ri.prototype||Object.defineProperty(ri.prototype,r,{get(){return bi(this)[r]}}),queueMicrotask(()=>{s.enabled&&t.dispatchEvent(new gt("addrendition",{rendition:e}))})}function rd(s){let e=U(s).media.audioRenditions,t=U(s).track;U(t).renditionSet.delete(s),queueMicrotask(()=>{U(s).track.enabled&&e.dispatchEvent(new gt("removerendition",{rendition:s}))})}function nd(s){let e=U(s).media.audioRenditions;!e||U(e).changeRequested||(U(e).changeRequested=!0,queueMicrotask(()=>{delete U(e).changeRequested,U(s).track.enabled&&e.dispatchEvent(new Event("change"))}))}function bi(s){return[...U(s).media.audioTracks].filter(t=>t.enabled).flatMap(t=>[...U(t).renditionSet])}var Ct,Pt,Ot,ri=class extends EventTarget{constructor(){super(...arguments);F(this,Ct,void 0);F(this,Pt,void 0);F(this,Ot,void 0)}[Symbol.iterator](){return bi(this).values()}get length(){return bi(this).length}getRenditionById(t){var i;return(i=bi(this).find(r=>`${r.id}`==`${t}`))!=null?i:null}get selectedIndex(){return bi(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[i,r]of bi(this).entries())r.selected=i===t}get onaddrendition(){return S(this,Ct)}set onaddrendition(t){S(this,Ct)&&(this.removeEventListener("addrendition",S(this,Ct)),G(this,Ct,void 0)),typeof t=="function"&&(G(this,Ct,t),this.addEventListener("addrendition",t))}get onremoverendition(){return S(this,Pt)}set onremoverendition(t){S(this,Pt)&&(this.removeEventListener("removerendition",S(this,Pt)),G(this,Pt,void 0)),typeof t=="function"&&(G(this,Pt,t),this.addEventListener("removerendition",t))}get onchange(){return S(this,Ot)}set onchange(t){S(this,Ot)&&(this.removeEventListener("change",S(this,Ot)),G(this,Ot,void 0)),typeof t=="function"&&(G(this,Ot,t),this.addEventListener("change",t))}};Ct=new WeakMap,Pt=new WeakMap,Ot=new WeakMap;var Ai,ds=class{constructor(){te(this,"src");te(this,"id");te(this,"bitrate");te(this,"codec");F(this,Ai,!1)}get selected(){return S(this,Ai)}set selected(e){S(this,Ai)!==e&&(G(this,Ai,e),nd(this))}};Ai=new WeakMap;function Gr(s,e){let t=s.audioTracks;U(e).media=s,U(e).renditionSet||(U(e).renditionSet=new Set);let i=U(t).trackSet;i.add(e);let r=i.size-1;r in ni.prototype||Object.defineProperty(ni.prototype,r,{get(){return[...U(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new mt("addtrack",{track:e}))})}function Kr(s){var i;let e=(i=U(s).media)==null?void 0:i.audioTracks;if(!e)return;U(e).trackSet.delete(s),queueMicrotask(()=>{e.dispatchEvent(new mt("removetrack",{track:s}))})}function ad(s){let e=U(s).media.audioTracks;!e||U(e).changeRequested||(U(e).changeRequested=!0,queueMicrotask(()=>{delete U(e).changeRequested,e.dispatchEvent(new Event("change"))}))}var Mt,Nt,Ft,Ri,$r,ni=class extends EventTarget{constructor(){super();F(this,Ri);F(this,Mt,void 0);F(this,Nt,void 0);F(this,Ft,void 0);U(this).trackSet=new Set}[Symbol.iterator](){return S(this,Ri,$r).values()}get length(){return S(this,Ri,$r).size}getTrackById(t){var i;return(i=[...S(this,Ri,$r)].find(r=>r.id===t))!=null?i:null}get onaddtrack(){return S(this,Mt)}set onaddtrack(t){S(this,Mt)&&(this.removeEventListener("addtrack",S(this,Mt)),G(this,Mt,void 0)),typeof t=="function"&&(G(this,Mt,t),this.addEventListener("addtrack",t))}get onremovetrack(){return S(this,Nt)}set onremovetrack(t){S(this,Nt)&&(this.removeEventListener("removetrack",S(this,Nt)),G(this,Nt,void 0)),typeof t=="function"&&(G(this,Nt,t),this.addEventListener("removetrack",t))}get onchange(){return S(this,Ft)}set onchange(t){S(this,Ft)&&(this.removeEventListener("change",S(this,Ft)),G(this,Ft,void 0)),typeof t=="function"&&(G(this,Ft,t),this.addEventListener("change",t))}};Mt=new WeakMap,Nt=new WeakMap,Ft=new WeakMap,Ri=new WeakSet,$r=function(){return U(this).trackSet};var Li,Ii=class{constructor(){te(this,"id");te(this,"kind");te(this,"label","");te(this,"language","");te(this,"sourceBuffer");F(this,Li,!1)}addRendition(e,t,i){let r=new ds;return r.src=e,r.codec=t,r.bitrate=i,sd(this,r),r}removeRendition(e){rd(e)}get enabled(){return S(this,Li)}set enabled(e){S(this,Li)!==e&&(G(this,Li,e),ad(this))}};Li=new WeakMap;var od=Hr(globalThis.HTMLMediaElement,"video"),ld=Hr(globalThis.HTMLMediaElement,"audio");function cd(s){if(!(s!=null&&s.prototype))return s;let e=Hr(s,"video");(!e||`${e}`.includes("[native code]"))&&Object.defineProperty(s.prototype,"videoTracks",{get(){return ty(this)}});let t=Hr(s,"audio");(!t||`${t}`.includes("[native code]"))&&Object.defineProperty(s.prototype,"audioTracks",{get(){return iy(this)}}),"addVideoTrack"in s.prototype||(s.prototype.addVideoTrack=function(n,a="",o=""){let l=new Si;return l.kind=n,l.label=a,l.language=o,Ur(this,l),l}),"removeVideoTrack"in s.prototype||(s.prototype.removeVideoTrack=Br),"addAudioTrack"in s.prototype||(s.prototype.addAudioTrack=function(n,a="",o=""){let l=new Ii;return l.kind=n,l.label=a,l.language=o,Gr(this,l),l}),"removeAudioTrack"in s.prototype||(s.prototype.removeAudioTrack=Kr),"videoRenditions"in s.prototype||Object.defineProperty(s.prototype,"videoRenditions",{get(){return i(this)}});let i=n=>{let a=U(n).videoRenditions;return a||(a=new si,U(a).media=n,U(n).videoRenditions=a),a};"audioRenditions"in s.prototype||Object.defineProperty(s.prototype,"audioRenditions",{get(){return r(this)}});let r=n=>{let a=U(n).audioRenditions;return a||(a=new ri,U(a).media=n,U(n).audioRenditions=a),a};return s}function Hr(s,e){var t;if(s!=null&&s.prototype)return(t=Object.getOwnPropertyDescriptor(s.prototype,`${e}Tracks`))==null?void 0:t.get}function ty(s){var t;let e=U(s).videoTracks;if(!e&&(e=new ii,U(s).videoTracks=e,od)){let i=od.call((t=s.nativeEl)!=null?t:s);for(let r of i)Ur(s,r);i.addEventListener("change",()=>{e.dispatchEvent(new Event("change"))}),i.addEventListener("addtrack",r=>{if([...e].some(n=>n instanceof Si)){for(let n of i)Br(n);return}Ur(s,r.track)}),i.addEventListener("removetrack",r=>{Br(r.track)})}return e}function iy(s){var t;let e=U(s).audioTracks;if(!e&&(e=new ni,U(s).audioTracks=e,ld)){let i=ld.call((t=s.nativeEl)!=null?t:s);for(let r of i)Gr(s,r);i.addEventListener("change",()=>{e.dispatchEvent(new Event("change"))}),i.addEventListener("addtrack",r=>{if([...e].some(n=>n instanceof Ii)){for(let n of i)Kr(n);return}Gr(s,r.track)}),i.addEventListener("removetrack",r=>{Kr(r.track)})}return e}To.push("castchange","entercast","leavecast");var M={BEACON_COLLECTION_DOMAIN:"beacon-collection-domain",CUSTOM_DOMAIN:"custom-domain",DEBUG:"debug",DISABLE_TRACKING:"disable-tracking",DISABLE_COOKIES:"disable-cookies",DRM_TOKEN:"drm-token",PLAYBACK_TOKEN:"playback-token",ENV_KEY:"env-key",MAX_RESOLUTION:"max-resolution",MIN_RESOLUTION:"min-resolution",RENDITION_ORDER:"rendition-order",PROGRAM_START_TIME:"program-start-time",PROGRAM_END_TIME:"program-end-time",ASSET_START_TIME:"asset-start-time",ASSET_END_TIME:"asset-end-time",METADATA_URL:"metadata-url",PLAYBACK_ID:"playback-id",PLAYER_SOFTWARE_NAME:"player-software-name",PLAYER_SOFTWARE_VERSION:"player-software-version",PREFER_CMCD:"prefer-cmcd",PREFER_PLAYBACK:"prefer-playback",START_TIME:"start-time",STREAM_TYPE:"stream-type",TARGET_LIVE_WINDOW:"target-live-window",LIVE_EDGE_OFFSET:"live-edge-offset",TYPE:"type"},sy=Object.values(M),ry=Pu(),ny="mux-video",Xe,Di,fs,ki,ms,gs,ps,ys,vs,wi,Vr,Lo=class extends Dr{constructor(){super();F(this,wi);F(this,Xe,void 0);F(this,Di,void 0);F(this,fs,void 0);F(this,ki,{});F(this,ms,{});F(this,gs,void 0);F(this,ps,void 0);F(this,ys,void 0);F(this,vs,void 0);G(this,fs,xu())}static get observedAttributes(){var t;return[...sy,...(t=Dr.observedAttributes)!=null?t:[]]}get preferCmcd(){var t;return(t=this.getAttribute(M.PREFER_CMCD))!=null?t:void 0}set preferCmcd(t){t!==this.preferCmcd&&(t?ao.includes(t)?this.setAttribute(M.PREFER_CMCD,t):console.warn(`Invalid value for preferCmcd. Must be one of ${ao.join()}`):this.removeAttribute(M.PREFER_CMCD))}get playerInitTime(){return S(this,fs)}get playerSoftwareName(){var t;return(t=S(this,ys))!=null?t:ny}set playerSoftwareName(t){G(this,ys,t)}get playerSoftwareVersion(){var t;return(t=S(this,ps))!=null?t:ry}set playerSoftwareVersion(t){G(this,ps,t)}get _hls(){var t;return(t=S(this,Xe))==null?void 0:t.engine}get mux(){var t;return(t=this.nativeEl)==null?void 0:t.mux}get error(){var t;return(t=go(this.nativeEl))!=null?t:null}get errorTranslator(){return S(this,vs)}set errorTranslator(t){G(this,vs,t)}get src(){return this.getAttribute("src")}set src(t){t!==this.src&&(t==null?this.removeAttribute("src"):this.setAttribute("src",t))}get type(){var t;return(t=this.getAttribute(M.TYPE))!=null?t:void 0}set type(t){t!==this.type&&(t?this.setAttribute(M.TYPE,t):this.removeAttribute(M.TYPE))}get autoplay(){let t=this.getAttribute("autoplay");return t===null?!1:t===""?!0:t}set autoplay(t){let i=this.autoplay;t!==i&&(t?this.setAttribute("autoplay",typeof t=="string"?t:""):this.removeAttribute("autoplay"))}get preload(){let t=this.getAttribute("preload");return t===""?"auto":["none","metadata","auto"].includes(t)?t:super.preload}set preload(t){t!=this.getAttribute("preload")&&(["","none","metadata","auto"].includes(t)?this.setAttribute("preload",t):this.removeAttribute("preload"))}get debug(){return this.getAttribute(M.DEBUG)!=null}set debug(t){t!==this.debug&&(t?this.setAttribute(M.DEBUG,""):this.removeAttribute(M.DEBUG))}get disableTracking(){return this.hasAttribute(M.DISABLE_TRACKING)}set disableTracking(t){t!==this.disableTracking&&this.toggleAttribute(M.DISABLE_TRACKING,!!t)}get disableCookies(){return this.hasAttribute(M.DISABLE_COOKIES)}set disableCookies(t){t!==this.disableCookies&&(t?this.setAttribute(M.DISABLE_COOKIES,""):this.removeAttribute(M.DISABLE_COOKIES))}get startTime(){let t=this.getAttribute(M.START_TIME);if(t==null)return;let i=+t;return Number.isNaN(i)?void 0:i}set startTime(t){t!==this.startTime&&(t==null?this.removeAttribute(M.START_TIME):this.setAttribute(M.START_TIME,`${t}`))}get playbackId(){var t;return this.hasAttribute(M.PLAYBACK_ID)?this.getAttribute(M.PLAYBACK_ID):(t=mo(this.src))!=null?t:void 0}set playbackId(t){t!==this.playbackId&&(t?this.setAttribute(M.PLAYBACK_ID,t):this.removeAttribute(M.PLAYBACK_ID))}get maxResolution(){var t;return(t=this.getAttribute(M.MAX_RESOLUTION))!=null?t:void 0}set maxResolution(t){t!==this.maxResolution&&(t?this.setAttribute(M.MAX_RESOLUTION,t):this.removeAttribute(M.MAX_RESOLUTION))}get minResolution(){var t;return(t=this.getAttribute(M.MIN_RESOLUTION))!=null?t:void 0}set minResolution(t){t!==this.minResolution&&(t?this.setAttribute(M.MIN_RESOLUTION,t):this.removeAttribute(M.MIN_RESOLUTION))}get renditionOrder(){var t;return(t=this.getAttribute(M.RENDITION_ORDER))!=null?t:void 0}set renditionOrder(t){t!==this.renditionOrder&&(t?this.setAttribute(M.RENDITION_ORDER,t):this.removeAttribute(M.RENDITION_ORDER))}get programStartTime(){let t=this.getAttribute(M.PROGRAM_START_TIME);if(t==null)return;let i=+t;return Number.isNaN(i)?void 0:i}set programStartTime(t){t==null?this.removeAttribute(M.PROGRAM_START_TIME):this.setAttribute(M.PROGRAM_START_TIME,`${t}`)}get programEndTime(){let t=this.getAttribute(M.PROGRAM_END_TIME);if(t==null)return;let i=+t;return Number.isNaN(i)?void 0:i}set programEndTime(t){t==null?this.removeAttribute(M.PROGRAM_END_TIME):this.setAttribute(M.PROGRAM_END_TIME,`${t}`)}get assetStartTime(){let t=this.getAttribute(M.ASSET_START_TIME);if(t==null)return;let i=+t;return Number.isNaN(i)?void 0:i}set assetStartTime(t){t==null?this.removeAttribute(M.ASSET_START_TIME):this.setAttribute(M.ASSET_START_TIME,`${t}`)}get assetEndTime(){let t=this.getAttribute(M.ASSET_END_TIME);if(t==null)return;let i=+t;return Number.isNaN(i)?void 0:i}set assetEndTime(t){t==null?this.removeAttribute(M.ASSET_END_TIME):this.setAttribute(M.ASSET_END_TIME,`${t}`)}get customDomain(){var t;return(t=this.getAttribute(M.CUSTOM_DOMAIN))!=null?t:void 0}set customDomain(t){t!==this.customDomain&&(t?this.setAttribute(M.CUSTOM_DOMAIN,t):this.removeAttribute(M.CUSTOM_DOMAIN))}get drmToken(){var t;return(t=this.getAttribute(M.DRM_TOKEN))!=null?t:void 0}set drmToken(t){t!==this.drmToken&&(t?this.setAttribute(M.DRM_TOKEN,t):this.removeAttribute(M.DRM_TOKEN))}get playbackToken(){var t,i,r,n;if(this.hasAttribute(M.PLAYBACK_TOKEN))return(t=this.getAttribute(M.PLAYBACK_TOKEN))!=null?t:void 0;if(this.hasAttribute(M.PLAYBACK_ID)){let[,a]=Ar((i=this.playbackId)!=null?i:"");return(r=new URLSearchParams(a).get("token"))!=null?r:void 0}if(this.src)return(n=new URLSearchParams(this.src).get("token"))!=null?n:void 0}set playbackToken(t){t!==this.playbackToken&&(t?this.setAttribute(M.PLAYBACK_TOKEN,t):this.removeAttribute(M.PLAYBACK_TOKEN))}get tokens(){let t=this.getAttribute(M.PLAYBACK_TOKEN),i=this.getAttribute(M.DRM_TOKEN);return{...S(this,ms),...t!=null?{playback:t}:{},...i!=null?{drm:i}:{}}}set tokens(t){G(this,ms,t!=null?t:{})}get ended(){return yo(this.nativeEl,this._hls)}get envKey(){var t;return(t=this.getAttribute(M.ENV_KEY))!=null?t:void 0}set envKey(t){t!==this.envKey&&(t?this.setAttribute(M.ENV_KEY,t):this.removeAttribute(M.ENV_KEY))}get beaconCollectionDomain(){var t;return(t=this.getAttribute(M.BEACON_COLLECTION_DOMAIN))!=null?t:void 0}set beaconCollectionDomain(t){t!==this.beaconCollectionDomain&&(t?this.setAttribute(M.BEACON_COLLECTION_DOMAIN,t):this.removeAttribute(M.BEACON_COLLECTION_DOMAIN))}get streamType(){var t;return(t=this.getAttribute(M.STREAM_TYPE))!=null?t:br(this.nativeEl)}set streamType(t){t!==this.streamType&&(t?this.setAttribute(M.STREAM_TYPE,t):this.removeAttribute(M.STREAM_TYPE))}get targetLiveWindow(){return this.hasAttribute(M.TARGET_LIVE_WINDOW)?+this.getAttribute(M.TARGET_LIVE_WINDOW):Su(this.nativeEl)}set targetLiveWindow(t){t!=this.targetLiveWindow&&(t==null?this.removeAttribute(M.TARGET_LIVE_WINDOW):this.setAttribute(M.TARGET_LIVE_WINDOW,`${+t}`))}get liveEdgeStart(){var t,i;if(this.hasAttribute(M.LIVE_EDGE_OFFSET)){let{liveEdgeOffset:r}=this,n=(t=this.nativeEl.seekable.end(0))!=null?t:0,a=(i=this.nativeEl.seekable.start(0))!=null?i:0;return Math.max(a,n-r)}return bu(this.nativeEl)}get liveEdgeOffset(){if(this.hasAttribute(M.LIVE_EDGE_OFFSET))return+this.getAttribute(M.LIVE_EDGE_OFFSET)}set liveEdgeOffset(t){t!=this.targetLiveWindow&&(t==null?this.removeAttribute(M.LIVE_EDGE_OFFSET):this.setAttribute(M.LIVE_EDGE_OFFSET,`${+t}`))}get seekable(){return Ir(this.nativeEl)}async addCuePoints(t){return lo(this.nativeEl,t)}get activeCuePoint(){return co(this.nativeEl)}get cuePoints(){return gu(this.nativeEl)}async addChapters(t){return ho(this.nativeEl,t)}get activeChapter(){return fo(this.nativeEl)}get chapters(){return yu(this.nativeEl)}getStartDate(){return vu(this.nativeEl,this._hls)}get currentPdt(){return Eu(this.nativeEl,this._hls)}get preferPlayback(){let t=this.getAttribute(M.PREFER_PLAYBACK);if(t===Xt.MSE||t===Xt.NATIVE)return t}set preferPlayback(t){t!==this.preferPlayback&&(t===Xt.MSE||t===Xt.NATIVE?this.setAttribute(M.PREFER_PLAYBACK,t):this.removeAttribute(M.PREFER_PLAYBACK))}get metadata(){return{...this.getAttributeNames().filter(i=>i.startsWith("metadata-")&&![M.METADATA_URL].includes(i)).reduce((i,r)=>{let n=this.getAttribute(r);return n!=null&&(i[r.replace(/^metadata-/,"").replace(/-/g,"_")]=n),i},{}),...S(this,ki)}}set metadata(t){G(this,ki,t!=null?t:{}),this.mux&&this.mux.emit("hb",S(this,ki))}get _hlsConfig(){return S(this,gs)}set _hlsConfig(t){G(this,gs,t)}load(){G(this,Xe,Lu(this,this.nativeEl,S(this,Xe)))}unload(){vo(this.nativeEl,S(this,Xe)),G(this,Xe,void 0)}attributeChangedCallback(t,i,r){var a,o;switch(Dr.observedAttributes.includes(t)&&!["src","autoplay","preload"].includes(t)&&super.attributeChangedCallback(t,i,r),t){case M.PLAYER_SOFTWARE_NAME:this.playerSoftwareName=r!=null?r:void 0;break;case M.PLAYER_SOFTWARE_VERSION:this.playerSoftwareVersion=r!=null?r:void 0;break;case"src":{let l=!!i,c=!!r;!l&&c?ce(this,wi,Vr).call(this):l&&!c?this.unload():l&&c&&(this.unload(),ce(this,wi,Vr).call(this));break}case"autoplay":if(r===i)break;(a=S(this,Xe))==null||a.setAutoplay(this.autoplay);break;case"preload":if(r===i)break;(o=S(this,Xe))==null||o.setPreload(r);break;case M.PLAYBACK_ID:this.src=_u(this);break;case M.DEBUG:{let l=this.debug;this.mux&&console.info("Cannot toggle debug mode of mux data after initialization. Make sure you set all metadata to override before setting the src."),this._hls&&(this._hls.config.debug=l);break}case M.METADATA_URL:r&&fetch(r).then(l=>l.json()).then(l=>this.metadata=l).catch(()=>console.error(`Unable to load or parse metadata JSON from metadata-url ${r}!`));break;case M.STREAM_TYPE:(r==null||r!==i)&&this.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}));break;case M.TARGET_LIVE_WINDOW:(r==null||r!==i)&&this.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0,detail:this.targetLiveWindow}));break;default:break}}connectedCallback(){var t;(t=super.connectedCallback)==null||t.call(this),this.nativeEl&&this.src&&!S(this,Xe)&&ce(this,wi,Vr).call(this)}disconnectedCallback(){this.unload()}};Xe=new WeakMap,Di=new WeakMap,fs=new WeakMap,ki=new WeakMap,ms=new WeakMap,gs=new WeakMap,ps=new WeakMap,ys=new WeakMap,vs=new WeakMap,wi=new WeakSet,Vr=async function(){S(this,Di)||(await G(this,Di,Promise.resolve()),G(this,Di,null),this.load())};var Es,hs=class extends Qu(cd(Lo)){constructor(){super(...arguments);F(this,Es,void 0)}get muxCastCustomData(){return{mux:{playbackId:this.playbackId,minResolution:this.minResolution,maxResolution:this.maxResolution,renditionOrder:this.renditionOrder,customDomain:this.customDomain,tokens:{drm:this.drmToken},envKey:this.envKey,metadata:this.metadata,disableCookies:this.disableCookies,disableTracking:this.disableTracking,beaconCollectionDomain:this.beaconCollectionDomain,startTime:this.startTime,preferCmcd:this.preferCmcd}}}get castCustomData(){var t;return(t=S(this,Es))!=null?t:this.muxCastCustomData}set castCustomData(t){G(this,Es,t)}};Es=new WeakMap;xs.customElements.get("mux-video")||(xs.customElements.define("mux-video",hs),xs.MuxVideoElement=hs);var zv=hs;export{M as Attributes,V as MediaError,To as VideoEvents,zv as default}; /*! Bundled license information: mux-embed/dist/mux.mjs: (*! * JavaScript Cookie v2.1.3 * https://github.com/js-cookie/js-cookie * * Copyright 2006, 2015 Klaus Hartl & Fagner Brack * Released under the MIT license *) */ //# sourceMappingURL=mux-video.mjs.map